Compare commits
155
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 | ||
|
|
f1a6c32e0c | ||
|
|
cf5a3e7d3d | ||
|
|
89f45082fb | ||
|
|
0ad6ac70ff | ||
|
|
e8e0decc6c | ||
|
|
57aaf77162 | ||
|
|
a3eebedb02 | ||
|
|
f8e5cd90a5 | ||
|
|
07ce24143b | ||
|
|
3d092b02f3 | ||
|
|
bf5e065520 | ||
|
|
08178e74d2 | ||
|
|
c66fcff906 | ||
|
|
b0dd0e509d | ||
|
|
719da6e921 | ||
|
|
e4b3d0a9a9 | ||
|
|
c0e231a32b | ||
|
|
af9f9a25da | ||
|
|
0a465bc7e1 | ||
|
|
aec735e09e | ||
|
|
9ce6d5f26e | ||
|
|
f4b4fb0562 | ||
|
|
aa22fad67d | ||
|
|
548bb4ce70 | ||
|
|
b6871b3618 | ||
|
|
fe5e816551 | ||
|
|
20d2a281b1 | ||
|
|
e2ae0c660a | ||
|
|
9e8ae16597 | ||
|
|
e5284a79c9 | ||
|
|
79dad5dfb0 | ||
|
|
a511c16fb1 | ||
|
|
98a1214a4d | ||
|
|
be459c45cf | ||
|
|
328ef2938c | ||
|
|
21f3f49078 | ||
|
|
882ad3b8cf | ||
|
|
d8b7d8bc2e | ||
|
|
c1692535a5 | ||
|
|
af0e326747 | ||
|
|
6cdaa9738a | ||
|
|
1e5d0c4517 | ||
|
|
127f5ca287 | ||
|
|
f51b775fd9 | ||
|
|
0015b92591 | ||
|
|
37e1f1811f | ||
|
|
deb6448739 | ||
|
|
bfb3224684 | ||
|
|
aed1f33935 | ||
|
|
33192efa33 | ||
|
|
d48435b948 | ||
|
|
daa4f79ea0 | ||
|
|
c70a566514 | ||
|
|
b99d3a7ff1 | ||
|
|
30cbb080b0 | ||
|
|
d8eec59d5d | ||
|
|
be89e2986b | ||
|
|
916af84651 | ||
|
|
567b5ecd4f | ||
|
|
b21d8d3e88 | ||
|
|
4e5ab529de | ||
|
|
3b1ffda3b2 | ||
|
|
cdf58044a8 | ||
|
|
727c3fde67 | ||
|
|
de880fb9f0 | ||
|
|
e9fdf7d538 | ||
|
|
57f221868d | ||
|
|
ae7d1a54cb | ||
|
|
71b075b365 | ||
|
|
c054cf99fe | ||
|
|
98a742f024 | ||
|
|
fb40bc548e | ||
|
|
d06c1954a5 | ||
|
|
545d487fea | ||
|
|
62f0812aae | ||
|
|
e0dda3ea0c | ||
|
|
7628f219e2 | ||
|
|
1d7a54c866 | ||
|
|
6c55493acb | ||
|
|
42bcac251b | ||
|
|
bb791138cd | ||
|
|
1fc509ea13 | ||
|
|
90a1b930a3 | ||
|
|
9011d58355 | ||
|
|
f2c0f203f6 | ||
|
|
3f5746dd7d | ||
|
|
adce95ead4 | ||
|
|
84d7ca0122 | ||
|
|
053af573fc | ||
|
|
06f34bec45 | ||
|
|
c1641fdb38 | ||
|
|
9115af350e | ||
|
|
77cf3612d9 | ||
|
|
07c7343f94 | ||
|
|
530f751f02 | ||
|
|
9a005cabe9 | ||
|
|
f7eb502d9d | ||
|
|
a407cfb514 | ||
|
|
ff43d07b6d | ||
|
|
340b5f22b7 | ||
|
|
b4a90131bb | ||
|
|
90149ddb4e | ||
|
|
1f09f0cf68 | ||
|
|
8035e7aecb | ||
|
|
cea32deba2 | ||
|
|
b02358e3a0 | ||
|
|
79320f27c9 | ||
|
|
52ca2f7339 | ||
|
|
78e54248e3 | ||
|
|
fc82604947 | ||
|
|
40bb0feaf8 | ||
|
|
0afb6a9481 | ||
|
|
57f72a473f | ||
|
|
876fbb9980 | ||
|
|
bee09f7c29 | ||
|
|
c31aef4131 | ||
|
|
53a36e7974 | ||
|
|
60e74c4916 | ||
|
|
1d24f912ae | ||
|
|
f9591c512c | ||
|
|
f74396e97b | ||
|
|
1127eeebb8 | ||
|
|
e9590e8b04 | ||
|
|
fd0bc89771 | ||
|
|
32a38b46fe | ||
|
|
e5f9d8cfdf | ||
|
|
ecd6b30626 | ||
|
|
31da701fe7 | ||
|
|
9d875b3935 | ||
|
|
8cab4ffb42 | ||
|
|
61aeb5bf86 | ||
|
|
0821008d6e | ||
|
|
a4a24b77b9 | ||
|
|
897edab3cf |
@@ -88,6 +88,25 @@ class Organization(Durable, table=True):
|
|||||||
accounts: list["Account"] = Relationship(back_populates="organization")
|
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):
|
class Account(Durable, table=True):
|
||||||
@model_validator(mode="before")
|
@model_validator(mode="before")
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import logging
|
|||||||
import uuid
|
import uuid
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Response, status
|
from fastapi import APIRouter, Body, Depends, Query, Response, status
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
import inse.auth.service as auth_service
|
import inse.auth.service as auth_service
|
||||||
@@ -204,3 +204,32 @@ async def change_password(
|
|||||||
current_password=current_password,
|
current_password=current_password,
|
||||||
new_password=new_password,
|
new_password=new_password,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/can-fetch-gdpr-relevant-data",
|
||||||
|
summary="Check if user can fetch GDPR-relevant data",
|
||||||
|
description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.",
|
||||||
|
operation_id="canFetchGdprRelevantData",
|
||||||
|
)
|
||||||
|
async def can_fetch_gdpr_relevant_data(
|
||||||
|
session: SessionDep,
|
||||||
|
access_token: Annotated[
|
||||||
|
AccessTokenMetadata,
|
||||||
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
|
],
|
||||||
|
raw_oa_author_id: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(description="OpenAlex author ID to check access for"),
|
||||||
|
] = None,
|
||||||
|
raw_oa_institution_id: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(description="OpenAlex institution ID to check access for"),
|
||||||
|
] = 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,
|
IdTokenMetadata,
|
||||||
LoginResponse,
|
LoginResponse,
|
||||||
Organization,
|
Organization,
|
||||||
|
OrganizationInstitution,
|
||||||
OtkResponse,
|
OtkResponse,
|
||||||
RefreshTokenMetadata,
|
RefreshTokenMetadata,
|
||||||
Secret,
|
Secret,
|
||||||
@@ -31,6 +32,7 @@ from inse.auth.model import (
|
|||||||
effective_role_for_roles,
|
effective_role_for_roles,
|
||||||
normalize_roles,
|
normalize_roles,
|
||||||
)
|
)
|
||||||
|
from inse.authors.v2 import service as authors_service
|
||||||
from inse.config import get_settings
|
from inse.config import get_settings
|
||||||
from inse.database import get_session
|
from inse.database import get_session
|
||||||
|
|
||||||
@@ -97,9 +99,12 @@ def create_predefined_accounts(session: Session, file_path: str):
|
|||||||
with open(file_path, "r") as file:
|
with open(file_path, "r") as file:
|
||||||
data: dict[str, Any] = json.loads(file.read())
|
data: dict[str, Any] = json.loads(file.read())
|
||||||
for organization_data in data.get("organizations", []):
|
for organization_data in data.get("organizations", []):
|
||||||
organization_id = organization_data.get("id")
|
organization_id_value = organization_data.get("id")
|
||||||
if organization_id is not None:
|
organization_id = (
|
||||||
organization_id = uuid.UUID(organization_id)
|
uuid.UUID(organization_id_value)
|
||||||
|
if organization_id_value is not None
|
||||||
|
else uuid.uuid4()
|
||||||
|
)
|
||||||
organization_name = organization_data["name"]
|
organization_name = organization_data["name"]
|
||||||
openalex_institution_id = organization_data.get(
|
openalex_institution_id = organization_data.get(
|
||||||
"openalex_institution_id"
|
"openalex_institution_id"
|
||||||
@@ -112,6 +117,14 @@ def create_predefined_accounts(session: Session, file_path: str):
|
|||||||
openalex_institution_id=openalex_institution_id,
|
openalex_institution_id=openalex_institution_id,
|
||||||
)
|
)
|
||||||
session.add(organization)
|
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", []):
|
for account_data in data.get("accounts", []):
|
||||||
organization_id = uuid.UUID(account_data["organization_id"])
|
organization_id = uuid.UUID(account_data["organization_id"])
|
||||||
roles = normalize_roles(
|
roles = normalize_roles(
|
||||||
@@ -1451,3 +1464,101 @@ def change_password(
|
|||||||
logger.info("Password changed successfully for account %s", account.id)
|
logger.info("Password changed successfully for account %s", account.id)
|
||||||
|
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
) -> bool:
|
||||||
|
"""Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
access_token (AccessTokenMetadata): The access token for the user.
|
||||||
|
raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None.
|
||||||
|
raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise.
|
||||||
|
"""
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s",
|
||||||
|
access_token.effective_institution_id,
|
||||||
|
raw_oa_author_id,
|
||||||
|
raw_oa_institution_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not raw_oa_author_id and not raw_oa_institution_id:
|
||||||
|
logger.debug("No OpenAlex author ID or institution ID provided")
|
||||||
|
return False
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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 (
|
||||||
|
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",
|
||||||
|
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:
|
||||||
|
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 does not belong to any organization institution %s",
|
||||||
|
raw_oa_author_id,
|
||||||
|
organization_institution_ids,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import datetime as _dt
|
import datetime as _dt
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from fastapi import HTTPException, Response
|
from fastapi import HTTPException, Response
|
||||||
@@ -14,11 +15,16 @@ from inse.auth.model import (
|
|||||||
Account,
|
Account,
|
||||||
IdTokenMetadata,
|
IdTokenMetadata,
|
||||||
Organization,
|
Organization,
|
||||||
|
OrganizationInstitution,
|
||||||
RefreshTokenMetadata,
|
RefreshTokenMetadata,
|
||||||
Secret,
|
Secret,
|
||||||
SecretPurpose,
|
SecretPurpose,
|
||||||
UserRole,
|
UserRole,
|
||||||
)
|
)
|
||||||
|
from inse.organization_management.model import (
|
||||||
|
InstitutionAssociation,
|
||||||
|
InstitutionAssociationsResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture()
|
||||||
@@ -81,6 +87,74 @@ def test_hash_and_verify_password():
|
|||||||
assert auth_service._verify_password("wrong", h) is False
|
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):
|
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_hmac_key = "test-hmac-key"
|
||||||
config_module.settings.token_issuer_id = "test-issuer"
|
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
|
assert login_result.id_token.real_account_id == acc.id
|
||||||
|
|
||||||
raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY)
|
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)
|
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)
|
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(
|
refresh_payload = auth_service._verify_refresh_token(
|
||||||
raw_refresh_token=raw_refresh_token,
|
raw_refresh_token=raw_refresh_token,
|
||||||
session=in_memory_session,
|
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(
|
effective_account_id=uuid.UUID(
|
||||||
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
|
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
|
||||||
),
|
),
|
||||||
expires_at=_dt.datetime.fromtimestamp(
|
expires_at=_dt.datetime.fromtimestamp(refresh_payload["exp"], tz=_dt.UTC),
|
||||||
refresh_payload["exp"], tz=_dt.UTC
|
|
||||||
),
|
|
||||||
epoch=refresh_payload[auth_service.EPOCH_KEY],
|
epoch=refresh_payload[auth_service.EPOCH_KEY],
|
||||||
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
|
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
|
||||||
effective_organization_id=uuid.UUID(
|
effective_organization_id=uuid.UUID(
|
||||||
@@ -240,7 +316,9 @@ def test_access_and_refresh_token_preserve_multiple_roles(
|
|||||||
UserRole.USER.value,
|
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(
|
refresh_payload = auth_service._verify_refresh_token(
|
||||||
raw_refresh_token=raw_refresh_token,
|
raw_refresh_token=raw_refresh_token,
|
||||||
session=in_memory_session,
|
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)
|
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
|
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
|
||||||
email = "reset@example.com"
|
email = "reset@example.com"
|
||||||
password = "oldpw123"
|
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
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class DashboardInstitution(BaseModel):
|
||||||
|
id: str
|
||||||
|
display_name: str
|
||||||
|
|
||||||
|
|
||||||
class DashboardStatistics(BaseModel):
|
class DashboardStatistics(BaseModel):
|
||||||
institution_id: str
|
institution_id: str
|
||||||
organization_name: str
|
organization_name: str
|
||||||
@@ -54,6 +59,8 @@ class DfgProjectTopic(BaseModel):
|
|||||||
field: str | None = None
|
field: str | None = None
|
||||||
domain: str | None = None
|
domain: str | None = None
|
||||||
project_count: int
|
project_count: int
|
||||||
|
field_project_count: int
|
||||||
|
subfield_project_count: int
|
||||||
keywords: list[DfgProjectKeyword]
|
keywords: list[DfgProjectKeyword]
|
||||||
|
|
||||||
|
|
||||||
@@ -65,6 +72,22 @@ class DfgProjectTopics(BaseModel):
|
|||||||
topics: list[DfgProjectTopic]
|
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):
|
class TopAuthor(BaseModel):
|
||||||
id: str | None = None
|
id: str | None = None
|
||||||
name: str
|
name: str
|
||||||
@@ -80,6 +103,11 @@ class TopAuthorStatistics(BaseModel):
|
|||||||
news: list[TopAuthor]
|
news: list[TopAuthor]
|
||||||
|
|
||||||
|
|
||||||
|
class TopAuthorAnalysis(BaseModel):
|
||||||
|
institution_id: str
|
||||||
|
authors: list[TopAuthor]
|
||||||
|
|
||||||
|
|
||||||
class TopicHeatmapValue(BaseModel):
|
class TopicHeatmapValue(BaseModel):
|
||||||
year: int
|
year: int
|
||||||
count: 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 (
|
from .model import (
|
||||||
BmbfProjectStatusStatistics,
|
BmbfProjectStatusStatistics,
|
||||||
|
BundProjectTopics,
|
||||||
|
DashboardInstitution,
|
||||||
DashboardStatistics,
|
DashboardStatistics,
|
||||||
DashboardStatisticValue,
|
DashboardStatisticValue,
|
||||||
DfgProjectStatusStatistics,
|
DfgProjectStatusStatistics,
|
||||||
DfgProjectTopics,
|
DfgProjectTopics,
|
||||||
|
EuProjectTopics,
|
||||||
EuProjectStatusStatistics,
|
EuProjectStatusStatistics,
|
||||||
TopAuthorStatistics,
|
TopAuthorStatistics,
|
||||||
|
TopAuthorAnalysis,
|
||||||
TopicHeatmap,
|
TopicHeatmap,
|
||||||
TopicWordCloud,
|
TopicWordCloud,
|
||||||
)
|
)
|
||||||
from .service import (
|
from .service import (
|
||||||
get_dashboard_bmbf_project_statuses,
|
get_dashboard_analytical_institution,
|
||||||
get_dashboard_bmbf_projects,
|
get_dashboard_institutions,
|
||||||
get_dashboard_dfg_project_statuses,
|
|
||||||
get_dashboard_dfg_projects,
|
|
||||||
get_dashboard_dfg_topics,
|
|
||||||
get_dashboard_eu_project_statuses,
|
|
||||||
get_dashboard_eu_projects,
|
|
||||||
get_dashboard_organization,
|
get_dashboard_organization,
|
||||||
get_dashboard_patents,
|
get_dashboard_patents,
|
||||||
get_dashboard_persons,
|
get_dashboard_persons,
|
||||||
get_dashboard_publications,
|
get_dashboard_publications,
|
||||||
|
get_dashboard_statistic_institution_ids,
|
||||||
get_dashboard_statistics,
|
get_dashboard_statistics,
|
||||||
get_top_authors,
|
|
||||||
get_topic_heatmap,
|
get_topic_heatmap,
|
||||||
get_topic_word_cloud,
|
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 = 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(
|
@router.get(
|
||||||
"/statistics",
|
"/statistics",
|
||||||
operation_id="getDashboardStatistics",
|
operation_id="getDashboardStatistics",
|
||||||
@@ -62,14 +95,18 @@ async def dashboard_statistics(
|
|||||||
response_model=DashboardStatisticValue,
|
response_model=DashboardStatisticValue,
|
||||||
)
|
)
|
||||||
async def dashboard_publications(
|
async def dashboard_publications(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
organization = get_dashboard_organization(session, access_token)
|
||||||
|
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||||
|
session, organization, institution_id
|
||||||
|
)
|
||||||
return await get_dashboard_publications(
|
return await get_dashboard_publications(
|
||||||
organization.openalex_institution_id,
|
institution_ids,
|
||||||
organization.name,
|
organization.name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
@@ -82,14 +119,18 @@ async def dashboard_publications(
|
|||||||
response_model=DashboardStatisticValue,
|
response_model=DashboardStatisticValue,
|
||||||
)
|
)
|
||||||
async def dashboard_persons(
|
async def dashboard_persons(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
organization = get_dashboard_organization(session, access_token)
|
||||||
|
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||||
|
session, organization, institution_id
|
||||||
|
)
|
||||||
return await get_dashboard_persons(
|
return await get_dashboard_persons(
|
||||||
organization.openalex_institution_id,
|
institution_ids,
|
||||||
organization.name,
|
organization.name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
@@ -102,14 +143,18 @@ async def dashboard_persons(
|
|||||||
response_model=DashboardStatisticValue,
|
response_model=DashboardStatisticValue,
|
||||||
)
|
)
|
||||||
async def dashboard_patents(
|
async def dashboard_patents(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
organization = get_dashboard_organization(session, access_token)
|
||||||
|
institution_ids = await get_dashboard_statistic_institution_ids(
|
||||||
|
session, organization, institution_id
|
||||||
|
)
|
||||||
return await get_dashboard_patents(
|
return await get_dashboard_patents(
|
||||||
organization.openalex_institution_id,
|
institution_ids,
|
||||||
organization.name,
|
organization.name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
@@ -122,14 +167,18 @@ async def dashboard_patents(
|
|||||||
response_model=DashboardStatisticValue,
|
response_model=DashboardStatisticValue,
|
||||||
)
|
)
|
||||||
async def dashboard_eu_projects(
|
async def dashboard_eu_projects(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_eu_projects(
|
||||||
organization.openalex_institution_id,
|
institution_ids,
|
||||||
organization.name,
|
organization.name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
@@ -142,15 +191,21 @@ async def dashboard_eu_projects(
|
|||||||
response_model=EuProjectStatusStatistics,
|
response_model=EuProjectStatusStatistics,
|
||||||
)
|
)
|
||||||
async def dashboard_eu_project_statuses(
|
async def dashboard_eu_project_statuses(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> EuProjectStatusStatistics:
|
) -> EuProjectStatusStatistics:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_eu_project_statuses(
|
||||||
organization.openalex_institution_id,
|
selected_institution_id,
|
||||||
organization.name,
|
selected_institution_name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
)
|
)
|
||||||
@@ -162,14 +217,18 @@ async def dashboard_eu_project_statuses(
|
|||||||
response_model=DashboardStatisticValue,
|
response_model=DashboardStatisticValue,
|
||||||
)
|
)
|
||||||
async def dashboard_bmbf_projects(
|
async def dashboard_bmbf_projects(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_bmbf_projects(
|
||||||
organization.openalex_institution_id,
|
institution_ids,
|
||||||
organization.name,
|
organization.name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
@@ -182,15 +241,21 @@ async def dashboard_bmbf_projects(
|
|||||||
response_model=BmbfProjectStatusStatistics,
|
response_model=BmbfProjectStatusStatistics,
|
||||||
)
|
)
|
||||||
async def dashboard_bmbf_project_statuses(
|
async def dashboard_bmbf_project_statuses(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> BmbfProjectStatusStatistics:
|
) -> BmbfProjectStatusStatistics:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_bmbf_project_statuses(
|
||||||
organization.openalex_institution_id,
|
selected_institution_id,
|
||||||
organization.name,
|
selected_institution_name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
)
|
)
|
||||||
@@ -202,14 +267,18 @@ async def dashboard_bmbf_project_statuses(
|
|||||||
response_model=DashboardStatisticValue,
|
response_model=DashboardStatisticValue,
|
||||||
)
|
)
|
||||||
async def dashboard_dfg_projects(
|
async def dashboard_dfg_projects(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_dfg_projects(
|
||||||
organization.openalex_institution_id,
|
institution_ids,
|
||||||
organization.name,
|
organization.name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
@@ -222,15 +291,21 @@ async def dashboard_dfg_projects(
|
|||||||
response_model=DfgProjectStatusStatistics,
|
response_model=DfgProjectStatusStatistics,
|
||||||
)
|
)
|
||||||
async def dashboard_dfg_project_statuses(
|
async def dashboard_dfg_project_statuses(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DfgProjectStatusStatistics:
|
) -> DfgProjectStatusStatistics:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_dfg_project_statuses(
|
||||||
organization.openalex_institution_id,
|
selected_institution_id,
|
||||||
organization.name,
|
selected_institution_name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
)
|
)
|
||||||
@@ -242,15 +317,73 @@ async def dashboard_dfg_project_statuses(
|
|||||||
response_model=DfgProjectTopics,
|
response_model=DfgProjectTopics,
|
||||||
)
|
)
|
||||||
async def dashboard_dfg_project_topics(
|
async def dashboard_dfg_project_topics(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> DfgProjectTopics:
|
) -> DfgProjectTopics:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_dashboard_dfg_topics(
|
||||||
organization.openalex_institution_id,
|
selected_institution_id,
|
||||||
organization.name,
|
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,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
)
|
)
|
||||||
@@ -266,27 +399,144 @@ async def dashboard_top_authors(
|
|||||||
default="all_time",
|
default="all_time",
|
||||||
pattern="^(all_time|last_5_years)$",
|
pattern="^(all_time|last_5_years)$",
|
||||||
),
|
),
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> TopAuthorStatistics:
|
) -> TopAuthorStatistics:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_top_authors(
|
||||||
organization.openalex_institution_id,
|
selected_institution_id,
|
||||||
organization.name,
|
selected_institution_name,
|
||||||
works_period=works_period,
|
works_period=works_period,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_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(
|
@router.get(
|
||||||
"/topic-heatmap",
|
"/topic-heatmap",
|
||||||
operation_id="getDashboardTopicHeatmap",
|
operation_id="getDashboardTopicHeatmap",
|
||||||
response_model=TopicHeatmap,
|
response_model=TopicHeatmap,
|
||||||
)
|
)
|
||||||
async def dashboard_topic_heatmap(
|
async def dashboard_topic_heatmap(
|
||||||
|
institution_id: str | None = Query(default=None),
|
||||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
limit: int = Query(default=25, ge=1, le=50),
|
||||||
@@ -294,9 +544,14 @@ async def dashboard_topic_heatmap(
|
|||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> TopicHeatmap:
|
) -> TopicHeatmap:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_topic_heatmap(
|
||||||
institution_id=organization.openalex_institution_id,
|
institution_id=selected_institution_id,
|
||||||
organization_name=organization.name,
|
organization_name=selected_institution_name,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
limit=limit,
|
limit=limit,
|
||||||
@@ -310,6 +565,7 @@ async def dashboard_topic_heatmap(
|
|||||||
)
|
)
|
||||||
async def dashboard_topic_word_cloud(
|
async def dashboard_topic_word_cloud(
|
||||||
topic_id: str = Query(alias="topicId", min_length=1),
|
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),
|
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||||
to_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),
|
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,
|
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> TopicWordCloud:
|
) -> TopicWordCloud:
|
||||||
organization = get_dashboard_organization(session, access_token)
|
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(
|
return await get_topic_word_cloud(
|
||||||
institution_id=organization.openalex_institution_id,
|
institution_id=selected_institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_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():
|
def get_session():
|
||||||
"""Yields a database session for use in FastAPI endpoints.
|
"""Yields a database session for use in FastAPI endpoints.
|
||||||
|
|||||||
@@ -361,6 +361,7 @@ class InstitutionsSearchClient:
|
|||||||
"government",
|
"government",
|
||||||
"facility",
|
"facility",
|
||||||
"other",
|
"other",
|
||||||
|
"funder",
|
||||||
}
|
}
|
||||||
|
|
||||||
cleaned_source = {}
|
cleaned_source = {}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ _VALID_INSTITUTION_TYPES = {
|
|||||||
"government",
|
"government",
|
||||||
"facility",
|
"facility",
|
||||||
"other",
|
"other",
|
||||||
|
"funder",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -174,3 +174,34 @@ async def test_list_institutions_accepts_practical_openalex_type_variants():
|
|||||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
assert result.results[0].counts_by_year[0].cited_by_count is None
|
||||||
assert result.group_by[0].key == "true"
|
assert result.group_by[0].key == "true"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_list_institutions_accepts_funder_institution_type():
|
||||||
|
def handler(_: httpx.Request) -> httpx.Response:
|
||||||
|
return httpx.Response(
|
||||||
|
200,
|
||||||
|
json={
|
||||||
|
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"id": "https://openalex.org/I4210119759",
|
||||||
|
"display_name": "Essen University Hospital",
|
||||||
|
"country_code": "DE",
|
||||||
|
"type": "funder",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
client = OpenAlexInstitutionsClient(
|
||||||
|
api_key="test-key",
|
||||||
|
transport=httpx.MockTransport(handler),
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await logic.list_institutions(client=client)
|
||||||
|
|
||||||
|
assert result.results[0].id == "https://openalex.org/I4210119759"
|
||||||
|
assert result.results[0].display_name == "Essen University Hospital"
|
||||||
|
assert result.results[0].type == "funder"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -142,15 +142,50 @@ async def autocomplete_institutions(
|
|||||||
if not query:
|
if not query:
|
||||||
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
|
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
|
||||||
|
|
||||||
|
stripped = query.strip()
|
||||||
|
fields = [("display_name", 1.0), ("display_name_alternatives", 0.8)]
|
||||||
|
should_clauses = []
|
||||||
|
for field, weight in fields:
|
||||||
|
should_clauses.extend([
|
||||||
|
{
|
||||||
|
"prefix": {
|
||||||
|
f"{field}.keyword": {
|
||||||
|
"value": stripped,
|
||||||
|
"case_insensitive": True,
|
||||||
|
"boost": 10.0 * weight,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{"match_phrase_prefix": {field: {"query": stripped, "boost": 5.0 * weight, "slop": 3}}},
|
||||||
|
{"match_bool_prefix": {field: {"query": stripped, "boost": 2.0 * weight}}},
|
||||||
|
{
|
||||||
|
"constant_score": {
|
||||||
|
"filter": {
|
||||||
|
"wildcard": {
|
||||||
|
f"{field}.keyword": {
|
||||||
|
"value": f"*{stripped}*",
|
||||||
|
"case_insensitive": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"boost": 1.0 * weight,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
return await search_institutions(
|
return await search_institutions(
|
||||||
page=page,
|
page=page,
|
||||||
size=size,
|
size=size,
|
||||||
query={
|
query={
|
||||||
"bool": {
|
"function_score": {
|
||||||
"should": [
|
"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}},
|
||||||
{"match_phrase_prefix": {"display_name": query}},
|
"field_value_factor": {
|
||||||
{"match_phrase_prefix": {"display_name_alternatives": query}},
|
"field": "works_count",
|
||||||
]
|
"modifier": "log1p",
|
||||||
|
"factor": 0.05,
|
||||||
|
"missing": 1.0,
|
||||||
|
},
|
||||||
|
"boost_mode": "multiply",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
source=source,
|
source=source,
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ def _index_to_cluster(index: ESIndex) -> ESCluster | None:
|
|||||||
ESIndex.OPENALEX_INSTITUTIONS,
|
ESIndex.OPENALEX_INSTITUTIONS,
|
||||||
ESIndex.OPENALEX_PUBLICATIONS,
|
ESIndex.OPENALEX_PUBLICATIONS,
|
||||||
ESIndex.WORK_CLASSIFICATIONS,
|
ESIndex.WORK_CLASSIFICATIONS,
|
||||||
|
ESIndex.CC_NEWS_WILDCARD,
|
||||||
}:
|
}:
|
||||||
return ESCluster.NES
|
return ESCluster.NES
|
||||||
elif index in {
|
elif index in {
|
||||||
@@ -260,11 +261,10 @@ async def search(
|
|||||||
payload["sort"] = sort
|
payload["sort"] = sort
|
||||||
if aggs is not None:
|
if aggs is not None:
|
||||||
payload["aggs"] = aggs
|
payload["aggs"] = aggs
|
||||||
if track_total_hits:
|
|
||||||
payload["track_total_hits"] = True
|
|
||||||
if highlight is not None:
|
if highlight is not None:
|
||||||
payload["highlight"] = highlight
|
payload["highlight"] = highlight
|
||||||
|
|
||||||
|
payload["track_total_hits"] = True # always track total hits for accurate pagination and counts
|
||||||
if len(payload) == 0:
|
if len(payload) == 0:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
|
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
|
||||||
@@ -439,12 +439,16 @@ async def count(
|
|||||||
async def msearch(
|
async def msearch(
|
||||||
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
|
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
|
||||||
cluster: ESCluster = ESCluster.NES,
|
cluster: ESCluster = ESCluster.NES,
|
||||||
|
request_cache: bool = False,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
"""Performs a multi-search request (_msearch) on Elasticsearch.
|
"""Performs a multi-search request (_msearch) on Elasticsearch.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
searches: A list of tuples, each containing (index, payload_dict).
|
searches: A list of tuples, each containing (index, payload_dict).
|
||||||
cluster: The Elasticsearch cluster to execute searches on.
|
cluster: The Elasticsearch cluster to execute searches on.
|
||||||
|
request_cache: Whether to enable the shard request cache for each search.
|
||||||
|
Elasticsearch rejects `request_cache` as an _msearch URL parameter, so
|
||||||
|
it goes into the per-search header line instead.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List[Dict[str, Any]]: List of response dictionaries for each search in order.
|
List[Dict[str, Any]]: List of response dictionaries for each search in order.
|
||||||
@@ -464,7 +468,9 @@ async def msearch(
|
|||||||
idx_str = ",".join(str(i) for i in idx)
|
idx_str = ",".join(str(i) for i in idx)
|
||||||
else:
|
else:
|
||||||
idx_str = str(idx)
|
idx_str = str(idx)
|
||||||
header_obj = {"index": idx_str}
|
header_obj: dict[str, Any] = {"index": idx_str}
|
||||||
|
if request_cache:
|
||||||
|
header_obj["request_cache"] = True
|
||||||
lines.append(json.dumps(header_obj))
|
lines.append(json.dumps(header_obj))
|
||||||
lines.append(json.dumps(body))
|
lines.append(json.dumps(body))
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ class ESIndex(StrEnum):
|
|||||||
OPENALEX_CONTINENTS = "openalex-continents"
|
OPENALEX_CONTINENTS = "openalex-continents"
|
||||||
OPENALEX_TOPICS = "openalex-topics"
|
OPENALEX_TOPICS = "openalex-topics"
|
||||||
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
||||||
|
OPENALEX_DOMAINS = "openalex-domains"
|
||||||
|
OPENALEX_FIELDS = "openalex-fields"
|
||||||
|
OPENALEX_SUBFIELDS = "openalex-subfields"
|
||||||
|
|
||||||
EPO_INDEX = "epo_index_1.0"
|
EPO_INDEX = "epo_index_1.0"
|
||||||
USPTO_INDEX = "uspto_patents_3.0"
|
USPTO_INDEX = "uspto_patents_3.0"
|
||||||
@@ -65,6 +68,7 @@ class ESIndex(StrEnum):
|
|||||||
AKTUELLES = "aktuell"
|
AKTUELLES = "aktuell"
|
||||||
AKTUELLES_POSTPROC = "aktuell_postproc"
|
AKTUELLES_POSTPROC = "aktuell_postproc"
|
||||||
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
|
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
|
||||||
|
CC_NEWS_WILDCARD = "cc-news-*"
|
||||||
|
|
||||||
|
|
||||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||||
|
|||||||
@@ -170,25 +170,6 @@ class DfgProjectPublicationSummary(BaseModel):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DfgProjectSubjectArea(BaseModel):
|
|
||||||
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
|
|
||||||
|
|
||||||
model_config = ConfigDict(populate_by_name=True)
|
|
||||||
|
|
||||||
fach: str | None = None
|
|
||||||
fachgebiet: str | None = None
|
|
||||||
fachkollegium: str | None = None
|
|
||||||
wissenschaftsbereich: str | None = None
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
|
|
||||||
return cls(
|
|
||||||
fach=f.fach,
|
|
||||||
fachgebiet=f.fachgebiet,
|
|
||||||
fachkollegium=f.fachkollegium,
|
|
||||||
wissenschaftsbereich=f.wissenschaftsbereich,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class DfgProjectDetails(BaseModel):
|
class DfgProjectDetails(BaseModel):
|
||||||
"""
|
"""
|
||||||
@@ -253,7 +234,7 @@ class DfgProjectDetails(BaseModel):
|
|||||||
|
|
||||||
subject_area_de: str | None = Field(default=None, description="Subject area, summary text (German)")
|
subject_area_de: str | None = Field(default=None, description="Subject area, summary text (German)")
|
||||||
subject_area_en: str | None = Field(default=None, description="Subject area, summary text (English)")
|
subject_area_en: str | None = Field(default=None, description="Subject area, summary text (English)")
|
||||||
subject_classifications: list[DfgProjectSubjectArea] = Field(
|
subject_classifications: list[DFGProjectFachgebieteInner] = Field(
|
||||||
default_factory=list,
|
default_factory=list,
|
||||||
description="Detailed DFG subject-area classification entries (Fachsystematik)",
|
description="Detailed DFG subject-area classification entries (Fachsystematik)",
|
||||||
)
|
)
|
||||||
@@ -319,7 +300,7 @@ class DfgProjectDetails(BaseModel):
|
|||||||
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
|
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
|
||||||
]
|
]
|
||||||
subject_classifications = [
|
subject_classifications = [
|
||||||
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
|
DFGProjectFachgebieteInner.from_dict(f) for f in (project.subject_classifications or [])
|
||||||
]
|
]
|
||||||
|
|
||||||
# De-duplicated flat views, order-preserving
|
# De-duplicated flat views, order-preserving
|
||||||
@@ -383,8 +364,6 @@ class DfgProjectDetails(BaseModel):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
|
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
|
||||||
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
|
|
||||||
obj = cls._sanitize_raw_project_dict(obj)
|
|
||||||
return cls.from_dfg_project(DFGProject.from_dict(obj))
|
return cls.from_dfg_project(DFGProject.from_dict(obj))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class Institution(BaseModel):
|
|||||||
ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.")
|
ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.")
|
||||||
display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.")
|
display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.")
|
||||||
country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.")
|
country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.")
|
||||||
type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`.")
|
type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`, `Funder`.")
|
||||||
homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.")
|
homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.")
|
||||||
image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).")
|
image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).")
|
||||||
image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.")
|
image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.")
|
||||||
@@ -61,8 +61,9 @@ class Institution(BaseModel):
|
|||||||
if value is None:
|
if value is None:
|
||||||
return value
|
return value
|
||||||
|
|
||||||
if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']):
|
valid_types = {'education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other', 'funder'}
|
||||||
raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')")
|
if value not in valid_types:
|
||||||
|
return 'other'
|
||||||
return value
|
return value
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ class DFGProject(BaseModel):
|
|||||||
equipment_group: StrictStr | None = None
|
equipment_group: StrictStr | None = None
|
||||||
equipment_name: StrictStr | None = None
|
equipment_name: StrictStr | None = None
|
||||||
external_link: StrictStr | None = None
|
external_link: StrictStr | None = None
|
||||||
fachgebiete: list[DFGProjectFachgebieteInner] | None = None
|
|
||||||
fetched_at: datetime | None = None
|
fetched_at: datetime | None = None
|
||||||
final_report_abstract_de: StrictStr | None = None
|
final_report_abstract_de: StrictStr | None = None
|
||||||
final_report_abstract_en: StrictStr | None = None
|
final_report_abstract_en: StrictStr | None = None
|
||||||
@@ -81,7 +80,7 @@ class DFGProject(BaseModel):
|
|||||||
publications: list[DFGProjectPublicationsInner] | None = None
|
publications: list[DFGProjectPublicationsInner] | None = None
|
||||||
subject_area_de: StrictStr | None = None
|
subject_area_de: StrictStr | None = None
|
||||||
subject_area_en: StrictStr | None = None
|
subject_area_en: StrictStr | None = None
|
||||||
subject_classifications: DFGProjectFachgebieteInner | None = None
|
subject_classifications: list[DFGProjectFachgebieteInner] | None = None
|
||||||
subproject_order: list[StrictStr] | None = None
|
subproject_order: list[StrictStr] | None = None
|
||||||
subprojects: list[DFGProjectSubprojectsInner] | None = None
|
subprojects: list[DFGProjectSubprojectsInner] | None = None
|
||||||
template_type: StrictStr | None = None
|
template_type: StrictStr | None = None
|
||||||
@@ -90,7 +89,7 @@ class DFGProject(BaseModel):
|
|||||||
website_html_de: StrictStr | None = None
|
website_html_de: StrictStr | None = None
|
||||||
website_html_en: StrictStr | None = None
|
website_html_en: StrictStr | None = None
|
||||||
topics: list[Topic] | None = None
|
topics: list[Topic] | None = None
|
||||||
__properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
|
__properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link","fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
validate_by_name=True,
|
validate_by_name=True,
|
||||||
@@ -131,13 +130,6 @@ class DFGProject(BaseModel):
|
|||||||
exclude=excluded_fields,
|
exclude=excluded_fields,
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
)
|
)
|
||||||
# override the default output from pydantic by calling `to_dict()` of each item in fachgebiete (list)
|
|
||||||
_items = []
|
|
||||||
if self.fachgebiete:
|
|
||||||
for _item_fachgebiete in self.fachgebiete:
|
|
||||||
if _item_fachgebiete:
|
|
||||||
_items.append(_item_fachgebiete.to_dict())
|
|
||||||
_dict['fachgebiete'] = _items
|
|
||||||
# override the default output from pydantic by calling `to_dict()` of each item in institutions (list)
|
# override the default output from pydantic by calling `to_dict()` of each item in institutions (list)
|
||||||
_items = []
|
_items = []
|
||||||
if self.institutions:
|
if self.institutions:
|
||||||
@@ -164,7 +156,7 @@ class DFGProject(BaseModel):
|
|||||||
_dict['publications'] = _items
|
_dict['publications'] = _items
|
||||||
# override the default output from pydantic by calling `to_dict()` of subject_classifications
|
# override the default output from pydantic by calling `to_dict()` of subject_classifications
|
||||||
if self.subject_classifications:
|
if self.subject_classifications:
|
||||||
_dict['subject_classifications'] = self.subject_classifications.to_dict()
|
_dict['subject_classifications'] = [f.to_dict() for f in self.subject_classifications]
|
||||||
# override the default output from pydantic by calling `to_dict()` of each item in subprojects (list)
|
# override the default output from pydantic by calling `to_dict()` of each item in subprojects (list)
|
||||||
_items = []
|
_items = []
|
||||||
if self.subprojects:
|
if self.subprojects:
|
||||||
@@ -191,14 +183,12 @@ class DFGProject(BaseModel):
|
|||||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||||
)
|
)
|
||||||
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
||||||
|
|
||||||
_obj = cls.model_validate({
|
_obj = cls.model_validate({
|
||||||
"abstract_de": obj.get("abstract_de"),
|
"abstract_de": obj.get("abstract_de"),
|
||||||
"abstract_en": obj.get("abstract_en"),
|
"abstract_en": obj.get("abstract_en"),
|
||||||
"equipment_group": obj.get("equipment_group"),
|
"equipment_group": obj.get("equipment_group"),
|
||||||
"equipment_name": obj.get("equipment_name"),
|
"equipment_name": obj.get("equipment_name"),
|
||||||
"external_link": obj.get("external_link"),
|
"external_link": obj.get("external_link"),
|
||||||
"fachgebiete": [DFGProjectFachgebieteInner.from_dict(_item) for _item in obj["fachgebiete"]] if obj.get("fachgebiete") is not None else None,
|
|
||||||
"fetched_at": obj.get("fetched_at"),
|
"fetched_at": obj.get("fetched_at"),
|
||||||
"final_report_abstract_de": obj.get("final_report_abstract_de"),
|
"final_report_abstract_de": obj.get("final_report_abstract_de"),
|
||||||
"final_report_abstract_en": obj.get("final_report_abstract_en"),
|
"final_report_abstract_en": obj.get("final_report_abstract_en"),
|
||||||
@@ -230,7 +220,7 @@ class DFGProject(BaseModel):
|
|||||||
"publications": [DFGProjectPublicationsInner.from_dict(_item) for _item in obj["publications"]] if obj.get("publications") is not None else None,
|
"publications": [DFGProjectPublicationsInner.from_dict(_item) for _item in obj["publications"]] if obj.get("publications") is not None else None,
|
||||||
"subject_area_de": obj.get("subject_area_de"),
|
"subject_area_de": obj.get("subject_area_de"),
|
||||||
"subject_area_en": obj.get("subject_area_en"),
|
"subject_area_en": obj.get("subject_area_en"),
|
||||||
"subject_classifications": DFGProjectFachgebieteInner.from_dict(obj["subject_classifications"]) if obj.get("subject_classifications") is not None else None,
|
"subject_classifications": [DFGProjectFachgebieteInner.from_dict(f) for f in (obj.get("subject_classifications") or [])],
|
||||||
"subproject_order": obj.get("subproject_order"),
|
"subproject_order": obj.get("subproject_order"),
|
||||||
"subprojects": [DFGProjectSubprojectsInner.from_dict(_item) for _item in obj["subprojects"]] if obj.get("subprojects") is not None else None,
|
"subprojects": [DFGProjectSubprojectsInner.from_dict(_item) for _item in obj["subprojects"]] if obj.get("subprojects") is not None else None,
|
||||||
"template_type": obj.get("template_type"),
|
"template_type": obj.get("template_type"),
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ TOPIC_NUM_CANDIDATES = 100
|
|||||||
TOPIC_SIMILARITY = 0.5
|
TOPIC_SIMILARITY = 0.5
|
||||||
|
|
||||||
TOPICS_INDEX = "aktuell_openalex_topics"
|
TOPICS_INDEX = "aktuell_openalex_topics"
|
||||||
TOPICS_INDEX_MAX_PAIRS = 100
|
|
||||||
|
|
||||||
_SESSION_TOPIC_CACHE: dict[str, list] = {}
|
_SESSION_TOPIC_CACHE: dict[str, list] = {}
|
||||||
|
|
||||||
@@ -48,6 +47,11 @@ RELATED_BLOCK_SIZE = 5
|
|||||||
RELATED_TOPIC_K = 1
|
RELATED_TOPIC_K = 1
|
||||||
EXACT_ID_CAP = 1000
|
EXACT_ID_CAP = 1000
|
||||||
|
|
||||||
|
KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"]
|
||||||
|
KEYWORD_SEARCH_SCAN_CAP = 50000
|
||||||
|
KEYWORD_SEARCH_ID_CAP = 2000
|
||||||
|
TOPIC_DOCS_PER_ARTICLE = 25
|
||||||
|
|
||||||
|
|
||||||
async def get_news_page(
|
async def get_news_page(
|
||||||
page: int,
|
page: int,
|
||||||
@@ -127,6 +131,206 @@ async def search_news(
|
|||||||
return news_page
|
return news_page
|
||||||
|
|
||||||
|
|
||||||
|
async def search_news_by_keywords(
|
||||||
|
keywords: list | None = None,
|
||||||
|
topic_ids: list | None = None,
|
||||||
|
filter_topic_ids: list | None = None,
|
||||||
|
fuzzy: bool = False,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 10,
|
||||||
|
year_from: int | None = None,
|
||||||
|
year_to: int | None = None,
|
||||||
|
relevance_values: list | None = None,
|
||||||
|
sort_order: str | None = None,
|
||||||
|
) -> NewsPage:
|
||||||
|
"""Searches the news for the keywords of a keywords-search run.
|
||||||
|
|
||||||
|
`fuzzy` resolves the keywords to OpenAlex topics (via the aktuell_openalex_topics index),
|
||||||
|
otherwise the raw keywords are matched as phrases against the article
|
||||||
|
text. The individual keywords are OR-ed rather than AND-ed.
|
||||||
|
An article carries at most KEYWORD_LIMIT keywords, so requiring all of them
|
||||||
|
would leave every multi-keyword search empty.
|
||||||
|
Articles matching more of them simply rank higher.
|
||||||
|
|
||||||
|
A fuzzy search without any resolved topic ids falls back to the raw
|
||||||
|
keywords. Once there are topic ids the fallback is off: a topic search that matches no article
|
||||||
|
stays empty instead of silently returning keyword hits.
|
||||||
|
|
||||||
|
By default results stay ranked by match strength (Elasticsearch's
|
||||||
|
`_score`). Passing `sort_order` ('asc'/'desc') overrides that with a
|
||||||
|
plain date sort, same as the plain news list.
|
||||||
|
"""
|
||||||
|
wanted_topic_ids: set = set()
|
||||||
|
if fuzzy:
|
||||||
|
wanted_topic_ids = {
|
||||||
|
topic_id
|
||||||
|
for topic_id in (topic_ids or []) + (filter_topic_ids or [])
|
||||||
|
if topic_id
|
||||||
|
}
|
||||||
|
|
||||||
|
if wanted_topic_ids:
|
||||||
|
should = await _topic_id_should_clauses(wanted_topic_ids)
|
||||||
|
else:
|
||||||
|
should = _keyword_should_clauses(keywords)
|
||||||
|
|
||||||
|
if not should:
|
||||||
|
return _empty_page(page, page_size)
|
||||||
|
|
||||||
|
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||||
|
query = {
|
||||||
|
"bool": {
|
||||||
|
"should": should,
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
"filter": clauses,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
highlight = {
|
||||||
|
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
|
||||||
|
"pre_tags": ["<em>"],
|
||||||
|
"post_tags": ["</em>"],
|
||||||
|
"encoder": "html",
|
||||||
|
}
|
||||||
|
|
||||||
|
sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None
|
||||||
|
|
||||||
|
response = await _run_search(
|
||||||
|
query=query,
|
||||||
|
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||||
|
size=page_size,
|
||||||
|
offset=(page - 1) * page_size,
|
||||||
|
sort=sort,
|
||||||
|
highlight=None if wanted_topic_ids else highlight,
|
||||||
|
)
|
||||||
|
|
||||||
|
news_page = await _build_page(response, page, page_size)
|
||||||
|
await _attach_topics(news_page.results)
|
||||||
|
|
||||||
|
return news_page
|
||||||
|
|
||||||
|
|
||||||
|
def _keyword_should_clauses(keywords: list | None) -> list:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"multi_match": {
|
||||||
|
"query": keyword.strip(),
|
||||||
|
"fields": KEYWORD_SEARCH_FIELDS,
|
||||||
|
"type": "phrase",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for keyword in (keywords or [])
|
||||||
|
if keyword and keyword.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def _topic_id_should_clauses(topic_ids: set) -> list:
|
||||||
|
"""Turns matched OpenAlex topics into id clauses, boosted by hit count.
|
||||||
|
|
||||||
|
Articles that match several of the searched topics get a higher boost, so
|
||||||
|
Elasticsearch ranks them above articles that only match one.
|
||||||
|
"""
|
||||||
|
topics_per_article = await _news_ids_by_topic_ids(topic_ids)
|
||||||
|
if not topics_per_article:
|
||||||
|
return []
|
||||||
|
|
||||||
|
ranked = sorted(topics_per_article.items(), key=lambda item: -len(item[1]))
|
||||||
|
ids_by_hit_count: dict[int, list] = {}
|
||||||
|
for news_id, matched_topics in ranked[:KEYWORD_SEARCH_ID_CAP]:
|
||||||
|
ids_by_hit_count.setdefault(len(matched_topics), []).append(news_id)
|
||||||
|
|
||||||
|
return [
|
||||||
|
{"ids": {"values": news_ids, "boost": float(hit_count)}}
|
||||||
|
for hit_count, news_ids in ids_by_hit_count.items()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def _news_ids_by_topic_ids(topic_ids: set) -> dict:
|
||||||
|
"""Returns news_id -> set of searched topic ids the article was mapped to."""
|
||||||
|
query = {"terms": {"topic_matches.topic_id.keyword": sorted(topic_ids)}}
|
||||||
|
|
||||||
|
topics_per_article: dict[str, set] = {}
|
||||||
|
scanned = 0
|
||||||
|
try:
|
||||||
|
async for hit in elasticsearch.scan(
|
||||||
|
index=TOPICS_INDEX,
|
||||||
|
query=query,
|
||||||
|
source=["news_id", "topic_matches.topic_id"],
|
||||||
|
cluster="inse",
|
||||||
|
):
|
||||||
|
scanned += 1
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
news_id = source.get("news_id")
|
||||||
|
if news_id:
|
||||||
|
matched = topics_per_article.setdefault(news_id, set())
|
||||||
|
for match in source.get("topic_matches") or []:
|
||||||
|
topic_id = match.get("topic_id")
|
||||||
|
if topic_id in topic_ids:
|
||||||
|
matched.add(topic_id)
|
||||||
|
if scanned >= KEYWORD_SEARCH_SCAN_CAP:
|
||||||
|
logger.warning(
|
||||||
|
f"Topic lookup hit the scan cap of {KEYWORD_SEARCH_SCAN_CAP} documents."
|
||||||
|
)
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Topic lookup for the keyword news search failed.")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
return {news_id: matched for news_id, matched in topics_per_article.items() if matched}
|
||||||
|
|
||||||
|
|
||||||
|
async def _attach_topics(articles: list) -> None:
|
||||||
|
news_ids = [article.id for article in articles if article.id]
|
||||||
|
if not news_ids:
|
||||||
|
return
|
||||||
|
|
||||||
|
topics_per_article = await _topics_for_news_ids(news_ids)
|
||||||
|
for article in articles:
|
||||||
|
article.topics = topics_per_article.get(article.id, [])
|
||||||
|
|
||||||
|
|
||||||
|
async def _topics_for_news_ids(news_ids: list) -> dict[str, list[MatchedTopic]]:
|
||||||
|
"""Reads the indexed OpenAlex topic matches for the given articles."""
|
||||||
|
try:
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=TOPICS_INDEX,
|
||||||
|
query={"terms": {"news_id.keyword": news_ids}},
|
||||||
|
source=["news_id", "keyword", "topic_matches"],
|
||||||
|
size=min(len(news_ids) * TOPIC_DOCS_PER_ARTICLE, 10000),
|
||||||
|
cluster="inse",
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Batched topic lookup for the news result page failed.")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
topics_per_article: dict[str, list[MatchedTopic]] = {}
|
||||||
|
seen_per_article: dict[str, set] = {}
|
||||||
|
for hit in response.get("hits", {}).get("hits", []):
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
news_id = source.get("news_id")
|
||||||
|
if not news_id:
|
||||||
|
continue
|
||||||
|
keyword = source.get("keyword")
|
||||||
|
matched = topics_per_article.setdefault(news_id, [])
|
||||||
|
seen_ids = seen_per_article.setdefault(news_id, set())
|
||||||
|
for match in source.get("topic_matches") or []:
|
||||||
|
topic_id = match.get("topic_id")
|
||||||
|
if not topic_id or topic_id in seen_ids:
|
||||||
|
continue
|
||||||
|
seen_ids.add(topic_id)
|
||||||
|
matched.append(
|
||||||
|
MatchedTopic(
|
||||||
|
id=topic_id,
|
||||||
|
display_name=match.get("topic_display_name"),
|
||||||
|
subfield_name=match.get("subfield"),
|
||||||
|
field_name=match.get("field"),
|
||||||
|
domain_name=match.get("domain"),
|
||||||
|
source_keyword=keyword,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return topics_per_article
|
||||||
|
|
||||||
|
|
||||||
async def get_news_by_author(
|
async def get_news_by_author(
|
||||||
author_id: str,
|
author_id: str,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
@@ -321,7 +525,7 @@ async def _get_article_keywords(
|
|||||||
|
|
||||||
|
|
||||||
async def _get_article_topics(news_id: str, keywords: list) -> list:
|
async def _get_article_topics(news_id: str, keywords: list) -> list:
|
||||||
indexed = await get_article_topics_from_index(news_id)
|
indexed = (await _topics_for_news_ids([news_id])).get(news_id, [])
|
||||||
if indexed:
|
if indexed:
|
||||||
return indexed
|
return indexed
|
||||||
|
|
||||||
@@ -336,42 +540,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
|
|||||||
return topics
|
return topics
|
||||||
|
|
||||||
|
|
||||||
async def get_article_topics_from_index(news_id: str) -> list:
|
|
||||||
try:
|
|
||||||
response = await elasticsearch.search(
|
|
||||||
index=TOPICS_INDEX,
|
|
||||||
query={"term": {"news_id.keyword": news_id}},
|
|
||||||
source=["keyword", "topic_matches"],
|
|
||||||
size=TOPICS_INDEX_MAX_PAIRS,
|
|
||||||
cluster="inse",
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
logger.exception(f"Topic-index lookup for {news_id} failed.")
|
|
||||||
return []
|
|
||||||
|
|
||||||
matched = []
|
|
||||||
seen_ids = set()
|
|
||||||
for hit in response.get("hits", {}).get("hits", []):
|
|
||||||
source = hit.get("_source", {})
|
|
||||||
keyword = source.get("keyword")
|
|
||||||
for match in source.get("topic_matches") or []:
|
|
||||||
topic_id = match.get("topic_id")
|
|
||||||
if not topic_id or topic_id in seen_ids:
|
|
||||||
continue
|
|
||||||
seen_ids.add(topic_id)
|
|
||||||
matched.append(
|
|
||||||
MatchedTopic(
|
|
||||||
id=topic_id,
|
|
||||||
display_name=match.get("topic_display_name"),
|
|
||||||
subfield_name=match.get("subfield"),
|
|
||||||
field_name=match.get("field"),
|
|
||||||
domain_name=match.get("domain"),
|
|
||||||
source_keyword=keyword,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return matched
|
|
||||||
|
|
||||||
|
|
||||||
def _normalize_keywords(candidates: list) -> list:
|
def _normalize_keywords(candidates: list) -> list:
|
||||||
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
||||||
seen = set()
|
seen = set()
|
||||||
@@ -516,7 +684,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s
|
|||||||
return relevant, authors, keywords, hit.get("_id")
|
return relevant, authors, keywords, hit.get("_id")
|
||||||
|
|
||||||
|
|
||||||
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict | None = None) -> dict:
|
||||||
try:
|
try:
|
||||||
return await elasticsearch.search(
|
return await elasticsearch.search(
|
||||||
index="aktuell",
|
index="aktuell",
|
||||||
|
|||||||
@@ -8,17 +8,6 @@ class NewsKeywords(BaseModel):
|
|||||||
keywords: list[str] = Field(description="The extracted keywords from the article.")
|
keywords: list[str] = Field(description="The extracted keywords from the article.")
|
||||||
|
|
||||||
|
|
||||||
class NewsArticle(BaseModel):
|
|
||||||
id: str
|
|
||||||
date: str | None = None
|
|
||||||
maintitle: str | None = None
|
|
||||||
author: str | None = None
|
|
||||||
url: str | None = None
|
|
||||||
relevant: bool | None = None
|
|
||||||
snippet: str | None = None
|
|
||||||
related: bool | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class MentionedPerson(BaseModel):
|
class MentionedPerson(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
is_ude: bool = False
|
is_ude: bool = False
|
||||||
@@ -34,6 +23,18 @@ class MatchedTopic(BaseModel):
|
|||||||
source_keyword: str | None = None
|
source_keyword: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class NewsArticle(BaseModel):
|
||||||
|
id: str
|
||||||
|
date: str | None = None
|
||||||
|
maintitle: str | None = None
|
||||||
|
author: str | None = None
|
||||||
|
url: str | None = None
|
||||||
|
relevant: bool | None = None
|
||||||
|
snippet: str | None = None
|
||||||
|
related: bool | None = None
|
||||||
|
topics: list[MatchedTopic] | None = None
|
||||||
|
|
||||||
|
|
||||||
class NewsArticleDetail(NewsArticle):
|
class NewsArticleDetail(NewsArticle):
|
||||||
full_content: str | None = None
|
full_content: str | None = None
|
||||||
relevant: bool | None = None
|
relevant: bool | None = None
|
||||||
|
|||||||
@@ -100,6 +100,68 @@ async def search_news(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/keyword/search",
|
||||||
|
operation_id="getNewsByKeywords",
|
||||||
|
response_model=NewsPage,
|
||||||
|
response_model_exclude_none=True,
|
||||||
|
summary="Searches news articles by the keywords or matched topics of a keywords search.",
|
||||||
|
tags=[Tags.NEWS],
|
||||||
|
)
|
||||||
|
async def search_news_by_keywords(
|
||||||
|
keywords: Annotated[
|
||||||
|
list[str] | None, Query(description="Raw keywords to match against title/content.")
|
||||||
|
] = None,
|
||||||
|
topic_ids: Annotated[
|
||||||
|
list[str] | None,
|
||||||
|
Query(alias="topicIds", description="OpenAlex topic ids the keywords resolved to."),
|
||||||
|
] = None,
|
||||||
|
filter_topic_ids: Annotated[
|
||||||
|
list[str] | None,
|
||||||
|
Query(alias="filterTopicIds", description="Additional topic ids to narrow the results by."),
|
||||||
|
] = None,
|
||||||
|
fuzzy: Annotated[
|
||||||
|
bool,
|
||||||
|
Query(description="Search by resolved topics if True, otherwise by raw keywords."),
|
||||||
|
] = False,
|
||||||
|
page: Annotated[
|
||||||
|
int, Query(description="Page number (1-based).", ge=1)
|
||||||
|
] = 1,
|
||||||
|
page_size: Annotated[
|
||||||
|
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||||
|
] = 10,
|
||||||
|
relevance: Annotated[
|
||||||
|
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||||
|
] = None,
|
||||||
|
year_from: Annotated[
|
||||||
|
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||||
|
] = None,
|
||||||
|
year_to: Annotated[
|
||||||
|
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||||
|
] = None,
|
||||||
|
sort_order: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
alias="sortOrder",
|
||||||
|
description="Overrides relevance ranking with a date sort: 'desc' (newest first) or 'asc' (oldest first).",
|
||||||
|
pattern="^(asc|desc)$",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
):
|
||||||
|
return await logic.search_news_by_keywords(
|
||||||
|
keywords=keywords or [],
|
||||||
|
topic_ids=topic_ids or [],
|
||||||
|
filter_topic_ids=filter_topic_ids or [],
|
||||||
|
fuzzy=fuzzy,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
sort_order=sort_order,
|
||||||
|
year_from=year_from,
|
||||||
|
year_to=year_to,
|
||||||
|
relevance_values=_parse_relevance(relevance),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/by-author",
|
"/by-author",
|
||||||
operation_id="getNewsByAuthor",
|
operation_id="getNewsByAuthor",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import uuid
|
import uuid
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
@@ -7,6 +8,7 @@ class OrganizationProfile(BaseModel):
|
|||||||
id: uuid.UUID
|
id: uuid.UUID
|
||||||
name: str
|
name: str
|
||||||
other_inst_id: str | None = None
|
other_inst_id: str | None = None
|
||||||
|
selected_openalex_institution_ids: list[str] = Field(default_factory=list)
|
||||||
deleted: bool
|
deleted: bool
|
||||||
member_count: int
|
member_count: int
|
||||||
|
|
||||||
@@ -21,9 +23,25 @@ class OrganizationPage(BaseModel):
|
|||||||
class CreateOrganizationRequest(BaseModel):
|
class CreateOrganizationRequest(BaseModel):
|
||||||
name: str = Field(min_length=1)
|
name: str = Field(min_length=1)
|
||||||
other_inst_id: str | None = None
|
other_inst_id: str | None = None
|
||||||
|
selected_openalex_institution_ids: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
class UpdateOrganizationRequest(BaseModel):
|
class UpdateOrganizationRequest(BaseModel):
|
||||||
name: str | None = Field(default=None, min_length=1)
|
name: str | None = Field(default=None, min_length=1)
|
||||||
other_inst_id: str | None = None
|
other_inst_id: str | None = None
|
||||||
|
selected_openalex_institution_ids: list[str] | None = None
|
||||||
deleted: bool | 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 . import service
|
||||||
from .model import (
|
from .model import (
|
||||||
CreateOrganizationRequest,
|
CreateOrganizationRequest,
|
||||||
|
InstitutionAssociationsResponse,
|
||||||
OrganizationPage,
|
OrganizationPage,
|
||||||
OrganizationProfile,
|
OrganizationProfile,
|
||||||
UpdateOrganizationRequest,
|
UpdateOrganizationRequest,
|
||||||
@@ -19,6 +20,18 @@ from .model import (
|
|||||||
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
|
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)
|
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
|
||||||
async def get_organizations(
|
async def get_organizations(
|
||||||
page: int = Query(default=0, ge=0),
|
page: int = Query(default=0, ge=0),
|
||||||
|
|||||||
@@ -1,18 +1,43 @@
|
|||||||
|
import logging
|
||||||
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from fastapi import HTTPException, status
|
from fastapi import HTTPException, status
|
||||||
from sqlmodel import Session, func, select
|
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 (
|
from .model import (
|
||||||
CreateOrganizationRequest,
|
CreateOrganizationRequest,
|
||||||
|
InstitutionAssociation,
|
||||||
|
InstitutionAssociationsResponse,
|
||||||
OrganizationPage,
|
OrganizationPage,
|
||||||
OrganizationProfile,
|
OrganizationProfile,
|
||||||
UpdateOrganizationRequest,
|
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:
|
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
|
||||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
@@ -31,6 +56,27 @@ def _normalize_name(name: str) -> str:
|
|||||||
return normalized_name
|
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(
|
def _ensure_name_available(
|
||||||
session: Session,
|
session: Session,
|
||||||
name: str,
|
name: str,
|
||||||
@@ -79,18 +125,76 @@ def _member_counts(
|
|||||||
return {organization_id: count for organization_id, count in rows}
|
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(
|
def _to_profile(
|
||||||
organization: Organization, member_count: int
|
organization: Organization,
|
||||||
|
member_count: int,
|
||||||
|
institution_ids: list[str],
|
||||||
) -> OrganizationProfile:
|
) -> 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(
|
return OrganizationProfile(
|
||||||
id=organization.id,
|
id=organization.id,
|
||||||
name=organization.name,
|
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,
|
deleted=organization.deleted,
|
||||||
member_count=member_count,
|
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(
|
def _deactivate_organization_accounts(
|
||||||
session: Session, organization_id: uuid.UUID
|
session: Session, organization_id: uuid.UUID
|
||||||
) -> None:
|
) -> None:
|
||||||
@@ -106,6 +210,27 @@ def _deactivate_organization_accounts(
|
|||||||
session.add(account)
|
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(
|
def get_organizations(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessTokenMetadata,
|
access_token: AccessTokenMetadata,
|
||||||
@@ -130,10 +255,15 @@ def get_organizations(
|
|||||||
).all()
|
).all()
|
||||||
organization_ids = [organization.id for organization in organizations]
|
organization_ids = [organization.id for organization in organizations]
|
||||||
counts = _member_counts(session, organization_ids)
|
counts = _member_counts(session, organization_ids)
|
||||||
|
institution_ids = _institution_data(session, organization_ids)
|
||||||
|
|
||||||
return OrganizationPage(
|
return OrganizationPage(
|
||||||
items=[
|
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
|
for organization in organizations
|
||||||
],
|
],
|
||||||
total=total,
|
total=total,
|
||||||
@@ -153,12 +283,25 @@ def create_organization(
|
|||||||
|
|
||||||
organization = Organization(
|
organization = Organization(
|
||||||
name=name,
|
name=name,
|
||||||
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
|
|
||||||
)
|
)
|
||||||
session.add(organization)
|
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.commit()
|
||||||
session.refresh(organization)
|
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(
|
def update_organization(
|
||||||
@@ -174,10 +317,21 @@ def update_organization(
|
|||||||
name = _normalize_name(payload.name)
|
name = _normalize_name(payload.name)
|
||||||
_ensure_name_available(session, name, organization.id)
|
_ensure_name_available(session, name, organization.id)
|
||||||
organization.name = name
|
organization.name = name
|
||||||
if payload.other_inst_id is not None:
|
if payload.selected_openalex_institution_ids is not None:
|
||||||
organization.openalex_institution_id = payload.other_inst_id.strip() or 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 is not None:
|
||||||
if payload.deleted and not organization.deleted:
|
if payload.deleted and not organization.deleted:
|
||||||
|
_ensure_not_current_organization(session, access_token, organization.id)
|
||||||
_deactivate_organization_accounts(session, organization.id)
|
_deactivate_organization_accounts(session, organization.id)
|
||||||
organization.deleted = payload.deleted
|
organization.deleted = payload.deleted
|
||||||
|
|
||||||
@@ -185,7 +339,113 @@ def update_organization(
|
|||||||
session.commit()
|
session.commit()
|
||||||
session.refresh(organization)
|
session.refresh(organization)
|
||||||
counts = _member_counts(session, [organization.id])
|
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(
|
def delete_organization(
|
||||||
@@ -196,6 +456,7 @@ def delete_organization(
|
|||||||
_require_super_admin(access_token)
|
_require_super_admin(access_token)
|
||||||
organization = _get_organization_or_404(session, organization_id)
|
organization = _get_organization_or_404(session, organization_id)
|
||||||
if not organization.deleted:
|
if not organization.deleted:
|
||||||
|
_ensure_not_current_organization(session, access_token, organization.id)
|
||||||
_deactivate_organization_accounts(session, organization.id)
|
_deactivate_organization_accounts(session, organization.id)
|
||||||
organization.deleted = True
|
organization.deleted = True
|
||||||
session.add(organization)
|
session.add(organization)
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
|
import asyncio
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from fastapi import HTTPException
|
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 import service
|
||||||
from inse.organization_management.model import (
|
from inse.organization_management.model import (
|
||||||
CreateOrganizationRequest,
|
CreateOrganizationRequest,
|
||||||
@@ -22,10 +28,11 @@ def session():
|
|||||||
yield database_session
|
yield database_session
|
||||||
|
|
||||||
|
|
||||||
def token(role: UserRole, organization_id):
|
def token(role: UserRole, organization_id, real_account_id=None):
|
||||||
return SimpleNamespace(
|
return SimpleNamespace(
|
||||||
effective_role=role,
|
effective_role=role,
|
||||||
effective_organization_id=organization_id,
|
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
|
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):
|
def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||||
|
admin_scope = Organization(name="Admin scope for delete")
|
||||||
organization = Organization(name="Organization to delete")
|
organization = Organization(name="Organization to delete")
|
||||||
|
session.add(admin_scope)
|
||||||
session.add(organization)
|
session.add(organization)
|
||||||
session.flush()
|
session.flush()
|
||||||
active_account = Account(
|
active_account = Account(
|
||||||
@@ -129,7 +243,7 @@ def test_deleting_organization_deactivates_all_its_accounts(session):
|
|||||||
session.commit()
|
session.commit()
|
||||||
|
|
||||||
service.delete_organization(
|
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)
|
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):
|
def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||||
|
admin_scope = Organization(name="Admin scope for update")
|
||||||
organization = Organization(name="Organization to update")
|
organization = Organization(name="Organization to update")
|
||||||
|
session.add(admin_scope)
|
||||||
session.add(organization)
|
session.add(organization)
|
||||||
session.flush()
|
session.flush()
|
||||||
account = Account(
|
account = Account(
|
||||||
@@ -155,7 +271,7 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
|
|||||||
|
|
||||||
service.update_organization(
|
service.update_organization(
|
||||||
session,
|
session,
|
||||||
token(UserRole.SUPER_ADMIN, organization.id),
|
token(UserRole.SUPER_ADMIN, admin_scope.id),
|
||||||
organization.id,
|
organization.id,
|
||||||
UpdateOrganizationRequest(deleted=True),
|
UpdateOrganizationRequest(deleted=True),
|
||||||
)
|
)
|
||||||
@@ -165,6 +281,61 @@ def test_marking_organization_deleted_deactivates_its_accounts(session):
|
|||||||
assert account.epoch == 1
|
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])
|
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||||
def test_only_superadmin_can_create_organizations(session, role):
|
def test_only_superadmin_can_create_organizations(session, role):
|
||||||
organization = Organization(name="Scope")
|
organization = Organization(name="Scope")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index."""
|
"""Find patents for extracted OpenAlex keywords via IPC/CPC reverse lookup."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
@@ -31,7 +31,6 @@ from inse.patents.ipc_lookup import (
|
|||||||
)
|
)
|
||||||
from inse.patents.ipc_search_client import IpcSearchClient
|
from inse.patents.ipc_search_client import IpcSearchClient
|
||||||
from inse.patents.keywords.model import (
|
from inse.patents.keywords.model import (
|
||||||
KeywordEvidence,
|
|
||||||
KeywordPatentMappingStatus,
|
KeywordPatentMappingStatus,
|
||||||
KeywordPatentMatch,
|
KeywordPatentMatch,
|
||||||
KeywordPatentSearchDiagnostics,
|
KeywordPatentSearchDiagnostics,
|
||||||
@@ -76,13 +75,7 @@ _MIN_LEADER_RELATIVE_MASS = 0.20
|
|||||||
_MIN_LEADER_MASS_RATIO = 1.5
|
_MIN_LEADER_MASS_RATIO = 1.5
|
||||||
_TARGET_CUMULATIVE_CLUSTER_MASS = 0.75
|
_TARGET_CUMULATIVE_CLUSTER_MASS = 0.75
|
||||||
_MIN_PATENT_MATCH_SCORE = 0.50
|
_MIN_PATENT_MATCH_SCORE = 0.50
|
||||||
_MIN_TEXT_PATENT_MATCH_SCORE = 0.30
|
|
||||||
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
|
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
|
||||||
# When IPC mapping is abstained, score only topic + text evidence.
|
|
||||||
_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55}
|
|
||||||
# Also try title/abstract search when IPC mapping produced terms but scoring
|
|
||||||
# returned no patents (empty retrieval or over-filtering).
|
|
||||||
_TEXT_SEARCH_AFTER_EMPTY_IPC = True
|
|
||||||
_TOPIC_SCORE_TOPIC_ID = 1.0
|
_TOPIC_SCORE_TOPIC_ID = 1.0
|
||||||
_TOPIC_SCORE_SUBFIELD = 0.7
|
_TOPIC_SCORE_SUBFIELD = 0.7
|
||||||
_TOPIC_SCORE_COMPATIBLE_FIELD = 0.3
|
_TOPIC_SCORE_COMPATIBLE_FIELD = 0.3
|
||||||
@@ -618,12 +611,6 @@ class TopicEvidence:
|
|||||||
score: float
|
score: float
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class TextGateDecision:
|
|
||||||
accepted: bool
|
|
||||||
reason: str
|
|
||||||
|
|
||||||
|
|
||||||
def _compute_topic_evidence(
|
def _compute_topic_evidence(
|
||||||
patent_topics: list[MappedOpenAlexTopic],
|
patent_topics: list[MappedOpenAlexTopic],
|
||||||
keyword_topic_ids: frozenset[str],
|
keyword_topic_ids: frozenset[str],
|
||||||
@@ -702,16 +689,6 @@ def _tokenize_words(text: str) -> list[str]:
|
|||||||
return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold())
|
return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold())
|
||||||
|
|
||||||
|
|
||||||
def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool:
|
|
||||||
if not needle or len(needle) > len(haystack):
|
|
||||||
return False
|
|
||||||
width = len(needle)
|
|
||||||
for index in range(len(haystack) - width + 1):
|
|
||||||
if haystack[index : index + width] == needle:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _token_set(tokens: list[str]) -> set[str]:
|
def _token_set(tokens: list[str]) -> set[str]:
|
||||||
return set(tokens)
|
return set(tokens)
|
||||||
|
|
||||||
@@ -735,23 +712,6 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]:
|
|||||||
return terms
|
return terms
|
||||||
|
|
||||||
|
|
||||||
def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]:
|
|
||||||
"""Full phrases for ES title/abstract retrieval (text path)."""
|
|
||||||
phrases: list[str] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
for item in items:
|
|
||||||
for value in (item.keyword, item.topic_display_name):
|
|
||||||
cleaned = " ".join((value or "").strip().split())
|
|
||||||
if len(cleaned) < 3:
|
|
||||||
continue
|
|
||||||
key = cleaned.casefold()
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
phrases.append(cleaned)
|
|
||||||
return phrases
|
|
||||||
|
|
||||||
|
|
||||||
def _text_overlap_score(
|
def _text_overlap_score(
|
||||||
patent: model.PatentEntry,
|
patent: model.PatentEntry,
|
||||||
search_terms: list[str],
|
search_terms: list[str],
|
||||||
@@ -772,173 +732,6 @@ def _text_overlap_score(
|
|||||||
return min(hits / 3, 1.0)
|
return min(hits / 3, 1.0)
|
||||||
|
|
||||||
|
|
||||||
def _text_match_kind(
|
|
||||||
*,
|
|
||||||
phrase_in_title: bool,
|
|
||||||
phrase_in_abstract: bool,
|
|
||||||
full_token_match: bool,
|
|
||||||
partial_token_match: bool,
|
|
||||||
) -> str:
|
|
||||||
if phrase_in_title:
|
|
||||||
return "phrase_title"
|
|
||||||
if phrase_in_abstract:
|
|
||||||
return "phrase_abstract"
|
|
||||||
if full_token_match:
|
|
||||||
return "full_token"
|
|
||||||
if partial_token_match:
|
|
||||||
return "partial_token"
|
|
||||||
return "none"
|
|
||||||
|
|
||||||
|
|
||||||
def _collect_keyword_text_evidence(
|
|
||||||
patent: model.PatentEntry,
|
|
||||||
phrases: list[str],
|
|
||||||
search_terms: list[str],
|
|
||||||
) -> KeywordEvidence:
|
|
||||||
"""Record phrase / full-token / partial-token evidence separately."""
|
|
||||||
title_tokens = _tokenize_words(patent.title or "")
|
|
||||||
abstract_tokens = _tokenize_words(patent.abstract or "")
|
|
||||||
combined_tokens = _token_set(title_tokens + abstract_tokens)
|
|
||||||
|
|
||||||
phrase_in_title = False
|
|
||||||
phrase_in_abstract = False
|
|
||||||
full_token_match = False
|
|
||||||
partial_token_match = False
|
|
||||||
matched_phrases: list[str] = []
|
|
||||||
|
|
||||||
for phrase in phrases:
|
|
||||||
phrase_tokens = _tokenize_words(phrase)
|
|
||||||
if not phrase_tokens:
|
|
||||||
continue
|
|
||||||
if _contains_token_sequence(title_tokens, phrase_tokens):
|
|
||||||
phrase_in_title = True
|
|
||||||
matched_phrases.append(phrase)
|
|
||||||
elif _contains_token_sequence(abstract_tokens, phrase_tokens):
|
|
||||||
phrase_in_abstract = True
|
|
||||||
matched_phrases.append(phrase)
|
|
||||||
|
|
||||||
present = [token for token in phrase_tokens if token in combined_tokens]
|
|
||||||
if present and len(present) == len(phrase_tokens):
|
|
||||||
full_token_match = True
|
|
||||||
elif present:
|
|
||||||
partial_token_match = True
|
|
||||||
|
|
||||||
matched_words = [term for term in search_terms if term in combined_tokens]
|
|
||||||
if matched_words and not full_token_match and not partial_token_match:
|
|
||||||
# Lone search-term hits without a covering phrase count as partial.
|
|
||||||
partial_token_match = True
|
|
||||||
|
|
||||||
word_match_score = (
|
|
||||||
min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0
|
|
||||||
)
|
|
||||||
kind = _text_match_kind(
|
|
||||||
phrase_in_title=phrase_in_title,
|
|
||||||
phrase_in_abstract=phrase_in_abstract,
|
|
||||||
full_token_match=full_token_match,
|
|
||||||
partial_token_match=partial_token_match,
|
|
||||||
)
|
|
||||||
|
|
||||||
return KeywordEvidence(
|
|
||||||
phrase_in_title=phrase_in_title,
|
|
||||||
phrase_in_abstract=phrase_in_abstract,
|
|
||||||
full_token_match=full_token_match,
|
|
||||||
partial_token_match=partial_token_match,
|
|
||||||
word_match_score=round(word_match_score, 4),
|
|
||||||
matched_phrases=list(dict.fromkeys(matched_phrases)),
|
|
||||||
matched_words=matched_words,
|
|
||||||
text_match_kind=kind,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _keyword_text_score(evidence: KeywordEvidence) -> float:
|
|
||||||
if evidence.phrase_in_title:
|
|
||||||
return 1.0
|
|
||||||
if evidence.phrase_in_abstract:
|
|
||||||
return 0.85
|
|
||||||
if evidence.full_token_match:
|
|
||||||
return 0.55
|
|
||||||
if evidence.partial_token_match:
|
|
||||||
return 0.25
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _exact_topic_or_subfield_match(
|
|
||||||
patent_topics: list[MappedOpenAlexTopic],
|
|
||||||
keyword_topic_ids: frozenset[str],
|
|
||||||
keyword_subfield_names: frozenset[str],
|
|
||||||
) -> bool:
|
|
||||||
evidence = _compute_topic_evidence(
|
|
||||||
patent_topics,
|
|
||||||
keyword_topic_ids,
|
|
||||||
keyword_subfield_names,
|
|
||||||
frozenset(),
|
|
||||||
)
|
|
||||||
return evidence.match_kind in {"topic_id", "subfield"}
|
|
||||||
|
|
||||||
|
|
||||||
def _keyword_text_passes_relevance_gate(
|
|
||||||
evidence: KeywordEvidence,
|
|
||||||
*,
|
|
||||||
topic_evidence: TopicEvidence,
|
|
||||||
) -> TextGateDecision:
|
|
||||||
"""Keyword text acceptance policy (no domain hardcoding).
|
|
||||||
|
|
||||||
Accept:
|
|
||||||
- phrase in title (strong)
|
|
||||||
- phrase in abstract (medium)
|
|
||||||
- exact topic/subfield together with full token text evidence
|
|
||||||
Reject:
|
|
||||||
- partial/general words alone
|
|
||||||
- compatible field alone
|
|
||||||
- exact topic/subfield without text evidence
|
|
||||||
"""
|
|
||||||
exact = topic_evidence.match_kind in {"topic_id", "subfield"}
|
|
||||||
|
|
||||||
if evidence.phrase_in_title:
|
|
||||||
return TextGateDecision(True, "phrase_in_title")
|
|
||||||
if evidence.phrase_in_abstract:
|
|
||||||
return TextGateDecision(True, "phrase_in_abstract")
|
|
||||||
if exact and evidence.full_token_match:
|
|
||||||
return TextGateDecision(
|
|
||||||
True,
|
|
||||||
f"{topic_evidence.match_kind}_with_full_token_match",
|
|
||||||
)
|
|
||||||
if exact and evidence.partial_token_match:
|
|
||||||
return TextGateDecision(False, "exact_topic_with_partial_tokens_only")
|
|
||||||
if exact:
|
|
||||||
return TextGateDecision(False, "exact_topic_without_text")
|
|
||||||
if topic_evidence.match_kind == "compatible_field":
|
|
||||||
return TextGateDecision(False, "compatible_field_only")
|
|
||||||
if evidence.partial_token_match or evidence.matched_words:
|
|
||||||
return TextGateDecision(False, "partial_or_loose_words_only")
|
|
||||||
return TextGateDecision(False, "insufficient_evidence")
|
|
||||||
|
|
||||||
|
|
||||||
def _matched_keyword_labels_from_evidence(
|
|
||||||
items: list[KeywordPatentSearchItem],
|
|
||||||
evidence: KeywordEvidence,
|
|
||||||
) -> list[str]:
|
|
||||||
matched: list[str] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases}
|
|
||||||
word_keys = set(evidence.matched_words)
|
|
||||||
|
|
||||||
for item in items:
|
|
||||||
for value in (item.keyword, item.topic_display_name):
|
|
||||||
label = (value or "").strip()
|
|
||||||
if not label:
|
|
||||||
continue
|
|
||||||
key = label.casefold()
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
label_tokens = _tokenize_words(label)
|
|
||||||
if key in phrase_keys or any(token in word_keys for token in label_tokens):
|
|
||||||
seen.add(key)
|
|
||||||
matched.append(label)
|
|
||||||
break
|
|
||||||
return matched
|
|
||||||
|
|
||||||
|
|
||||||
def _patent_passes_relevance_gate(
|
def _patent_passes_relevance_gate(
|
||||||
patent_topics: list[MappedOpenAlexTopic],
|
patent_topics: list[MappedOpenAlexTopic],
|
||||||
*,
|
*,
|
||||||
@@ -1261,210 +1054,6 @@ async def _score_patents_with_ipc(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async def _score_patents_text_search(
|
|
||||||
*,
|
|
||||||
raw_patents: list[model.PatentEntry],
|
|
||||||
search_keywords: list[KeywordPatentSearchItem],
|
|
||||||
phrases: list[str],
|
|
||||||
text_search_terms: list[str],
|
|
||||||
keyword_topic_ids: frozenset[str],
|
|
||||||
keyword_subfield_names: frozenset[str],
|
|
||||||
keyword_soft_field_names: frozenset[str],
|
|
||||||
resolver: PatentOpenAlexMappingResolver,
|
|
||||||
) -> tuple[list[KeywordPatentMatch], dict[str, int]]:
|
|
||||||
"""Score patents without IPC using graded topic + structured text evidence."""
|
|
||||||
patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents)
|
|
||||||
scored: list[KeywordPatentMatch] = []
|
|
||||||
filtered_by_relevance_gate = 0
|
|
||||||
filtered_by_min_score = 0
|
|
||||||
passed_relevance_gate = 0
|
|
||||||
|
|
||||||
for patent in raw_patents:
|
|
||||||
patent_topics = patent_topics_by_key.get(patent_map_key(patent), [])
|
|
||||||
evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms)
|
|
||||||
topic_evidence = _compute_topic_evidence(
|
|
||||||
patent_topics,
|
|
||||||
keyword_topic_ids,
|
|
||||||
keyword_subfield_names,
|
|
||||||
keyword_soft_field_names,
|
|
||||||
)
|
|
||||||
decision = _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=topic_evidence,
|
|
||||||
)
|
|
||||||
if not decision.accepted:
|
|
||||||
filtered_by_relevance_gate += 1
|
|
||||||
logger.info(
|
|
||||||
"Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f "
|
|
||||||
"text_kind=%s phrase_title=%s phrase_abstract=%s "
|
|
||||||
"full_token=%s partial_token=%s reason=%s",
|
|
||||||
patent.patent_id,
|
|
||||||
patent.title,
|
|
||||||
topic_evidence.match_kind,
|
|
||||||
topic_evidence.score,
|
|
||||||
evidence.text_match_kind,
|
|
||||||
evidence.phrase_in_title,
|
|
||||||
evidence.phrase_in_abstract,
|
|
||||||
evidence.full_token_match,
|
|
||||||
evidence.partial_token_match,
|
|
||||||
decision.reason,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
passed_relevance_gate += 1
|
|
||||||
text_score = _keyword_text_score(evidence)
|
|
||||||
# Field-only remains a weak ranking signal when already accepted via phrase.
|
|
||||||
score = _compute_final_score(
|
|
||||||
0.0,
|
|
||||||
topic_evidence.score,
|
|
||||||
text_score,
|
|
||||||
weights=_TEXT_SCORE_WEIGHTS,
|
|
||||||
)
|
|
||||||
if score < _MIN_TEXT_PATENT_MATCH_SCORE:
|
|
||||||
filtered_by_min_score += 1
|
|
||||||
logger.info(
|
|
||||||
"Text reject: id=%s reason=below_min_score score=%.4f",
|
|
||||||
patent.patent_id,
|
|
||||||
score,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f "
|
|
||||||
"text_kind=%s text_score=%.2f final_score=%.4f reason=%s",
|
|
||||||
patent.patent_id,
|
|
||||||
patent.title,
|
|
||||||
topic_evidence.match_kind,
|
|
||||||
topic_evidence.score,
|
|
||||||
evidence.text_match_kind,
|
|
||||||
text_score,
|
|
||||||
score,
|
|
||||||
decision.reason,
|
|
||||||
)
|
|
||||||
scored.append(
|
|
||||||
KeywordPatentMatch(
|
|
||||||
patent=patent,
|
|
||||||
match_score=score,
|
|
||||||
ipc_score=0.0,
|
|
||||||
topic_score=topic_evidence.score,
|
|
||||||
text_score=text_score,
|
|
||||||
matched_keywords=_matched_keyword_labels_from_evidence(
|
|
||||||
search_keywords,
|
|
||||||
evidence,
|
|
||||||
),
|
|
||||||
matched_ipc_symbols=[],
|
|
||||||
text_retrieval=True,
|
|
||||||
keyword_evidence=evidence,
|
|
||||||
topic_match_kind=topic_evidence.match_kind,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent text search: filtered_by_relevance_gate=%d "
|
|
||||||
"filtered_by_min_score=%d passed_relevance_gate=%d scored=%d",
|
|
||||||
filtered_by_relevance_gate,
|
|
||||||
filtered_by_min_score,
|
|
||||||
passed_relevance_gate,
|
|
||||||
len(scored),
|
|
||||||
)
|
|
||||||
return scored, {
|
|
||||||
"filtered_by_relevance_gate": filtered_by_relevance_gate,
|
|
||||||
"filtered_by_min_score": filtered_by_min_score,
|
|
||||||
"passed_relevance_gate": passed_relevance_gate,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def _search_patents_text_search(
|
|
||||||
*,
|
|
||||||
client: BasePatentSearchClient,
|
|
||||||
queries: IpcPatentSearchQueries,
|
|
||||||
ipc_search: IpcSearchClient,
|
|
||||||
resolver: PatentOpenAlexMappingResolver,
|
|
||||||
search_keywords: list[KeywordPatentSearchItem],
|
|
||||||
keyword_topic_ids: frozenset[str],
|
|
||||||
keyword_subfield_names: frozenset[str],
|
|
||||||
keyword_soft_field_names: frozenset[str],
|
|
||||||
mapping_status: KeywordPatentMappingStatus,
|
|
||||||
ipc_cluster_selections: list[dict] | None = None,
|
|
||||||
) -> PatentsByKeywordsResponse:
|
|
||||||
cluster_dicts = list(ipc_cluster_selections or [])
|
|
||||||
phrases = _text_search_phrases(search_keywords)
|
|
||||||
text_search_terms = _text_search_terms(search_keywords)
|
|
||||||
if not phrases:
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent text search: no phrases for keywords %s",
|
|
||||||
[item.keyword for item in search_keywords],
|
|
||||||
)
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=0,
|
|
||||||
patents=[],
|
|
||||||
mapping_status="no_patents_found",
|
|
||||||
diagnostics=_empty_diagnostics(
|
|
||||||
search_path="text",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent text search: mapping_status=%s phrases=%s",
|
|
||||||
mapping_status,
|
|
||||||
phrases,
|
|
||||||
)
|
|
||||||
raw_patents = await _fetch_patents_for_queries(
|
|
||||||
client,
|
|
||||||
queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS),
|
|
||||||
queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS),
|
|
||||||
)
|
|
||||||
if raw_patents is None:
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=0,
|
|
||||||
patents=[],
|
|
||||||
mapping_status="search_error",
|
|
||||||
diagnostics=_empty_diagnostics(
|
|
||||||
search_path="text",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents))
|
|
||||||
scored, filter_counts = await _score_patents_text_search(
|
|
||||||
raw_patents=raw_patents,
|
|
||||||
search_keywords=search_keywords,
|
|
||||||
phrases=phrases,
|
|
||||||
text_search_terms=text_search_terms,
|
|
||||||
keyword_topic_ids=keyword_topic_ids,
|
|
||||||
keyword_subfield_names=keyword_subfield_names,
|
|
||||||
keyword_soft_field_names=keyword_soft_field_names,
|
|
||||||
resolver=resolver,
|
|
||||||
)
|
|
||||||
scored, diagnostics = _finalize_scored_patents(
|
|
||||||
scored,
|
|
||||||
raw_count=len(raw_patents),
|
|
||||||
filtered_by_ipc=0,
|
|
||||||
filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"],
|
|
||||||
filtered_by_min_score=filter_counts["filtered_by_min_score"],
|
|
||||||
passed_relevance_gate=filter_counts["passed_relevance_gate"],
|
|
||||||
search_path="text",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
)
|
|
||||||
await enrich_patents_classifications([item.patent for item in scored], ipc_search)
|
|
||||||
|
|
||||||
if not scored:
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=0,
|
|
||||||
patents=[],
|
|
||||||
mapping_status="no_patents_found",
|
|
||||||
diagnostics=diagnostics,
|
|
||||||
)
|
|
||||||
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=len(scored),
|
|
||||||
patents=scored,
|
|
||||||
mapping_status=mapping_status,
|
|
||||||
diagnostics=diagnostics,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def get_patents_by_keywords(
|
async def get_patents_by_keywords(
|
||||||
request: PatentsByKeywordsRequest,
|
request: PatentsByKeywordsRequest,
|
||||||
*,
|
*,
|
||||||
@@ -1528,21 +1117,18 @@ async def get_patents_by_keywords(
|
|||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"Keyword patent search: no IPC search terms for keywords %s "
|
"Keyword patent search: no IPC search terms for keywords %s "
|
||||||
"(mapping_status=%s) — trying keyword text search",
|
"(mapping_status=%s)",
|
||||||
[item.keyword for item in search_keywords],
|
[item.keyword for item in search_keywords],
|
||||||
mapping_status,
|
mapping_status,
|
||||||
)
|
)
|
||||||
return await _search_patents_text_search(
|
return PatentsByKeywordsResponse(
|
||||||
client=client,
|
patent_count=0,
|
||||||
queries=queries,
|
patents=[],
|
||||||
ipc_search=ipc_search,
|
|
||||||
resolver=resolver,
|
|
||||||
search_keywords=search_keywords,
|
|
||||||
keyword_topic_ids=keyword_topic_ids,
|
|
||||||
keyword_subfield_names=keyword_subfield_names,
|
|
||||||
keyword_soft_field_names=keyword_soft_field_names,
|
|
||||||
mapping_status=mapping_status,
|
mapping_status=mapping_status,
|
||||||
ipc_cluster_selections=cluster_dicts,
|
diagnostics=_empty_diagnostics(
|
||||||
|
search_path="none",
|
||||||
|
ipc_cluster_selections=cluster_dicts,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
text_search_terms = _text_search_terms(search_keywords)
|
text_search_terms = _text_search_terms(search_keywords)
|
||||||
@@ -1594,31 +1180,11 @@ async def get_patents_by_keywords(
|
|||||||
diagnostics=diagnostics,
|
diagnostics=diagnostics,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not _TEXT_SEARCH_AFTER_EMPTY_IPC:
|
return PatentsByKeywordsResponse(
|
||||||
return PatentsByKeywordsResponse(
|
patent_count=0,
|
||||||
patent_count=0,
|
patents=[],
|
||||||
patents=[],
|
mapping_status="no_patents_found",
|
||||||
mapping_status="no_patents_found",
|
diagnostics=diagnostics,
|
||||||
diagnostics=diagnostics,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent search: IPC path yielded no scored patents — "
|
|
||||||
"trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)"
|
|
||||||
)
|
|
||||||
return await _search_patents_text_search(
|
|
||||||
client=client,
|
|
||||||
queries=queries,
|
|
||||||
ipc_search=ipc_search,
|
|
||||||
resolver=resolver,
|
|
||||||
search_keywords=search_keywords,
|
|
||||||
keyword_topic_ids=keyword_topic_ids,
|
|
||||||
keyword_subfield_names=keyword_subfield_names,
|
|
||||||
keyword_soft_field_names=keyword_soft_field_names,
|
|
||||||
# IPC was selected but produced no usable hits; UI treats this like
|
|
||||||
# uncertain IPC evidence and labels patents via text_retrieval.
|
|
||||||
mapping_status="uncertain",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -46,19 +46,12 @@ _USPTO_SOURCE_FIELDS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
_MIN_MATCH_TERM_LEN = 4
|
_MIN_MATCH_TERM_LEN = 4
|
||||||
_MIN_TEXT_PHRASE_LEN = 3
|
|
||||||
|
|
||||||
# Prefer concrete group/subgroup hits over broad subclass prefixes.
|
# Prefer concrete group/subgroup hits over broad subclass prefixes.
|
||||||
_BOOST_SUBGROUP = 4.0
|
_BOOST_SUBGROUP = 4.0
|
||||||
_BOOST_MAIN_GROUP = 2.5
|
_BOOST_MAIN_GROUP = 2.5
|
||||||
_BOOST_SUBCLASS = 1.0
|
_BOOST_SUBCLASS = 1.0
|
||||||
|
|
||||||
# Text search: prefer exact phrases in title over abstract / loose match.
|
|
||||||
_BOOST_TEXT_PHRASE_TITLE = 5.0
|
|
||||||
_BOOST_TEXT_PHRASE_ABSTRACT = 3.0
|
|
||||||
_BOOST_TEXT_MATCH_TITLE = 1.5
|
|
||||||
_BOOST_TEXT_MATCH_ABSTRACT = 1.0
|
|
||||||
|
|
||||||
|
|
||||||
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
|
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
|
||||||
cleaned = term.strip()
|
cleaned = term.strip()
|
||||||
@@ -157,76 +150,6 @@ def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[s
|
|||||||
return clauses
|
return clauses
|
||||||
|
|
||||||
|
|
||||||
def _normalize_text_phrases(phrases: list[str]) -> list[str]:
|
|
||||||
cleaned: list[str] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
for phrase in phrases:
|
|
||||||
value = " ".join((phrase or "").strip().split())
|
|
||||||
if len(value) < _MIN_TEXT_PHRASE_LEN:
|
|
||||||
continue
|
|
||||||
key = value.casefold()
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
cleaned.append(value)
|
|
||||||
return cleaned
|
|
||||||
|
|
||||||
|
|
||||||
def _text_match_clauses(
|
|
||||||
phrases: list[str],
|
|
||||||
*,
|
|
||||||
title_fields: tuple[str, ...],
|
|
||||||
abstract_field: str,
|
|
||||||
) -> list[dict[str, Any]]:
|
|
||||||
"""Build title/abstract should-clauses with phrase boosts over loose match."""
|
|
||||||
clauses: list[dict[str, Any]] = []
|
|
||||||
for phrase in _normalize_text_phrases(phrases):
|
|
||||||
for field in title_fields:
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match_phrase": {
|
|
||||||
field: {
|
|
||||||
"query": phrase,
|
|
||||||
"boost": _BOOST_TEXT_PHRASE_TITLE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match": {
|
|
||||||
field: {
|
|
||||||
"query": phrase,
|
|
||||||
"operator": "and",
|
|
||||||
"boost": _BOOST_TEXT_MATCH_TITLE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match_phrase": {
|
|
||||||
abstract_field: {
|
|
||||||
"query": phrase,
|
|
||||||
"boost": _BOOST_TEXT_PHRASE_ABSTRACT,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match": {
|
|
||||||
abstract_field: {
|
|
||||||
"query": phrase,
|
|
||||||
"operator": "and",
|
|
||||||
"boost": _BOOST_TEXT_MATCH_ABSTRACT,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return clauses
|
|
||||||
|
|
||||||
|
|
||||||
class IpcPatentSearchQueries:
|
class IpcPatentSearchQueries:
|
||||||
def epo_query_by_ipc_terms(
|
def epo_query_by_ipc_terms(
|
||||||
self,
|
self,
|
||||||
@@ -299,55 +222,3 @@ class IpcPatentSearchQueries:
|
|||||||
size: int = DEFAULT_SEARCH_SIZE,
|
size: int = DEFAULT_SEARCH_SIZE,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
|
return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
|
||||||
|
|
||||||
def epo_query_by_text_phrases(
|
|
||||||
self,
|
|
||||||
phrases: list[str],
|
|
||||||
size: int = DEFAULT_SEARCH_SIZE,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
should = _text_match_clauses(
|
|
||||||
phrases,
|
|
||||||
title_fields=("title_en", "title_de"),
|
|
||||||
abstract_field="abstract",
|
|
||||||
)
|
|
||||||
query: dict[str, Any] = (
|
|
||||||
{"match_none": {}}
|
|
||||||
if not should
|
|
||||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"size": size,
|
|
||||||
"track_total_hits": True,
|
|
||||||
"sort": [
|
|
||||||
{"_score": {"order": "desc"}},
|
|
||||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
|
||||||
],
|
|
||||||
"_source": _PATENT_SOURCE_FIELDS,
|
|
||||||
"query": query,
|
|
||||||
}
|
|
||||||
|
|
||||||
def uspto_query_by_text_phrases(
|
|
||||||
self,
|
|
||||||
phrases: list[str],
|
|
||||||
size: int = DEFAULT_SEARCH_SIZE,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
should = _text_match_clauses(
|
|
||||||
phrases,
|
|
||||||
title_fields=("title",),
|
|
||||||
abstract_field="abstract",
|
|
||||||
)
|
|
||||||
query: dict[str, Any] = (
|
|
||||||
{"match_none": {}}
|
|
||||||
if not should
|
|
||||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"size": size,
|
|
||||||
"track_total_hits": True,
|
|
||||||
"sort": [
|
|
||||||
{"_score": {"order": "desc"}},
|
|
||||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
|
||||||
],
|
|
||||||
"_source": _USPTO_SOURCE_FIELDS,
|
|
||||||
"query": query,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,21 +10,17 @@ from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
|
|||||||
from inse.patents.common import model
|
from inse.patents.common import model
|
||||||
from inse.patents.keywords.logic import (
|
from inse.patents.keywords.logic import (
|
||||||
TopicEvidence,
|
TopicEvidence,
|
||||||
_aggregate_subclass_clusters,
|
|
||||||
_collect_keyword_text_evidence,
|
|
||||||
_compute_final_score,
|
_compute_final_score,
|
||||||
_compute_topic_evidence,
|
_compute_topic_evidence,
|
||||||
_exact_topic_or_subfield_match,
|
|
||||||
_filter_keywords_for_patent_search,
|
_filter_keywords_for_patent_search,
|
||||||
_ipc_hierarchy_quality,
|
_ipc_hierarchy_quality,
|
||||||
_keyword_is_patent_searchable,
|
_keyword_is_patent_searchable,
|
||||||
_keyword_text_passes_relevance_gate,
|
|
||||||
_keyword_text_score,
|
|
||||||
_patent_passes_relevance_gate,
|
_patent_passes_relevance_gate,
|
||||||
_patent_search_terms,
|
_patent_search_terms,
|
||||||
_score_ipc_match,
|
_score_ipc_match,
|
||||||
_score_patent,
|
_score_patent,
|
||||||
_select_dominant_clusters,
|
_select_dominant_clusters,
|
||||||
|
_aggregate_subclass_clusters,
|
||||||
_term_from_ipc_match,
|
_term_from_ipc_match,
|
||||||
_text_overlap_score,
|
_text_overlap_score,
|
||||||
_text_search_terms,
|
_text_search_terms,
|
||||||
@@ -34,10 +30,6 @@ from inse.patents.keywords.logic import (
|
|||||||
get_patents_by_keywords,
|
get_patents_by_keywords,
|
||||||
select_ipc_matches_by_cluster_mass,
|
select_ipc_matches_by_cluster_mass,
|
||||||
)
|
)
|
||||||
from inse.patents.keywords.model import (
|
|
||||||
KeywordPatentSearchItem,
|
|
||||||
PatentsByKeywordsRequest,
|
|
||||||
)
|
|
||||||
from inse.patents.keywords.reverse_lookup import (
|
from inse.patents.keywords.reverse_lookup import (
|
||||||
IpcCodeMatch,
|
IpcCodeMatch,
|
||||||
_dedupe_ipc_matches,
|
_dedupe_ipc_matches,
|
||||||
@@ -45,6 +37,7 @@ from inse.patents.keywords.reverse_lookup import (
|
|||||||
_weighted_score,
|
_weighted_score,
|
||||||
clear_reverse_lookup_caches,
|
clear_reverse_lookup_caches,
|
||||||
)
|
)
|
||||||
|
from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
|
||||||
from inse.patents.keywords.search_queries import (
|
from inse.patents.keywords.search_queries import (
|
||||||
IpcPatentSearchQueries,
|
IpcPatentSearchQueries,
|
||||||
_search_terms_for_symbol,
|
_search_terms_for_symbol,
|
||||||
@@ -646,132 +639,6 @@ def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None:
|
|||||||
assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0
|
assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0
|
||||||
|
|
||||||
|
|
||||||
def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None:
|
|
||||||
"""Soft field / loose words must not accept a mechanical separator patent."""
|
|
||||||
patent = model.PatentEntry(
|
|
||||||
patent_id="EP-MECH",
|
|
||||||
source="EPO",
|
|
||||||
title=(
|
|
||||||
"Rotating machine for separating materials in different "
|
|
||||||
"states of aggregation"
|
|
||||||
),
|
|
||||||
abstract="Apparatus for mechanical separation of materials.",
|
|
||||||
ipc=["B01D45/12"],
|
|
||||||
)
|
|
||||||
phrases = ["Organic Chemistry", "organische Chemie"]
|
|
||||||
terms = ["organic", "chemistry", "organische", "chemie"]
|
|
||||||
evidence = _collect_keyword_text_evidence(patent, phrases, terms)
|
|
||||||
|
|
||||||
assert evidence.phrase_in_title is False
|
|
||||||
assert evidence.phrase_in_abstract is False
|
|
||||||
assert evidence.full_token_match is False
|
|
||||||
assert evidence.matched_phrases == []
|
|
||||||
assert evidence.matched_words == []
|
|
||||||
|
|
||||||
field_only = TopicEvidence(match_kind="compatible_field", score=0.3)
|
|
||||||
assert not _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=field_only,
|
|
||||||
).accepted
|
|
||||||
exact = TopicEvidence(match_kind="topic_id", score=1.0)
|
|
||||||
assert not _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=exact,
|
|
||||||
).accepted
|
|
||||||
|
|
||||||
|
|
||||||
def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None:
|
|
||||||
phrase_patent = model.PatentEntry(
|
|
||||||
patent_id="EP-PHRASE",
|
|
||||||
source="EPO",
|
|
||||||
title="Process for organic chemistry synthesis",
|
|
||||||
abstract="Catalytic reactions.",
|
|
||||||
)
|
|
||||||
phrases = ["organic chemistry"]
|
|
||||||
terms = ["organic", "chemistry"]
|
|
||||||
evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms)
|
|
||||||
assert evidence.phrase_in_title is True
|
|
||||||
assert evidence.text_match_kind == "phrase_title"
|
|
||||||
assert _keyword_text_score(evidence) == 1.0
|
|
||||||
assert _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
|
|
||||||
).accepted
|
|
||||||
|
|
||||||
full_token_patent = model.PatentEntry(
|
|
||||||
patent_id="EP-WORDS",
|
|
||||||
source="EPO",
|
|
||||||
title="Catalytic organic synthesis method",
|
|
||||||
abstract="Uses chemistry laboratory techniques.",
|
|
||||||
)
|
|
||||||
full_evidence = _collect_keyword_text_evidence(
|
|
||||||
full_token_patent,
|
|
||||||
phrases,
|
|
||||||
terms,
|
|
||||||
)
|
|
||||||
assert full_evidence.phrase_in_title is False
|
|
||||||
assert full_evidence.phrase_in_abstract is False
|
|
||||||
assert full_evidence.full_token_match is True
|
|
||||||
assert not _keyword_text_passes_relevance_gate(
|
|
||||||
full_evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
|
|
||||||
).accepted
|
|
||||||
assert _keyword_text_passes_relevance_gate(
|
|
||||||
full_evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
|
|
||||||
).accepted
|
|
||||||
|
|
||||||
partial_patent = model.PatentEntry(
|
|
||||||
patent_id="EP-PARTIAL",
|
|
||||||
source="EPO",
|
|
||||||
title="Organic polymer blend",
|
|
||||||
abstract="Industrial materials processing.",
|
|
||||||
)
|
|
||||||
partial_evidence = _collect_keyword_text_evidence(
|
|
||||||
partial_patent,
|
|
||||||
phrases,
|
|
||||||
terms,
|
|
||||||
)
|
|
||||||
assert partial_evidence.partial_token_match is True
|
|
||||||
assert partial_evidence.full_token_match is False
|
|
||||||
decision = _keyword_text_passes_relevance_gate(
|
|
||||||
partial_evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
|
|
||||||
)
|
|
||||||
assert not decision.accepted
|
|
||||||
assert decision.reason == "exact_topic_with_partial_tokens_only"
|
|
||||||
|
|
||||||
assert _exact_topic_or_subfield_match(
|
|
||||||
[
|
|
||||||
MappedOpenAlexTopic(
|
|
||||||
topic_id="https://openalex.org/TORG",
|
|
||||||
topic_display_name="Organic Chemistry",
|
|
||||||
subfield_name="Organic Chemistry",
|
|
||||||
field_name="Chemistry",
|
|
||||||
)
|
|
||||||
],
|
|
||||||
frozenset({"TORG"}),
|
|
||||||
frozenset({"organic chemistry"}),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_token_match_rejects_machine_inside_micromachined() -> None:
|
|
||||||
patent = model.PatentEntry(
|
|
||||||
patent_id="EP-MICRO",
|
|
||||||
source="EPO",
|
|
||||||
title="Micromachined sensor device",
|
|
||||||
abstract="Fabrication of micromachined structures.",
|
|
||||||
)
|
|
||||||
assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0
|
|
||||||
evidence = _collect_keyword_text_evidence(
|
|
||||||
patent,
|
|
||||||
["Machine Learning"],
|
|
||||||
["machine", "learning"],
|
|
||||||
)
|
|
||||||
assert evidence.matched_words == []
|
|
||||||
assert evidence.full_token_match is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
|
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
|
||||||
patent = model.PatentEntry(
|
patent = model.PatentEntry(
|
||||||
patent_id="EP1",
|
patent_id="EP1",
|
||||||
@@ -914,8 +781,7 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None:
|
|||||||
uspto_symbols.assert_called_once()
|
uspto_symbols.assert_called_once()
|
||||||
assert epo_symbols.call_args.args[0][0] == "C07C243/08"
|
assert epo_symbols.call_args.args[0][0] == "C07C243/08"
|
||||||
assert "C07C" in epo_symbols.call_args.args[0]
|
assert "C07C" in epo_symbols.call_args.args[0]
|
||||||
# IPC search returns empty → text fallback also queries EPO/USPTO.
|
assert captured == ["epo", "uspto"]
|
||||||
assert captured == ["epo", "uspto", "epo", "uspto"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_text_search_terms_include_topic_metadata() -> None:
|
def test_text_search_terms_include_topic_metadata() -> None:
|
||||||
@@ -993,64 +859,84 @@ def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None:
|
|||||||
assert uspto["sort"][0] == {"_score": {"order": "desc"}}
|
assert uspto["sort"][0] == {"_score": {"order": "desc"}}
|
||||||
|
|
||||||
|
|
||||||
def test_text_queries_prefer_phrase_match_in_title() -> None:
|
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
|
||||||
queries = IpcPatentSearchQueries()
|
request = PatentsByKeywordsRequest(
|
||||||
epo = queries.epo_query_by_text_phrases(["organic chemistry"])
|
keywords=[
|
||||||
uspto = queries.uspto_query_by_text_phrases(["organic chemistry"])
|
KeywordPatentSearchItem(
|
||||||
|
keyword="organische Chemie",
|
||||||
epo_should = epo["query"]["bool"]["should"]
|
keyword_level="coarse",
|
||||||
uspto_should = uspto["query"]["bool"]["should"]
|
topic_id="https://openalex.org/TORG",
|
||||||
|
topic_display_name="Organic Chemistry",
|
||||||
def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None:
|
field_name="Chemistry",
|
||||||
for clause in clauses:
|
relevance_score=1.0,
|
||||||
payload = clause.get(kind, {}).get(field)
|
)
|
||||||
if isinstance(payload, dict) and payload.get("query") == "organic chemistry":
|
]
|
||||||
return float(payload.get("boost", 1.0))
|
|
||||||
return None
|
|
||||||
|
|
||||||
assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0
|
|
||||||
assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0
|
|
||||||
assert clause_boost(epo_should, "match", "title_en") == 1.5
|
|
||||||
assert clause_boost(uspto_should, "match_phrase", "title") == 5.0
|
|
||||||
assert epo["sort"][0] == {"_score": {"order": "desc"}}
|
|
||||||
|
|
||||||
|
|
||||||
def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
|
|
||||||
"""Fragmented IPC abstention must fall back to title/abstract search."""
|
|
||||||
patent = model.PatentEntry(
|
|
||||||
patent_id="EP123",
|
|
||||||
source="EPO",
|
|
||||||
title="Process for organic chemistry synthesis",
|
|
||||||
abstract="A catalytic method in organic chemistry.",
|
|
||||||
publication_date="20240101",
|
|
||||||
ipc=["C07C243/08"],
|
|
||||||
cpc=[],
|
|
||||||
)
|
)
|
||||||
|
ipc_matches = [
|
||||||
|
IpcCodeMatch(
|
||||||
|
"subgroup",
|
||||||
|
"C07C243/08",
|
||||||
|
0.90,
|
||||||
|
"organische Chemie",
|
||||||
|
"topic",
|
||||||
|
"TORG",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
async def fake_search_epo(query):
|
with patch(
|
||||||
assert "match_phrase" in str(query) or "title_en" in str(query)
|
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||||
return {
|
new=AsyncMock(return_value=ipc_matches),
|
||||||
"hits": {
|
), patch(
|
||||||
"hits": [
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||||
{
|
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
|
||||||
"_source": {
|
), patch(
|
||||||
"doc_number": "123",
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||||
"country": "EP",
|
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||||
"kind": "A1",
|
):
|
||||||
"date_publication": "20240101",
|
response = asyncio.run(get_patents_by_keywords(request))
|
||||||
"title_en": patent.title,
|
|
||||||
"abstract": patent.abstract,
|
|
||||||
"ipc": patent.ipc,
|
|
||||||
"cpc": [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async def fake_search_uspto(query):
|
assert response.mapping_status == "search_error"
|
||||||
return {"hits": {"hits": []}}
|
assert response.patent_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_ipc_search_terms_returns_without_text_fallback() -> None:
|
||||||
|
"""Without usable IPC symbols the search abstains — no title/abstract path."""
|
||||||
|
request = PatentsByKeywordsRequest(
|
||||||
|
keywords=[
|
||||||
|
KeywordPatentSearchItem(
|
||||||
|
keyword="organische Chemie",
|
||||||
|
keyword_level="coarse",
|
||||||
|
topic_id="https://openalex.org/TORG",
|
||||||
|
topic_display_name="Organic Chemistry",
|
||||||
|
field_name="Chemistry",
|
||||||
|
relevance_score=1.0,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
search_epo = AsyncMock(return_value={"hits": {"hits": []}})
|
||||||
|
search_uspto = AsyncMock(return_value={"hits": {"hits": []}})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||||
|
new=AsyncMock(return_value=[]),
|
||||||
|
), patch(
|
||||||
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||||
|
new=search_epo,
|
||||||
|
), patch(
|
||||||
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||||
|
new=search_uspto,
|
||||||
|
):
|
||||||
|
response = asyncio.run(get_patents_by_keywords(request))
|
||||||
|
|
||||||
|
assert response.mapping_status == "no_mapping"
|
||||||
|
assert response.patent_count == 0
|
||||||
|
assert response.patents == []
|
||||||
|
search_epo.assert_not_called()
|
||||||
|
search_uspto.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None:
|
||||||
|
"""Fragmented IPC mapping abstains without falling back to text retrieval."""
|
||||||
fragmented = [
|
fragmented = [
|
||||||
IpcCodeMatch(
|
IpcCodeMatch(
|
||||||
"subgroup",
|
"subgroup",
|
||||||
@@ -1074,113 +960,31 @@ def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
|
|||||||
)
|
)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
search_epo = AsyncMock(return_value={"hits": {"hits": []}})
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||||
new=AsyncMock(return_value=fragmented),
|
new=AsyncMock(return_value=fragmented),
|
||||||
), patch(
|
), patch(
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||||
new=AsyncMock(side_effect=fake_search_epo),
|
new=search_epo,
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
|
||||||
new=AsyncMock(side_effect=fake_search_uspto),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
|
|
||||||
new=AsyncMock(return_value={}),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.enrich_patents_classifications",
|
|
||||||
new=AsyncMock(),
|
|
||||||
), patch.object(
|
|
||||||
IpcPatentSearchQueries,
|
|
||||||
"epo_query_by_text_phrases",
|
|
||||||
wraps=IpcPatentSearchQueries().epo_query_by_text_phrases,
|
|
||||||
) as epo_text:
|
|
||||||
response = asyncio.run(get_patents_by_keywords(request))
|
|
||||||
|
|
||||||
epo_text.assert_called_once()
|
|
||||||
assert response.mapping_status == "uncertain"
|
|
||||||
assert response.patent_count == 1
|
|
||||||
assert response.patents[0].text_retrieval is True
|
|
||||||
assert response.patents[0].ipc_score == 0.0
|
|
||||||
assert response.patents[0].text_score > 0.0
|
|
||||||
assert response.patents[0].matched_ipc_symbols == []
|
|
||||||
assert response.patents[0].keyword_evidence is not None
|
|
||||||
assert response.patents[0].keyword_evidence.phrase_in_title is True
|
|
||||||
assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title"
|
|
||||||
|
|
||||||
|
|
||||||
def test_text_fallback_empty_yields_no_patents_found() -> None:
|
|
||||||
request = PatentsByKeywordsRequest(
|
|
||||||
keywords=[
|
|
||||||
KeywordPatentSearchItem(
|
|
||||||
keyword="organische Chemie",
|
|
||||||
keyword_level="coarse",
|
|
||||||
topic_id="https://openalex.org/TORG",
|
|
||||||
topic_display_name="Organic Chemistry",
|
|
||||||
field_name="Chemistry",
|
|
||||||
relevance_score=1.0,
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
with patch(
|
|
||||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
|
||||||
new=AsyncMock(return_value=[]),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
|
||||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
|
||||||
), patch(
|
), patch(
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
|
|
||||||
new=AsyncMock(return_value={}),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.enrich_patents_classifications",
|
|
||||||
new=AsyncMock(),
|
|
||||||
):
|
):
|
||||||
response = asyncio.run(get_patents_by_keywords(request))
|
response = asyncio.run(get_patents_by_keywords(request))
|
||||||
|
|
||||||
assert response.mapping_status == "no_patents_found"
|
assert response.mapping_status == "uncertain"
|
||||||
assert response.patent_count == 0
|
assert response.patent_count == 0
|
||||||
assert response.patents == []
|
assert response.patents == []
|
||||||
|
search_epo.assert_not_called()
|
||||||
|
|
||||||
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
|
|
||||||
request = PatentsByKeywordsRequest(
|
|
||||||
keywords=[
|
|
||||||
KeywordPatentSearchItem(
|
|
||||||
keyword="organische Chemie",
|
|
||||||
keyword_level="coarse",
|
|
||||||
topic_id="https://openalex.org/TORG",
|
|
||||||
topic_display_name="Organic Chemistry",
|
|
||||||
field_name="Chemistry",
|
|
||||||
relevance_score=1.0,
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
with patch(
|
|
||||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
|
||||||
new=AsyncMock(return_value=[]),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
|
||||||
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
|
||||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
|
||||||
):
|
|
||||||
response = asyncio.run(get_patents_by_keywords(request))
|
|
||||||
|
|
||||||
assert response.mapping_status == "search_error"
|
|
||||||
assert response.patent_count == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
|
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
|
||||||
clear_reverse_lookup_caches()
|
clear_reverse_lookup_caches()
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
||||||
dict,
|
lambda: {},
|
||||||
)
|
)
|
||||||
clear_reverse_lookup_caches()
|
clear_reverse_lookup_caches()
|
||||||
|
|
||||||
|
|||||||
@@ -251,7 +251,7 @@ class OrgPatentsSearchClient:
|
|||||||
|
|
||||||
async def search_by_institution(
|
async def search_by_institution(
|
||||||
self,
|
self,
|
||||||
institution_id: str,
|
institution_id: str | list[str],
|
||||||
match_type: MatchTypeFilter = "all",
|
match_type: MatchTypeFilter = "all",
|
||||||
page: int = 0,
|
page: int = 0,
|
||||||
size: int = DEFAULT_PAGE_SIZE,
|
size: int = DEFAULT_PAGE_SIZE,
|
||||||
@@ -259,8 +259,16 @@ class OrgPatentsSearchClient:
|
|||||||
from_year: int | None = None,
|
from_year: int | None = None,
|
||||||
to_year: int | None = None,
|
to_year: int | None = None,
|
||||||
) -> tuple[list[OrgPatentEntry], int]:
|
) -> tuple[list[OrgPatentEntry], int]:
|
||||||
short_id = institution_id.replace("https://openalex.org/", "").upper()
|
institution_ids = (
|
||||||
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
|
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":
|
if match_type == "institution":
|
||||||
filters.append({"terms": {"match_type": ["institution", "both"]}})
|
filters.append({"terms": {"match_type": ["institution", "both"]}})
|
||||||
|
|||||||
@@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query(
|
|||||||
title: str | None = None,
|
title: str | None = None,
|
||||||
funding_start_years: list[str] | None = None,
|
funding_start_years: list[str] | None = None,
|
||||||
funding_end_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,
|
countries: list[str] | None = None,
|
||||||
framework_programmes: list[str] | None = None,
|
framework_programmes: list[str] | None = None,
|
||||||
funding_schemes: 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:
|
if funding_end_years:
|
||||||
must_clauses.append(_eu_year_filters("endDate", 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 ===
|
# === Project core filters ===
|
||||||
if framework_programmes:
|
if framework_programmes:
|
||||||
must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}})
|
must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}})
|
||||||
@@ -937,6 +951,8 @@ async def search_eu_cordis_projects(
|
|||||||
title: str | None = None,
|
title: str | None = None,
|
||||||
funding_start_years: list[str] | None = None,
|
funding_start_years: list[str] | None = None,
|
||||||
funding_end_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,
|
countries: list[str] | None = None,
|
||||||
framework_programmes: list[str] | None = None,
|
framework_programmes: list[str] | None = None,
|
||||||
funding_schemes: list[str] | None = None,
|
funding_schemes: list[str] | None = None,
|
||||||
@@ -944,6 +960,7 @@ async def search_eu_cordis_projects(
|
|||||||
sort_by: str = "title",
|
sort_by: str = "title",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
) -> EuCordisProjectSearchPage:
|
) -> EuCordisProjectSearchPage:
|
||||||
"""
|
"""
|
||||||
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
|
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
|
||||||
@@ -964,6 +981,8 @@ async def search_eu_cordis_projects(
|
|||||||
title=title,
|
title=title,
|
||||||
funding_start_years=funding_start_years,
|
funding_start_years=funding_start_years,
|
||||||
funding_end_years=funding_end_years,
|
funding_end_years=funding_end_years,
|
||||||
|
active_from_year=active_from_year,
|
||||||
|
active_to_year=active_to_year,
|
||||||
countries=countries,
|
countries=countries,
|
||||||
framework_programmes=framework_programmes,
|
framework_programmes=framework_programmes,
|
||||||
funding_schemes=funding_schemes,
|
funding_schemes=funding_schemes,
|
||||||
@@ -1015,6 +1034,14 @@ async def search_eu_cordis_projects(
|
|||||||
hits = response.get("hits", {}).get("hits", [])
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
|
||||||
|
if skip_enrichment:
|
||||||
|
return EuCordisProjectSearchPage(
|
||||||
|
elements=[EuCordisProjectSummary.from_hit(hit) for hit in hits],
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
)
|
||||||
|
|
||||||
project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list)
|
project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list)
|
||||||
|
|
||||||
for hit in hits:
|
for hit in hits:
|
||||||
@@ -1124,10 +1151,6 @@ async def get_eu_cordis_projects_funding_data(
|
|||||||
"track_total_hits": False,
|
"track_total_hits": False,
|
||||||
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
|
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
|
||||||
"query": query,
|
"query": query,
|
||||||
# "id" is unique per project and used elsewhere as a term-filter
|
|
||||||
# field, so it's mapped as keyword - safe + deterministic sort
|
|
||||||
# key for search_after pagination across an arbitrarily large
|
|
||||||
# result set.
|
|
||||||
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
|
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
|
||||||
}
|
}
|
||||||
if search_after is not None:
|
if search_after is not None:
|
||||||
@@ -1247,68 +1270,6 @@ async def get_openalex_author_ids_by_dois(
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def get_openalex_authors_for_cordis_project_ids(
|
|
||||||
project_ids: list[str],
|
|
||||||
) -> dict[str, AuthorPage]:
|
|
||||||
"""Returns a mapping of project_id -> AuthorPage for a batch of projects."""
|
|
||||||
if not project_ids:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
|
|
||||||
response = await elasticsearch.search(
|
|
||||||
query=query,
|
|
||||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
|
||||||
cluster=ESCluster.INSE,
|
|
||||||
source=["projectID", "doi","qaProcessedDoi"],
|
|
||||||
size=10000,
|
|
||||||
)
|
|
||||||
dois_by_project: dict[str, set[str]] = {}
|
|
||||||
for hit in response.get("hits", {}).get("hits", []):
|
|
||||||
source = hit.get("_source", {})
|
|
||||||
pid = source.get("projectID")
|
|
||||||
doi = source.get("doi")
|
|
||||||
qa_processed_doi = source.get("qaProcessedDoi")
|
|
||||||
if pid:
|
|
||||||
dois_by_project.setdefault(pid, set())
|
|
||||||
if doi:
|
|
||||||
dois_by_project[pid].add(doi)
|
|
||||||
elif qa_processed_doi:
|
|
||||||
dois_by_project[pid].add(qa_processed_doi)
|
|
||||||
|
|
||||||
all_dois = list({doi for dois in dois_by_project.values() for doi in dois})
|
|
||||||
|
|
||||||
# single ES call for the whole batch, keyed by raw DOI
|
|
||||||
author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois)
|
|
||||||
|
|
||||||
# aggregate per project, dedupe author_ids within a project
|
|
||||||
author_ids_by_project: dict[str, list[str]] = {}
|
|
||||||
for pid, dois in dois_by_project.items():
|
|
||||||
project_author_ids: set[str] = set()
|
|
||||||
for doi in dois:
|
|
||||||
project_author_ids.update(author_ids_by_doi.get(doi, []))
|
|
||||||
author_ids_by_project[pid] = list(project_author_ids)
|
|
||||||
|
|
||||||
# single ES call to fetch all Author objects across every project
|
|
||||||
all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids})
|
|
||||||
|
|
||||||
author_page = await get_authors_by_ids(author_ids=all_author_ids)
|
|
||||||
authors_by_id = {author.id: author for author in author_page.elements}
|
|
||||||
|
|
||||||
# split the fetched authors back out per project
|
|
||||||
result: dict[str, AuthorPage] = {}
|
|
||||||
for pid in project_ids:
|
|
||||||
ids_for_project = author_ids_by_project.get(pid, [])
|
|
||||||
authors_for_project = [
|
|
||||||
authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id
|
|
||||||
]
|
|
||||||
result[pid] = AuthorPage(
|
|
||||||
elements=authors_for_project,
|
|
||||||
total=len(authors_for_project),
|
|
||||||
page=0,
|
|
||||||
size=len(authors_for_project),
|
|
||||||
)
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
async def get_openalex_authors_for_projects_ids(
|
async def get_openalex_authors_for_projects_ids(
|
||||||
project_ids_by_type: dict[EuCordisProjectType, list[str]],
|
project_ids_by_type: dict[EuCordisProjectType, list[str]],
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import logging
|
import logging
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
import inse.authors.v2.service as author_service
|
||||||
|
from inse.auth.model import AccessTokenMetadata
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESCluster, ESIndex
|
from inse.model import ESCluster, ESIndex
|
||||||
from inse.projects.model import EuCordisProjectType
|
from inse.projects.model import EuCordisProjectType
|
||||||
@@ -359,6 +360,53 @@ async def get_person_institutes(
|
|||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
async def get_dfg_institutes_by_ids(
|
||||||
|
institute_ids: list[int],
|
||||||
|
) -> dict[str, dict]:
|
||||||
|
|
||||||
|
if not institute_ids:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=ESIndex.DFG_INSTITUTES,
|
||||||
|
cluster=ESCluster.INSE,
|
||||||
|
body={
|
||||||
|
"size": len(institute_ids),
|
||||||
|
"_source": [
|
||||||
|
"institute_id",
|
||||||
|
"root_id",
|
||||||
|
"root_name_de",
|
||||||
|
"root_name_en",
|
||||||
|
"institute_name_de",
|
||||||
|
"institute_name_en",
|
||||||
|
"address_country_de",
|
||||||
|
"address_country_en",
|
||||||
|
],
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"_id": institute_ids,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
result = {}
|
||||||
|
|
||||||
|
for hit in response["hits"]["hits"]:
|
||||||
|
source = hit["_source"]
|
||||||
|
|
||||||
|
result[source["institute_id"]] = {
|
||||||
|
"institute_id": source["institute_id"],
|
||||||
|
"root_id": source.get("root_id"),
|
||||||
|
"root_name_de": source.get("root_name_de"),
|
||||||
|
"root_name_en": source.get("root_name_en"),
|
||||||
|
"institute_name_de": source.get("institute_name_de"),
|
||||||
|
"institute_name_en": source.get("institute_name_en"),
|
||||||
|
"address_country_de": source.get("address_country_de"),
|
||||||
|
"address_country_en": source.get("address_country_en"),
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
#EU Cordis Projects
|
#EU Cordis Projects
|
||||||
|
|
||||||
|
|||||||
@@ -254,8 +254,37 @@ class DfgProjectSummary(BaseModel):
|
|||||||
names = []
|
names = []
|
||||||
institutions = {}
|
institutions = {}
|
||||||
project_persons = []
|
project_persons = []
|
||||||
|
|
||||||
persons = source.get("persons", [])
|
persons = source.get("persons", [])
|
||||||
|
institutions_raw= source.get("institutions", [])
|
||||||
|
if isinstance(institutions_raw, list):
|
||||||
|
for institution in institutions_raw:
|
||||||
|
if not isinstance(institution, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
institute_id = institution.get("institute_id")
|
||||||
|
if institute_id is not None:
|
||||||
|
institutions[f"institute:{institute_id}"] = DfgInstitutionSummary(
|
||||||
|
id=institute_id,
|
||||||
|
institute_name_de=institution.get("institute_name_de"),
|
||||||
|
institute_name_en=institution.get("institute_name_en"),
|
||||||
|
address_country_de=institution.get("address_country_de"),
|
||||||
|
address_country_en=institution.get("address_country_en"),
|
||||||
|
root_id=institution.get("root_id"),
|
||||||
|
root_name_de=institution.get("root_name_de"),
|
||||||
|
root_name_en=institution.get("root_name_en"),
|
||||||
|
)
|
||||||
|
root_id = institution.get("root_id")
|
||||||
|
if root_id is not None:
|
||||||
|
institutions[f"root:{root_id}"] = DfgInstitutionSummary(
|
||||||
|
id=root_id,
|
||||||
|
institute_name_de=institution.get("root_name_de"),
|
||||||
|
institute_name_en=institution.get("root_name_en"),
|
||||||
|
address_country_de=institution.get("address_country_de"),
|
||||||
|
address_country_en=institution.get("address_country_en"),
|
||||||
|
root_id=None,
|
||||||
|
root_name_de=None,
|
||||||
|
root_name_en=None,
|
||||||
|
)
|
||||||
|
|
||||||
if isinstance(persons, list):
|
if isinstance(persons, list):
|
||||||
for person in persons:
|
for person in persons:
|
||||||
@@ -266,35 +295,35 @@ class DfgProjectSummary(BaseModel):
|
|||||||
|
|
||||||
if full_name:
|
if full_name:
|
||||||
names.append(full_name.strip())
|
names.append(full_name.strip())
|
||||||
|
# previously we were creating institution objects for each person, but now we are using the institutions from the institutions_raw list
|
||||||
|
#institution = None
|
||||||
|
# if person.get("institute_id") is not None:
|
||||||
|
# institute = DfgInstitutionSummary(
|
||||||
|
# id=person["institute_id"],
|
||||||
|
# institute_name_de=person.get("institute_name_de"),
|
||||||
|
# institute_name_en=person.get("institute_name_en"),
|
||||||
|
# address_country_de=person.get("address_country_de"),
|
||||||
|
# address_country_en=person.get("address_country_en"),
|
||||||
|
# root_id=None,
|
||||||
|
# root_name_de=None,
|
||||||
|
# root_name_en=None,
|
||||||
|
# )
|
||||||
|
|
||||||
institution = None
|
# institutions[f"institute:{person['institute_id']}"] = institute
|
||||||
if person.get("institute_id") is not None:
|
|
||||||
institute = DfgInstitutionSummary(
|
|
||||||
id=person["institute_id"],
|
|
||||||
institute_name_de=person.get("institute_name_de"),
|
|
||||||
institute_name_en=person.get("institute_name_en"),
|
|
||||||
address_country_de=person.get("address_country_de"),
|
|
||||||
address_country_en=person.get("address_country_en"),
|
|
||||||
root_id=None,
|
|
||||||
root_name_de=None,
|
|
||||||
root_name_en=None,
|
|
||||||
)
|
|
||||||
|
|
||||||
institutions[f"institute:{person['institute_id']}"] = institute
|
# if person.get("root_id") is not None:
|
||||||
|
# root_institution = DfgInstitutionSummary(
|
||||||
|
# id=person["root_id"],
|
||||||
|
# institute_name_de=person.get("root_name_de"),
|
||||||
|
# institute_name_en=person.get("root_name_en"),
|
||||||
|
# address_country_de=person.get("address_country_de"),
|
||||||
|
# address_country_en=person.get("address_country_en"),
|
||||||
|
# root_id=None,
|
||||||
|
# root_name_de=None,
|
||||||
|
# root_name_en=None,
|
||||||
|
# )
|
||||||
|
|
||||||
if person.get("root_id") is not None:
|
# institutions[f"root:{person['root_id']}"] = root_institution
|
||||||
root_institution = DfgInstitutionSummary(
|
|
||||||
id=person["root_id"],
|
|
||||||
institute_name_de=person.get("root_name_de"),
|
|
||||||
institute_name_en=person.get("root_name_en"),
|
|
||||||
address_country_de=person.get("address_country_de"),
|
|
||||||
address_country_en=person.get("address_country_en"),
|
|
||||||
root_id=None,
|
|
||||||
root_name_de=None,
|
|
||||||
root_name_en=None,
|
|
||||||
)
|
|
||||||
|
|
||||||
institutions[f"root:{person['root_id']}"] = root_institution
|
|
||||||
|
|
||||||
if person.get("person_id") is not None:
|
if person.get("person_id") is not None:
|
||||||
project_persons.append(
|
project_persons.append(
|
||||||
@@ -305,7 +334,7 @@ class DfgProjectSummary(BaseModel):
|
|||||||
full_name=full_name,
|
full_name=full_name,
|
||||||
role_label_en=person.get("role_label_en"),
|
role_label_en=person.get("role_label_en"),
|
||||||
role_label_de=person.get("role_label_de"),
|
role_label_de=person.get("role_label_de"),
|
||||||
institution=institution,
|
institution=None,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
topics_raw = source.get("topics") or []
|
topics_raw = source.get("topics") or []
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from inse.projects.logic import (
|
|||||||
get_openalex_topics_for_bund_projects,
|
get_openalex_topics_for_bund_projects,
|
||||||
get_openalex_topics_for_dfg_projects,
|
get_openalex_topics_for_dfg_projects,
|
||||||
get_person_ids_by_institution_ids,
|
get_person_ids_by_institution_ids,
|
||||||
|
get_dfg_institutes_by_ids,
|
||||||
get_person_institutes,
|
get_person_institutes,
|
||||||
)
|
)
|
||||||
from inse.projects.model import (
|
from inse.projects.model import (
|
||||||
@@ -194,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
|||||||
_type_: The retrieved publications.
|
_type_: The retrieved publications.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
query_dois = list({
|
query_dois = set({
|
||||||
variant
|
variant
|
||||||
for doi in dois
|
for doi in dois
|
||||||
for variant in (
|
for variant in (
|
||||||
@@ -210,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
|||||||
{
|
{
|
||||||
"bool": {
|
"bool": {
|
||||||
"should": [
|
"should": [
|
||||||
{"terms": {"doi": query_dois}},
|
{"terms": {"doi": list(query_dois)}},
|
||||||
{"terms": {"qaProcessedDoi": query_dois}},
|
{"terms": {"qaProcessedDoi": list(query_dois)}},
|
||||||
],
|
],
|
||||||
"minimum_should_match": 1,
|
"minimum_should_match": 1,
|
||||||
}
|
}
|
||||||
@@ -222,6 +223,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
|||||||
|
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
query=query,
|
query=query,
|
||||||
|
size=10000,
|
||||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
)
|
)
|
||||||
@@ -263,7 +265,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
|||||||
_type_: The retrieved publications.
|
_type_: The retrieved publications.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
query_dois = list({
|
query_dois = set({
|
||||||
variant
|
variant
|
||||||
for doi in dois
|
for doi in dois
|
||||||
for variant in (
|
for variant in (
|
||||||
@@ -280,7 +282,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
|||||||
"query": {
|
"query": {
|
||||||
"terms": {
|
"terms": {
|
||||||
"publications.doi":
|
"publications.doi":
|
||||||
query_dois
|
list(query_dois)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,7 +292,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
|||||||
}
|
}
|
||||||
|
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
size=1000,
|
size=10000,
|
||||||
query=query,
|
query=query,
|
||||||
index=ESIndex.DFG_PROJECTS,
|
index=ESIndex.DFG_PROJECTS,
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
@@ -317,7 +319,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]:
|
|||||||
|
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
source=["projects.project_id"],
|
source=["projects.project_id"],
|
||||||
size=1000,
|
size=10000,
|
||||||
query=query,
|
query=query,
|
||||||
index=ESIndex.DFG_PERSONS,
|
index=ESIndex.DFG_PERSONS,
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
@@ -366,6 +368,9 @@ async def search_dfg_projects(
|
|||||||
sort_by: str = "id",
|
sort_by: str = "id",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
|
active_from_year: int | None = None,
|
||||||
|
active_to_year: int | None = None,
|
||||||
) -> DfgProjectPage:
|
) -> DfgProjectPage:
|
||||||
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
||||||
|
|
||||||
@@ -411,6 +416,7 @@ async def search_dfg_projects(
|
|||||||
"subject_area_en",
|
"subject_area_en",
|
||||||
"persons",
|
"persons",
|
||||||
"subject_classifications",
|
"subject_classifications",
|
||||||
|
"institutions",
|
||||||
],
|
],
|
||||||
"query": {},
|
"query": {},
|
||||||
}
|
}
|
||||||
@@ -485,6 +491,11 @@ async def search_dfg_projects(
|
|||||||
if funding_end_years:
|
if funding_end_years:
|
||||||
must_clauses.append({"terms": {"funding_end": 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:
|
if names:
|
||||||
name_must_clauses = []
|
name_must_clauses = []
|
||||||
for full_name in names:
|
for full_name in names:
|
||||||
@@ -522,35 +533,55 @@ async def search_dfg_projects(
|
|||||||
)
|
)
|
||||||
if not matching_institution_ids:
|
if not matching_institution_ids:
|
||||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||||
matching_person_ids = await get_person_ids_by_institution_ids(
|
#previously we were filtering by person_ids, but now we are filtering by institution_ids directly
|
||||||
institution_ids=matching_institution_ids
|
# matching_person_ids = await get_person_ids_by_institution_ids(
|
||||||
)
|
# institution_ids=matching_institution_ids
|
||||||
|
# )
|
||||||
|
# must_clauses.append(
|
||||||
|
# {
|
||||||
|
# "nested": {
|
||||||
|
# "path": "persons",
|
||||||
|
# "query": {"terms": {"persons.person_id": matching_person_ids}},
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# )
|
||||||
must_clauses.append(
|
must_clauses.append(
|
||||||
{
|
{
|
||||||
"nested": {
|
"nested": {
|
||||||
"path": "persons",
|
"path": "institutions",
|
||||||
"query": {"terms": {"persons.person_id": matching_person_ids}},
|
"query": {"terms": {"institutions.institute_id": matching_institution_ids}},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
print("MATCHING_INSTITUTION_IDS", matching_institution_ids)
|
||||||
|
|
||||||
if institution_ids:
|
if institution_ids:
|
||||||
matching_person_ids = await get_person_ids_by_institution_ids(
|
#prevously we were filtering by person_ids, but now we are filtering by institution_ids directly
|
||||||
institution_ids=institution_ids
|
# matching_person_ids = await get_person_ids_by_institution_ids(
|
||||||
)
|
# institution_ids=institution_ids
|
||||||
|
# )
|
||||||
|
|
||||||
if not matching_person_ids:
|
# if not matching_person_ids:
|
||||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
# return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||||
|
|
||||||
|
# must_clauses.append(
|
||||||
|
# {
|
||||||
|
# "nested": {
|
||||||
|
# "path": "persons",
|
||||||
|
# "query": {"terms": {"persons.person_id": matching_person_ids}},
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# )
|
||||||
must_clauses.append(
|
must_clauses.append(
|
||||||
{
|
{
|
||||||
"nested": {
|
"nested": {
|
||||||
"path": "persons",
|
"path": "institutions",
|
||||||
"query": {"terms": {"persons.person_id": matching_person_ids}},
|
"query": {"terms": {"institutions.institute_id": institution_ids}},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
body["query"] = (
|
body["query"] = (
|
||||||
{"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
{"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||||
)
|
)
|
||||||
@@ -584,6 +615,12 @@ async def search_dfg_projects(
|
|||||||
|
|
||||||
hits = response.get("hits", {}).get("hits", [])
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
|
||||||
|
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]
|
project_ids = [hit["_source"]["id"] for hit in hits]
|
||||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
||||||
|
|
||||||
@@ -599,20 +636,27 @@ async def search_dfg_projects(
|
|||||||
source = hit["_source"]
|
source = hit["_source"]
|
||||||
project_id = source["id"]
|
project_id = source["id"]
|
||||||
source["topics"] = topic_lookup.get(str(project_id), [])
|
source["topics"] = topic_lookup.get(str(project_id), [])
|
||||||
|
institutions = source.get("institutions", [])
|
||||||
|
for institution in institutions:
|
||||||
|
institute_id = institution.get("institute_id")
|
||||||
|
if institute_id is not None:
|
||||||
|
institute_info = await get_dfg_institutes_by_ids(institute_ids=[institute_id])
|
||||||
|
if institute_info:
|
||||||
|
institution.update(institute_info[institute_id])
|
||||||
persons = source.get("persons", [])
|
persons = source.get("persons", [])
|
||||||
for person in persons:
|
for person in persons:
|
||||||
person_id = person.get("person_id")
|
person_id = person.get("person_id")
|
||||||
institute = person_lookup.get(person_id)
|
institute = person_lookup.get(person_id)
|
||||||
|
|
||||||
if institute:
|
# if institute:
|
||||||
person["root_id"] = institute.get("root_id")
|
# person["root_id"] = institute.get("root_id")
|
||||||
person["institute_id"] = institute.get("institute_id")
|
# person["institute_id"] = institute.get("institute_id")
|
||||||
person["root_name_de"] = institute.get("root_name_de")
|
# person["root_name_de"] = institute.get("root_name_de")
|
||||||
person["root_name_en"] = institute.get("root_name_en")
|
# person["root_name_en"] = institute.get("root_name_en")
|
||||||
person["institute_name_de"] = institute.get("institute_name_de")
|
# person["institute_name_de"] = institute.get("institute_name_de")
|
||||||
person["institute_name_en"] = institute.get("institute_name_en")
|
# person["institute_name_en"] = institute.get("institute_name_en")
|
||||||
person["address_country_de"] = institute.get("address_country_de")
|
# person["address_country_de"] = institute.get("address_country_de")
|
||||||
person["address_country_en"] = institute.get("address_country_en")
|
# person["address_country_en"] = institute.get("address_country_en")
|
||||||
|
|
||||||
return _complete_response_to_dfg_project_page(response, page, size)
|
return _complete_response_to_dfg_project_page(response, page, size)
|
||||||
|
|
||||||
@@ -654,12 +698,128 @@ async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None:
|
|||||||
)
|
)
|
||||||
hits = response.get("hits", {}).get("hits", [])
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
|
||||||
if hits:
|
if not hits:
|
||||||
hit = hits[0]
|
return None
|
||||||
hit["_source"]["topics"] = topic_lookup.get(project_id, [])
|
|
||||||
details = DfgProjectDetails.from_elastic_hit(hit=hit)
|
hit = hits[0]
|
||||||
return details
|
source = hit["_source"]
|
||||||
return None
|
source["topics"] = topic_lookup.get(project_id, [])
|
||||||
|
|
||||||
|
persons = source.get("persons", [])
|
||||||
|
|
||||||
|
# --- Enrich persons with institute/root info (mirrors search_dfg_projects) ---
|
||||||
|
person_ids = {
|
||||||
|
person["person_id"]
|
||||||
|
for person in persons
|
||||||
|
if isinstance(person, dict) and person.get("person_id") is not None
|
||||||
|
}
|
||||||
|
person_lookup = await get_person_institutes(person_ids=list(person_ids))
|
||||||
|
|
||||||
|
institutions: dict[str, dict] = {}
|
||||||
|
|
||||||
|
for person in persons:
|
||||||
|
person_id = person.get("person_id")
|
||||||
|
institute = person_lookup.get(person_id)
|
||||||
|
if not institute:
|
||||||
|
continue
|
||||||
|
|
||||||
|
person["root_id"] = institute.get("root_id")
|
||||||
|
person["institute_id"] = institute.get("institute_id")
|
||||||
|
person["root_name_de"] = institute.get("root_name_de")
|
||||||
|
person["root_name_en"] = institute.get("root_name_en")
|
||||||
|
person["institute_name_de"] = institute.get("institute_name_de")
|
||||||
|
person["institute_name_en"] = institute.get("institute_name_en")
|
||||||
|
person["address_country_de"] = institute.get("address_country_de")
|
||||||
|
person["address_country_en"] = institute.get("address_country_en")
|
||||||
|
|
||||||
|
if institute.get("institute_id") is not None:
|
||||||
|
institutions[f"institute:{institute['institute_id']}"] = {
|
||||||
|
"institute_id": institute["institute_id"],
|
||||||
|
"institute_name_de": institute.get("institute_name_de"),
|
||||||
|
"institute_name_en": institute.get("institute_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if institute.get("root_id") is not None:
|
||||||
|
institutions[f"root:{institute['root_id']}"] = {
|
||||||
|
"institute_id": institute["root_id"],
|
||||||
|
"institute_name_de": institute.get("root_name_de"),
|
||||||
|
"institute_name_en": institute.get("root_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
source["institutions"] = list(institutions.values())
|
||||||
|
|
||||||
|
return DfgProjectDetails.from_elastic_hit(hit=hit)
|
||||||
|
|
||||||
|
async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None:
|
||||||
|
"""Fetches the details of a single DFG project based on its project ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
project_id (str): The project ID to fetch.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[DfgProjectDetails]: The project details or None if not found.
|
||||||
|
"""
|
||||||
|
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id])
|
||||||
|
query = {"ids": {"values": [project_id]}}
|
||||||
|
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=ESIndex.DFG_PROJECTS,
|
||||||
|
query=query,
|
||||||
|
size=1,
|
||||||
|
)
|
||||||
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
|
||||||
|
if not hits:
|
||||||
|
return None
|
||||||
|
|
||||||
|
hit = hits[0]
|
||||||
|
source = hit["_source"]
|
||||||
|
source["topics"] = topic_lookup.get(project_id, [])
|
||||||
|
|
||||||
|
persons = source.get("persons", [])
|
||||||
|
|
||||||
|
#Enrich persons with institute/root info
|
||||||
|
person_ids = {
|
||||||
|
person["person_id"]
|
||||||
|
for person in persons
|
||||||
|
if isinstance(person, dict) and person.get("person_id") is not None
|
||||||
|
}
|
||||||
|
person_lookup = await get_person_institutes(person_ids=list(person_ids))
|
||||||
|
|
||||||
|
institutions: dict[str, dict] = {}
|
||||||
|
|
||||||
|
for person in persons:
|
||||||
|
person_id = person.get("person_id")
|
||||||
|
institute = person_lookup.get(person_id)
|
||||||
|
if not institute:
|
||||||
|
continue
|
||||||
|
|
||||||
|
person["root_id"] = institute.get("root_id")
|
||||||
|
person["institute_id"] = institute.get("institute_id")
|
||||||
|
person["root_name_de"] = institute.get("root_name_de")
|
||||||
|
person["root_name_en"] = institute.get("root_name_en")
|
||||||
|
person["institute_name_de"] = institute.get("institute_name_de")
|
||||||
|
person["institute_name_en"] = institute.get("institute_name_en")
|
||||||
|
person["address_country_de"] = institute.get("address_country_de")
|
||||||
|
person["address_country_en"] = institute.get("address_country_en")
|
||||||
|
|
||||||
|
if institute.get("institute_id") is not None:
|
||||||
|
institutions[f"institute:{institute['institute_id']}"] = {
|
||||||
|
"institute_id": institute["institute_id"],
|
||||||
|
"institute_name_de": institute.get("institute_name_de"),
|
||||||
|
"institute_name_en": institute.get("institute_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if institute.get("root_id") is not None:
|
||||||
|
institutions[f"root:{institute['root_id']}"] = {
|
||||||
|
"institute_id": institute["root_id"],
|
||||||
|
"institute_name_de": institute.get("root_name_de"),
|
||||||
|
"institute_name_en": institute.get("root_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
source["institutions"] = list(institutions.values())
|
||||||
|
|
||||||
|
return DfgProjectDetails.from_elastic_hit(hit=hit)
|
||||||
|
|
||||||
#BUND
|
#BUND
|
||||||
|
|
||||||
@@ -707,6 +867,8 @@ async def search_bund_projects_with_filters(
|
|||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
skip_topic_enrichment: bool = False,
|
skip_topic_enrichment: bool = False,
|
||||||
|
active_from_year: int | None = None,
|
||||||
|
active_to_year: int | None = None,
|
||||||
) -> BundProjectPage:
|
) -> BundProjectPage:
|
||||||
"""
|
"""
|
||||||
Main search function for BUND projects, analogous to the DFG search.
|
Main search function for BUND projects, analogous to the DFG search.
|
||||||
@@ -848,6 +1010,15 @@ async def search_bund_projects_with_filters(
|
|||||||
if funding_end_years:
|
if funding_end_years:
|
||||||
must_clauses.append(_bund_year_filters("funding_end", 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": {}}
|
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||||
# === Sorting ===
|
# === Sorting ===
|
||||||
sort_by = sort_by.strip().lower()
|
sort_by = sort_by.strip().lower()
|
||||||
@@ -1000,11 +1171,13 @@ async def search_all_projects(
|
|||||||
page = projects_filtering_properties.page
|
page = projects_filtering_properties.page
|
||||||
offset = page * size
|
offset = page * size
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
|
|
||||||
index=index,
|
index=index,
|
||||||
size=size,
|
size=size,
|
||||||
offset=offset,
|
offset=offset,
|
||||||
query=query,
|
query=query,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
|
track_total_hits=True,
|
||||||
)
|
)
|
||||||
return _response_to_funding_project_page(response=response, page=page, size=size)
|
return _response_to_funding_project_page(response=response, page=page, size=size)
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import logging
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Path, Query, status
|
from fastapi import APIRouter, Body, Depends, Path, Query, status
|
||||||
|
from inse.auth.model import AccessTokenMetadata
|
||||||
|
from inse.auth.service import CurrentUserAccessTokenPayloadDep
|
||||||
from inse.institutions.institutions_search_client import (
|
from inse.institutions.institutions_search_client import (
|
||||||
InstitutionsSearchClient,
|
InstitutionsSearchClient,
|
||||||
)
|
)
|
||||||
@@ -28,6 +30,9 @@ from inse.projects.model import (
|
|||||||
SortDirection,
|
SortDirection,
|
||||||
)
|
)
|
||||||
from inse.tags import Tags
|
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
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -63,6 +68,129 @@ async def search_bund_projects(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/dfg/search",
|
||||||
|
summary="Get DFG projects.",
|
||||||
|
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
|
||||||
|
operation_id="getDfgProjects",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {
|
||||||
|
"description": "Successful Response",
|
||||||
|
"model": DfgProjectPage,
|
||||||
|
},
|
||||||
|
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||||
|
status.HTTP_403_FORBIDDEN: {
|
||||||
|
"description": "Access denied for the provided institution ID"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
response_model_by_alias=False,
|
||||||
|
)
|
||||||
|
async def get_dfg_projects(
|
||||||
|
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.")] = None,
|
||||||
|
keywords: Annotated[
|
||||||
|
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.")
|
||||||
|
] = None,
|
||||||
|
filter_topic_ids: Annotated[
|
||||||
|
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."
|
||||||
|
),
|
||||||
|
] = 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",
|
||||||
|
sort_direction: Annotated[
|
||||||
|
str, Query(description="The sort direction (asc or desc).")
|
||||||
|
] = "asc",
|
||||||
|
fuzzy: Annotated[
|
||||||
|
bool,
|
||||||
|
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, "
|
||||||
|
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
||||||
|
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
||||||
|
"sort_direction=%s, fuzzy=%s",
|
||||||
|
author_id,
|
||||||
|
author_filter_ids,
|
||||||
|
institution_ids,
|
||||||
|
keywords,
|
||||||
|
topic_ids,
|
||||||
|
filter_topic_ids,
|
||||||
|
title,
|
||||||
|
funding_start_years,
|
||||||
|
funding_end_years,
|
||||||
|
page,
|
||||||
|
size,
|
||||||
|
sort_by,
|
||||||
|
sort_direction,
|
||||||
|
fuzzy,
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
detail="Access denied for the provided author ID or institution ID",
|
||||||
|
)
|
||||||
|
return await projects_service.get_dfg_projects(
|
||||||
|
institutions_search_client=institutions_search_client,
|
||||||
|
raw_oa_institution_id=raw_oa_institution_id,
|
||||||
|
author_id=author_id,
|
||||||
|
author_filter_ids=author_filter_ids,
|
||||||
|
institution_ids=institution_ids,
|
||||||
|
funding_start_years=funding_start_years,
|
||||||
|
funding_end_years=funding_end_years,
|
||||||
|
title=title,
|
||||||
|
keywords=keywords,
|
||||||
|
topic_ids=topic_ids,
|
||||||
|
filter_topic_ids=filter_topic_ids,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
sort_by=sort_by,
|
||||||
|
sort_direction=sort_direction,
|
||||||
|
fuzzy=fuzzy,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/dfg/{id}",
|
"/dfg/{id}",
|
||||||
summary="Get a single DFG project.",
|
summary="Get a single DFG project.",
|
||||||
@@ -96,10 +224,18 @@ async def get_single_dfg_project(
|
|||||||
"description": "Successful Response",
|
"description": "Successful Response",
|
||||||
"model": BundProjectPage,
|
"model": BundProjectPage,
|
||||||
},
|
},
|
||||||
|
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||||
|
status.HTTP_403_FORBIDDEN: {
|
||||||
|
"description": "Access denied for the provided institution ID"
|
||||||
|
},
|
||||||
},
|
},
|
||||||
response_model_by_alias=False,
|
response_model_by_alias=False,
|
||||||
)
|
)
|
||||||
async def search_bund_projects(
|
async def search_bund_projects(
|
||||||
|
session: SessionDep,
|
||||||
|
access_token_metadata: Annotated[
|
||||||
|
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||||
|
],
|
||||||
institutions_search_client: Annotated[
|
institutions_search_client: Annotated[
|
||||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
],
|
],
|
||||||
@@ -152,9 +288,23 @@ async def search_bund_projects(
|
|||||||
] = "asc",
|
] = "asc",
|
||||||
fuzzy: Annotated[
|
fuzzy: Annotated[
|
||||||
bool,
|
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,
|
] = False,
|
||||||
) -> BundProjectPage:
|
) -> BundProjectPage:
|
||||||
|
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,
|
||||||
|
detail="Access denied for the provided author ID or institution ID",
|
||||||
|
)
|
||||||
return await projects_service.search_bund_projects_with_filters(
|
return await projects_service.search_bund_projects_with_filters(
|
||||||
institutions_search_client=institutions_search_client,
|
institutions_search_client=institutions_search_client,
|
||||||
executing_agency=executing_agency,
|
executing_agency=executing_agency,
|
||||||
@@ -171,9 +321,10 @@ async def search_bund_projects(
|
|||||||
size=size,
|
size=size,
|
||||||
sort_by=sort_by,
|
sort_by=sort_by,
|
||||||
sort_direction=sort_direction,
|
sort_direction=sort_direction,
|
||||||
fuzzy=fuzzy
|
fuzzy=fuzzy,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/bund/{id}",
|
"/bund/{id}",
|
||||||
summary="Get a single BUND project.",
|
summary="Get a single BUND project.",
|
||||||
@@ -196,6 +347,7 @@ async def get_single_bund_project(
|
|||||||
project_id=id,
|
project_id=id,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
########
|
########
|
||||||
from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType
|
from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType
|
||||||
from inse.projects.service import search_eu_cordis_projects
|
from inse.projects.service import search_eu_cordis_projects
|
||||||
@@ -217,10 +369,17 @@ from inse.projects.service import search_eu_cordis_projects
|
|||||||
"model": EuCordisProjectSearchPage,
|
"model": EuCordisProjectSearchPage,
|
||||||
},
|
},
|
||||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||||
|
status.HTTP_403_FORBIDDEN: {
|
||||||
|
"description": "Access denied for the provided institution ID"
|
||||||
|
},
|
||||||
},
|
},
|
||||||
response_model_by_alias=False,
|
response_model_by_alias=False,
|
||||||
)
|
)
|
||||||
async def search_eu_cordis_projects_endpoint(
|
async def search_eu_cordis_projects_endpoint(
|
||||||
|
session: SessionDep,
|
||||||
|
access_token_metadata: Annotated[
|
||||||
|
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||||
|
],
|
||||||
institutions_search_client: Annotated[
|
institutions_search_client: Annotated[
|
||||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
],
|
],
|
||||||
@@ -234,15 +393,21 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
] = None,
|
] = None,
|
||||||
author_ids: Annotated[
|
author_ids: Annotated[
|
||||||
list[str] | None,
|
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,
|
] = None,
|
||||||
organization_ids: Annotated[
|
organization_ids: Annotated[
|
||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="CORDIS organisation IDs. All selected organizations must match."),
|
Query(
|
||||||
|
description="CORDIS organisation IDs. All selected organizations must match."
|
||||||
|
),
|
||||||
] = None,
|
] = None,
|
||||||
organization_names: Annotated[
|
organization_names: Annotated[
|
||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="CORDIS organization names. All selected organizations must match."),
|
Query(
|
||||||
|
description="CORDIS organization names. All selected organizations must match."
|
||||||
|
),
|
||||||
] = None,
|
] = None,
|
||||||
project_types: Annotated[
|
project_types: Annotated[
|
||||||
list[EuCordisProjectType] | None,
|
list[EuCordisProjectType] | None,
|
||||||
@@ -297,7 +462,9 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
] = "asc",
|
] = "asc",
|
||||||
fuzzy: Annotated[
|
fuzzy: Annotated[
|
||||||
bool,
|
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,
|
] = False,
|
||||||
) -> EuCordisProjectSearchPage:
|
) -> EuCordisProjectSearchPage:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -330,7 +497,18 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
sort_direction,
|
sort_direction,
|
||||||
fuzzy,
|
fuzzy,
|
||||||
)
|
)
|
||||||
|
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,
|
||||||
|
detail="Access denied for the provided author ID or institution ID",
|
||||||
|
)
|
||||||
return await search_eu_cordis_projects(
|
return await search_eu_cordis_projects(
|
||||||
institutions_search_client=institutions_search_client,
|
institutions_search_client=institutions_search_client,
|
||||||
raw_oa_institution_id=raw_oa_institution_id,
|
raw_oa_institution_id=raw_oa_institution_id,
|
||||||
@@ -356,6 +534,7 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
fuzzy=fuzzy,
|
fuzzy=fuzzy,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/eu/{id}",
|
"/eu/{id}",
|
||||||
summary="Get a single EU Cordis project.",
|
summary="Get a single EU Cordis project.",
|
||||||
@@ -368,16 +547,18 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
},
|
},
|
||||||
status.HTTP_404_NOT_FOUND: {
|
status.HTTP_404_NOT_FOUND: {
|
||||||
"description": "Project not found",
|
"description": "Project not found",
|
||||||
"model": EuCordisProjectResponse
|
"model": EuCordisProjectResponse,
|
||||||
},
|
},
|
||||||
status.HTTP_500_INTERNAL_SERVER_ERROR: {
|
status.HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||||
"description": "Internal server error",
|
"description": "Internal server error",
|
||||||
"model": EuCordisProjectResponse
|
"model": EuCordisProjectResponse,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
async def get_single_eu_cordis_project(
|
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:
|
) -> EuCordisProjectResponse:
|
||||||
"""
|
"""
|
||||||
Get a single EU Cordis project by ID.
|
Get a single EU Cordis project by ID.
|
||||||
@@ -396,7 +577,7 @@ async def get_single_eu_cordis_project(
|
|||||||
success=False,
|
success=False,
|
||||||
project_type=None,
|
project_type=None,
|
||||||
eu_project_data=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
|
# Determine the project type
|
||||||
@@ -413,15 +594,12 @@ async def get_single_eu_cordis_project(
|
|||||||
success=False,
|
success=False,
|
||||||
project_type=None,
|
project_type=None,
|
||||||
eu_project_data=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 success with the project data
|
||||||
return EuCordisProjectResponse(
|
return EuCordisProjectResponse(
|
||||||
success=True,
|
success=True, project_type=project_type, eu_project_data=project, error=None
|
||||||
project_type=project_type,
|
|
||||||
eu_project_data=project,
|
|
||||||
error=None
|
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -430,7 +608,7 @@ async def get_single_eu_cordis_project(
|
|||||||
success=False,
|
success=False,
|
||||||
project_type=None,
|
project_type=None,
|
||||||
eu_project_data=None,
|
eu_project_data=None,
|
||||||
error=f"Internal server error: {e!s}"
|
error=f"Internal server error: {e!s}",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -497,7 +675,9 @@ async def get_institution_bund_projects_funding_over_time(
|
|||||||
] = None,
|
] = None,
|
||||||
fuzzy: Annotated[
|
fuzzy: Annotated[
|
||||||
bool,
|
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,
|
] = False,
|
||||||
) -> InstitutionFunderSummary:
|
) -> InstitutionFunderSummary:
|
||||||
return await projects_service.get_institution_bund_projects_funding_over_time(
|
return await projects_service.get_institution_bund_projects_funding_over_time(
|
||||||
@@ -548,15 +728,21 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
|||||||
] = None,
|
] = None,
|
||||||
author_ids: Annotated[
|
author_ids: Annotated[
|
||||||
list[str] | None,
|
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,
|
] = None,
|
||||||
organization_ids: Annotated[
|
organization_ids: Annotated[
|
||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="CORDIS organisation IDs. All selected organizations must match."),
|
Query(
|
||||||
|
description="CORDIS organisation IDs. All selected organizations must match."
|
||||||
|
),
|
||||||
] = None,
|
] = None,
|
||||||
organization_names: Annotated[
|
organization_names: Annotated[
|
||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="CORDIS organization names. All selected organizations must match."),
|
Query(
|
||||||
|
description="CORDIS organization names. All selected organizations must match."
|
||||||
|
),
|
||||||
] = None,
|
] = None,
|
||||||
project_types: Annotated[
|
project_types: Annotated[
|
||||||
list[EuCordisProjectType] | None,
|
list[EuCordisProjectType] | None,
|
||||||
@@ -604,7 +790,9 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
|||||||
] = None,
|
] = None,
|
||||||
fuzzy: Annotated[
|
fuzzy: Annotated[
|
||||||
bool,
|
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,
|
] = False,
|
||||||
) -> InstitutionFunderSummary:
|
) -> InstitutionFunderSummary:
|
||||||
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
|
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
|
||||||
@@ -629,102 +817,6 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/person/dfg/search",
|
|
||||||
summary="Get DFG projects.",
|
|
||||||
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
|
|
||||||
operation_id="getDfgProjects",
|
|
||||||
responses={
|
|
||||||
status.HTTP_200_OK: {
|
|
||||||
"description": "Successful Response",
|
|
||||||
"model": DfgProjectPage,
|
|
||||||
},
|
|
||||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
|
||||||
},
|
|
||||||
response_model_by_alias=False,
|
|
||||||
)
|
|
||||||
async def get_dfg_projects(
|
|
||||||
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[int] | None, Query(description="The dfg author IDs to filter by.")] = None,
|
|
||||||
institution_ids: Annotated[
|
|
||||||
list[int] | 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.")
|
|
||||||
] = None,
|
|
||||||
topic_ids: Annotated[
|
|
||||||
list[str] | None, Query(description="The openalex topic IDs to filter by.")
|
|
||||||
] = None,
|
|
||||||
filter_topic_ids: Annotated[
|
|
||||||
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."
|
|
||||||
),
|
|
||||||
] = 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",
|
|
||||||
sort_direction: Annotated[
|
|
||||||
str, Query(description="The sort direction (asc or desc).")
|
|
||||||
] = "asc",
|
|
||||||
fuzzy: Annotated[
|
|
||||||
bool,
|
|
||||||
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, "
|
|
||||||
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
|
||||||
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
|
||||||
"sort_direction=%s, fuzzy=%s",
|
|
||||||
author_id,
|
|
||||||
author_filter_ids,
|
|
||||||
institution_ids,
|
|
||||||
keywords,
|
|
||||||
topic_ids,
|
|
||||||
filter_topic_ids,
|
|
||||||
title,
|
|
||||||
funding_start_years,
|
|
||||||
funding_end_years,
|
|
||||||
page,
|
|
||||||
size,
|
|
||||||
sort_by,
|
|
||||||
sort_direction,
|
|
||||||
fuzzy,
|
|
||||||
)
|
|
||||||
return await projects_service.get_dfg_projects_by_author_id(
|
|
||||||
institutions_search_client=institutions_search_client,
|
|
||||||
raw_oa_institution_id=raw_oa_institution_id,
|
|
||||||
author_id=author_id,
|
|
||||||
author_filter_ids=author_filter_ids,
|
|
||||||
institution_ids=institution_ids,
|
|
||||||
funding_start_years=funding_start_years,
|
|
||||||
funding_end_years=funding_end_years,
|
|
||||||
title=title,
|
|
||||||
keywords=keywords,
|
|
||||||
topic_ids=topic_ids,
|
|
||||||
filter_topic_ids=filter_topic_ids,
|
|
||||||
page=page,
|
|
||||||
size=size,
|
|
||||||
sort_by=sort_by,
|
|
||||||
sort_direction=sort_direction,
|
|
||||||
fuzzy=fuzzy,
|
|
||||||
)
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/search",
|
"/search",
|
||||||
summary="Search projects across all funders.",
|
summary="Search projects across all funders.",
|
||||||
@@ -747,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."
|
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,
|
] = None,
|
||||||
title: Annotated[
|
title: Annotated[str | None, Query(description="The title to filter by.")] = None,
|
||||||
str | None, Query(description="The title to filter by.")
|
|
||||||
] = None,
|
|
||||||
sort_by: Annotated[
|
sort_by: Annotated[
|
||||||
ProjectsSortBy, Query(description="The field to sort by.")
|
ProjectsSortBy, Query(description="The field to sort by.")
|
||||||
] = ProjectsSortBy.TITLE,
|
] = ProjectsSortBy.TITLE,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import logging
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from inse.exceptions import NotFoundException
|
from inse.exceptions import NotFoundException
|
||||||
|
from inse.auth.model import AccessTokenMetadata
|
||||||
from inse.institutions.institutions_search_client import (
|
from inse.institutions.institutions_search_client import (
|
||||||
InstitutionsSearchClient,
|
InstitutionsSearchClient,
|
||||||
)
|
)
|
||||||
@@ -26,9 +27,7 @@ from inse.projects.eu_cordis_projects_client import (
|
|||||||
from inse.projects.eu_cordis_projects_client import (
|
from inse.projects.eu_cordis_projects_client import (
|
||||||
search_eu_cordis_projects as _search_eu_cordis_projects_es,
|
search_eu_cordis_projects as _search_eu_cordis_projects_es,
|
||||||
)
|
)
|
||||||
from inse.projects.logic import (
|
|
||||||
get_dfg_author_names_by_ids,
|
|
||||||
)
|
|
||||||
from inse.projects.model import (
|
from inse.projects.model import (
|
||||||
BundProjectPage,
|
BundProjectPage,
|
||||||
DfgProjectPage,
|
DfgProjectPage,
|
||||||
@@ -41,8 +40,9 @@ from inse.projects.model import (
|
|||||||
ProjectType,
|
ProjectType,
|
||||||
SortDirection,
|
SortDirection,
|
||||||
)
|
)
|
||||||
|
from inse.projects.logic import get_dfg_author_names_by_ids
|
||||||
from inse.works.logic import get_publication_dois_of_author
|
from inse.works.logic import get_publication_dois_of_author
|
||||||
|
from fastapi import HTTPException as HttpException
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -157,12 +157,25 @@ async def _get_dfg_project_ids_for_openalex_authors(
|
|||||||
|
|
||||||
return list(set.intersection(*project_sets))
|
return list(set.intersection(*project_sets))
|
||||||
|
|
||||||
async def get_dfg_projects_by_author_id(
|
def _is_number_list(values: list[str] | None) -> bool:
|
||||||
|
if not values:
|
||||||
|
return True # nothing to validate, treat as valid/empty
|
||||||
|
for value in values:
|
||||||
|
if value is None or value == "":
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def get_dfg_projects(
|
||||||
institutions_search_client: InstitutionsSearchClient,
|
institutions_search_client: InstitutionsSearchClient,
|
||||||
raw_oa_institution_id: str | None,
|
raw_oa_institution_id: str | None,
|
||||||
author_id: str | None,
|
author_id: str | None,
|
||||||
author_filter_ids: list[int] | None,
|
author_filter_ids: list[str] | None,
|
||||||
institution_ids: list[int] | None,
|
institution_ids: list[str] | None,
|
||||||
keywords: list[str] | None,
|
keywords: list[str] | None,
|
||||||
topic_ids: list[str] | None,
|
topic_ids: list[str] | None,
|
||||||
filter_topic_ids: list[str] | None,
|
filter_topic_ids: list[str] | None,
|
||||||
@@ -174,6 +187,10 @@ async def get_dfg_projects_by_author_id(
|
|||||||
sort_by: str = "topic",
|
sort_by: str = "topic",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
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:
|
) -> DfgProjectPage:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||||
@@ -195,6 +212,23 @@ async def get_dfg_projects_by_author_id(
|
|||||||
sort_direction,
|
sort_direction,
|
||||||
fuzzy,
|
fuzzy,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Validate author_filter_ids / institution_ids. Return an empty page
|
||||||
|
if not _is_number_list(author_filter_ids) or not _is_number_list(institution_ids):
|
||||||
|
logger.debug(
|
||||||
|
"Invalid author_filter_ids=%s or institution_ids=%s, returning empty page",
|
||||||
|
author_filter_ids,
|
||||||
|
institution_ids,
|
||||||
|
)
|
||||||
|
return DfgProjectPage(elements=[], page=page, size=size, total=0)
|
||||||
|
|
||||||
|
author_filter_ids_int = (
|
||||||
|
[int(float(v)) for v in author_filter_ids] if author_filter_ids else None
|
||||||
|
)
|
||||||
|
institution_ids_int = (
|
||||||
|
[int(float(v)) for v in institution_ids] if institution_ids else None
|
||||||
|
)
|
||||||
|
|
||||||
filter_names = []
|
filter_names = []
|
||||||
author_project_ids = []
|
author_project_ids = []
|
||||||
if author_id:
|
if author_id:
|
||||||
@@ -207,25 +241,29 @@ async def get_dfg_projects_by_author_id(
|
|||||||
size=size,
|
size=size,
|
||||||
total=0)
|
total=0)
|
||||||
|
|
||||||
if author_filter_ids:
|
if author_filter_ids_int:
|
||||||
filter_names = (
|
filter_names = (
|
||||||
await get_dfg_author_names_by_ids(author_ids=author_filter_ids)
|
await get_dfg_author_names_by_ids(author_ids=author_filter_ids_int)
|
||||||
if author_filter_ids
|
if author_filter_ids_int
|
||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
if author_filter_ids and not filter_names:
|
if author_filter_ids_int and not filter_names:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"No author names found for author_filter_ids=%s",
|
"No author names found for author_filter_ids=%s",
|
||||||
author_filter_ids,
|
author_filter_ids_int,
|
||||||
)
|
)
|
||||||
institution_aliases = []
|
resolved_institution_aliases = list(institution_aliases or [])
|
||||||
if raw_oa_institution_id:
|
if raw_oa_institution_id:
|
||||||
institution_aliases = (
|
if institutions_search_client is None:
|
||||||
|
raise ValueError(
|
||||||
|
"institutions_search_client must be provided when raw_oa_institution_id is set"
|
||||||
|
)
|
||||||
|
resolved_institution_aliases.extend(
|
||||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
raw_oa_institution_id
|
raw_oa_institution_id
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if not institution_aliases:
|
if not resolved_institution_aliases:
|
||||||
return DfgProjectPage(
|
return DfgProjectPage(
|
||||||
elements=[],
|
elements=[],
|
||||||
page=page,
|
page=page,
|
||||||
@@ -235,10 +273,10 @@ async def get_dfg_projects_by_author_id(
|
|||||||
return await projects_search_client.search_dfg_projects(
|
return await projects_search_client.search_dfg_projects(
|
||||||
page=page,
|
page=page,
|
||||||
size=size,
|
size=size,
|
||||||
institution_aliases=institution_aliases,
|
institution_aliases=resolved_institution_aliases,
|
||||||
project_ids=author_project_ids,
|
project_ids=author_project_ids,
|
||||||
names=filter_names or [],
|
names=filter_names or [],
|
||||||
institution_ids=institution_ids,
|
institution_ids=institution_ids_int,
|
||||||
keywords=keywords,
|
keywords=keywords,
|
||||||
topic_ids=topic_ids,
|
topic_ids=topic_ids,
|
||||||
filter_topic_ids=filter_topic_ids,
|
filter_topic_ids=filter_topic_ids,
|
||||||
@@ -248,6 +286,9 @@ async def get_dfg_projects_by_author_id(
|
|||||||
sort_by=sort_by,
|
sort_by=sort_by,
|
||||||
sort_direction=sort_direction,
|
sort_direction=sort_direction,
|
||||||
fuzzy=fuzzy,
|
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(
|
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||||
@@ -423,9 +464,16 @@ async def search_bund_projects_with_filters(
|
|||||||
sort_by: str = "title",
|
sort_by: str = "title",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
active_from_year: int | None = None,
|
||||||
|
active_to_year: int | None = None,
|
||||||
|
oa_institution_aliases: list[str] | None = None,
|
||||||
) -> BundProjectPage:
|
) -> BundProjectPage:
|
||||||
institution_aliases = []
|
institution_aliases = list(oa_institution_aliases or [])
|
||||||
if raw_oa_institution_id:
|
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 = (
|
institution_aliases = (
|
||||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
raw_oa_institution_id
|
raw_oa_institution_id
|
||||||
@@ -454,7 +502,9 @@ async def search_bund_projects_with_filters(
|
|||||||
size=size,
|
size=size,
|
||||||
sort_by=sort_by,
|
sort_by=sort_by,
|
||||||
sort_direction=sort_direction,
|
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(
|
def _calculate_funding_over_time(
|
||||||
@@ -616,6 +666,8 @@ async def search_eu_cordis_projects(
|
|||||||
title: str | None = None,
|
title: str | None = None,
|
||||||
funding_start_years: list[str] | None = None,
|
funding_start_years: list[str] | None = None,
|
||||||
funding_end_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,
|
countries: list[str] | None = None,
|
||||||
framework_programmes: list[str] | None = None,
|
framework_programmes: list[str] | None = None,
|
||||||
funding_schemes: list[str] | None = None,
|
funding_schemes: list[str] | None = None,
|
||||||
@@ -623,6 +675,7 @@ async def search_eu_cordis_projects(
|
|||||||
sort_by: str = "title",
|
sort_by: str = "title",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
) -> EuCordisProjectSearchPage:
|
) -> EuCordisProjectSearchPage:
|
||||||
"""Single entry point for EU CORDIS project search.
|
"""Single entry point for EU CORDIS project search.
|
||||||
|
|
||||||
@@ -639,7 +692,6 @@ async def search_eu_cordis_projects(
|
|||||||
eu_cordis_projects_client.search_eu_cordis_projects.
|
eu_cordis_projects_client.search_eu_cordis_projects.
|
||||||
"""
|
"""
|
||||||
resolved_organization_names: list[str] = list(organization_names or [])
|
resolved_organization_names: list[str] = list(organization_names or [])
|
||||||
|
|
||||||
if raw_oa_institution_id:
|
if raw_oa_institution_id:
|
||||||
if institutions_search_client is None:
|
if institutions_search_client is None:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
@@ -676,6 +728,8 @@ async def search_eu_cordis_projects(
|
|||||||
title=title,
|
title=title,
|
||||||
funding_start_years=funding_start_years,
|
funding_start_years=funding_start_years,
|
||||||
funding_end_years=funding_end_years,
|
funding_end_years=funding_end_years,
|
||||||
|
active_from_year=active_from_year,
|
||||||
|
active_to_year=active_to_year,
|
||||||
countries=countries,
|
countries=countries,
|
||||||
framework_programmes=framework_programmes,
|
framework_programmes=framework_programmes,
|
||||||
funding_schemes=funding_schemes,
|
funding_schemes=funding_schemes,
|
||||||
@@ -683,4 +737,5 @@ async def search_eu_cordis_projects(
|
|||||||
sort_by=sort_by,
|
sort_by=sort_by,
|
||||||
sort_direction=sort_direction,
|
sort_direction=sort_direction,
|
||||||
fuzzy=fuzzy,
|
fuzzy=fuzzy,
|
||||||
|
skip_enrichment=skip_enrichment,
|
||||||
)
|
)
|
||||||
@@ -2,6 +2,21 @@ import pytest
|
|||||||
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
|
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
|
@pytest.mark.anyio
|
||||||
async def test_search_eu_cordis_projects_by_title():
|
async def test_search_eu_cordis_projects_by_title():
|
||||||
"""Test searching EU CORDIS projects by title."""
|
"""Test searching EU CORDIS projects by title."""
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from inse.projects import projects_search_client
|
from inse.projects import projects_search_client
|
||||||
|
|
||||||
|
|
||||||
@@ -20,6 +23,33 @@ async def test_search_dfg_projects():
|
|||||||
for name in element.names
|
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
|
@pytest.mark.anyio
|
||||||
async def test_get_dfg_project_by_id():
|
async def test_get_dfg_project_by_id():
|
||||||
# Get by ID of the project we found or a known one
|
# Get by ID of the project we found or a known one
|
||||||
|
|||||||
@@ -3,11 +3,10 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from math import floor
|
||||||
from time import time
|
from time import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
from inse.authors.institution_membership_query import (
|
from inse.authors.institution_membership_query import (
|
||||||
build_active_institution_membership_query,
|
build_active_institution_membership_query,
|
||||||
)
|
)
|
||||||
@@ -746,15 +745,29 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _min_max_normalize(values: pd.Series) -> pd.Series:
|
def _quantile(values: list[float], quantile: float) -> float:
|
||||||
|
"""Returns a linearly interpolated quantile (the former pandas default)."""
|
||||||
|
ordered = sorted(values)
|
||||||
|
if not ordered:
|
||||||
|
return 0.0
|
||||||
|
position = (len(ordered) - 1) * quantile
|
||||||
|
lower_index = floor(position)
|
||||||
|
upper_index = min(lower_index + 1, len(ordered) - 1)
|
||||||
|
fraction = position - lower_index
|
||||||
|
return ordered[lower_index] + (
|
||||||
|
ordered[upper_index] - ordered[lower_index]
|
||||||
|
) * fraction
|
||||||
|
|
||||||
|
|
||||||
|
def _min_max_normalize(values: list[float]) -> list[float]:
|
||||||
"""Scales a numeric column to the range [0, 1] via min-max normalization."""
|
"""Scales a numeric column to the range [0, 1] via min-max normalization."""
|
||||||
minimum = values.min()
|
minimum = min(values)
|
||||||
maximum = values.max()
|
maximum = max(values)
|
||||||
# if all values are the same, return a series of 1.0 to avoid division by zero.
|
# if all values are the same, return a series of 1.0 to avoid division by zero.
|
||||||
if maximum == minimum:
|
if maximum == minimum:
|
||||||
return pd.Series([1.0] * len(values))
|
return [1.0] * len(values)
|
||||||
|
|
||||||
return (values - minimum) / (maximum - minimum)
|
return [(value - minimum) / (maximum - minimum) for value in values]
|
||||||
|
|
||||||
|
|
||||||
def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
||||||
@@ -775,38 +788,29 @@ def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
|||||||
news_counts.append(author.news_count)
|
news_counts.append(author.news_count)
|
||||||
patents_counts.append(author.patents_count)
|
patents_counts.append(author.patents_count)
|
||||||
|
|
||||||
frame = pd.DataFrame({
|
|
||||||
"works": works_counts,
|
|
||||||
"citations": citations_counts,
|
|
||||||
"companies": companies_counts,
|
|
||||||
"news": news_counts,
|
|
||||||
"patents": patents_counts,
|
|
||||||
})
|
|
||||||
|
|
||||||
quantile_value = 0.95
|
quantile_value = 0.95
|
||||||
|
metrics = [
|
||||||
frame["works"] = frame["works"].clip(upper=frame["works"].quantile(quantile_value))
|
works_counts,
|
||||||
frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(quantile_value))
|
citations_counts,
|
||||||
frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(quantile_value))
|
companies_counts,
|
||||||
frame["news"] = frame["news"].clip(upper=frame["news"].quantile(quantile_value))
|
news_counts,
|
||||||
frame["patents"] = frame["patents"].clip(upper=frame["patents"].quantile(quantile_value))
|
patents_counts,
|
||||||
|
]
|
||||||
works_normalized = _min_max_normalize(frame["works"])
|
normalized_metrics = [
|
||||||
citations_normalized = _min_max_normalize(frame["citations"])
|
_min_max_normalize(
|
||||||
companies_normalized = _min_max_normalize(frame["companies"])
|
[min(value, _quantile(values, quantile_value)) for value in values]
|
||||||
news_normalized = _min_max_normalize(frame["news"])
|
)
|
||||||
patents_normalized = _min_max_normalize(frame["patents"])
|
for values in metrics
|
||||||
|
]
|
||||||
scores = (
|
|
||||||
works_normalized * weights.works
|
|
||||||
+ citations_normalized * weights.citation
|
|
||||||
+ companies_normalized * weights.companies
|
|
||||||
+ news_normalized * weights.news
|
|
||||||
+ patents_normalized * weights.patents
|
|
||||||
)
|
|
||||||
|
|
||||||
for index, author in enumerate(authors):
|
for index, author in enumerate(authors):
|
||||||
author.score = float(scores.iloc[index])
|
author.score = float(
|
||||||
|
normalized_metrics[0][index] * weights.works
|
||||||
|
+ normalized_metrics[1][index] * weights.citation
|
||||||
|
+ normalized_metrics[2][index] * weights.companies
|
||||||
|
+ normalized_metrics[3][index] * weights.news
|
||||||
|
+ normalized_metrics[4][index] * weights.patents
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _author_score(author: RankedAuthor) -> float:
|
def _author_score(author: RankedAuthor) -> float:
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ from typing import Annotated
|
|||||||
import inse.topics.v2.service as topics_service
|
import inse.topics.v2.service as topics_service
|
||||||
from fastapi import APIRouter, Path, Query
|
from fastapi import APIRouter, Path, Query
|
||||||
from inse.model import SortDirection
|
from inse.model import SortDirection
|
||||||
|
from inse.models.openalex.domain import Domain
|
||||||
|
from inse.models.openalex.model_field import ModelField
|
||||||
|
from inse.models.openalex.subfield import Subfield
|
||||||
from inse.models.openalex.topic import Topic
|
from inse.models.openalex.topic import Topic
|
||||||
from inse.router_prefixes import RouterPrefixes
|
from inse.router_prefixes import RouterPrefixes
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
@@ -78,6 +81,48 @@ async def get_topic_by_id(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/domains/single/{domain_id}",
|
||||||
|
operation_id="getDomainById",
|
||||||
|
summary="Returns a domain for a given domain ID.",
|
||||||
|
)
|
||||||
|
async def get_domain_by_id(
|
||||||
|
domain_id: Annotated[
|
||||||
|
str,
|
||||||
|
Path(description="The ID of the domain to retrieve."),
|
||||||
|
],
|
||||||
|
) -> Domain:
|
||||||
|
return await topics_service.get_domain_by_id_or_raise(domain_id=domain_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/fields/single/{field_id}",
|
||||||
|
operation_id="getFieldById",
|
||||||
|
summary="Returns a field for a given field ID.",
|
||||||
|
)
|
||||||
|
async def get_field_by_id(
|
||||||
|
field_id: Annotated[
|
||||||
|
str,
|
||||||
|
Path(description="The ID of the field to retrieve."),
|
||||||
|
],
|
||||||
|
) -> ModelField:
|
||||||
|
return await topics_service.get_field_by_id_or_raise(field_id=field_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/subfields/single/{subfield_id}",
|
||||||
|
operation_id="getSubfieldById",
|
||||||
|
summary="Returns a subfield for a given subfield ID.",
|
||||||
|
)
|
||||||
|
async def get_subfield_by_id(
|
||||||
|
subfield_id: Annotated[
|
||||||
|
str,
|
||||||
|
Path(description="The ID of the subfield to retrieve."),
|
||||||
|
],
|
||||||
|
) -> Subfield:
|
||||||
|
return await topics_service.get_subfield_by_id_or_raise(subfield_id=subfield_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/topics/id",
|
"/topics/id",
|
||||||
operation_id="getTopicsByIds",
|
operation_id="getTopicsByIds",
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
from inse.exceptions import NotFoundException
|
from inse.exceptions import NotFoundException
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESIndex, SortDirection
|
from inse.model import ESIndex, SortDirection
|
||||||
|
from inse.models.openalex.domain import Domain
|
||||||
|
from inse.models.openalex.model_field import ModelField
|
||||||
|
from inse.models.openalex.subfield import Subfield
|
||||||
from inse.models.openalex.topic import Topic
|
from inse.models.openalex.topic import Topic
|
||||||
from inse.topics.v2.model import TopicPageV2, TopicSortBy
|
from inse.topics.v2.model import TopicPageV2, TopicSortBy
|
||||||
|
|
||||||
@@ -184,6 +187,117 @@ async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic:
|
|||||||
return topic
|
return topic
|
||||||
|
|
||||||
|
|
||||||
|
async def get_domain_by_id(domain_id: str) -> Domain | None:
|
||||||
|
"""Retrieves a domain based on its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
domain_id (str): The numeric OpenAlex ID of the domain to retrieve (e.g. "4").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Domain | None: The domain matching the provided ID, or None if not found.
|
||||||
|
"""
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_DOMAINS,
|
||||||
|
doc_id=domain_id,
|
||||||
|
source=["id", "display_name", "description"],
|
||||||
|
)
|
||||||
|
if response.get("found"):
|
||||||
|
return Domain.from_dict(response.get("_source", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_domain_by_id_or_raise(domain_id: str) -> Domain:
|
||||||
|
"""Retrieves a domain based on its ID, raising an exception if not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
domain_id (str): The ID of the domain to retrieve.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundException: If the domain with the specified ID is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Domain: The domain matching the provided ID.
|
||||||
|
"""
|
||||||
|
domain = await get_domain_by_id(domain_id)
|
||||||
|
if domain is None:
|
||||||
|
raise NotFoundException(f"Domain with ID {domain_id} not found.")
|
||||||
|
return domain
|
||||||
|
|
||||||
|
|
||||||
|
async def get_field_by_id(field_id: str) -> ModelField | None:
|
||||||
|
"""Retrieves a field based on its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field_id (str): The numeric OpenAlex ID of the field to retrieve (e.g. "27").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ModelField | None: The field matching the provided ID, or None if not found.
|
||||||
|
"""
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_FIELDS,
|
||||||
|
doc_id=field_id,
|
||||||
|
source=["id", "display_name", "description"],
|
||||||
|
)
|
||||||
|
if response.get("found"):
|
||||||
|
return ModelField.from_dict(response.get("_source", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_field_by_id_or_raise(field_id: str) -> ModelField:
|
||||||
|
"""Retrieves a field based on its ID, raising an exception if not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field_id (str): The ID of the field to retrieve.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundException: If the field with the specified ID is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ModelField: The field matching the provided ID.
|
||||||
|
"""
|
||||||
|
field = await get_field_by_id(field_id)
|
||||||
|
if field is None:
|
||||||
|
raise NotFoundException(f"Field with ID {field_id} not found.")
|
||||||
|
return field
|
||||||
|
|
||||||
|
|
||||||
|
async def get_subfield_by_id(subfield_id: str) -> Subfield | None:
|
||||||
|
"""Retrieves a subfield based on its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subfield_id (str): The numeric OpenAlex ID of the subfield to retrieve (e.g. "2743").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Subfield | None: The subfield matching the provided ID, or None if not found.
|
||||||
|
"""
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_SUBFIELDS,
|
||||||
|
doc_id=subfield_id,
|
||||||
|
source=["id", "display_name", "description"],
|
||||||
|
)
|
||||||
|
if response.get("found"):
|
||||||
|
return Subfield.from_dict(response.get("_source", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_subfield_by_id_or_raise(subfield_id: str) -> Subfield:
|
||||||
|
"""Retrieves a subfield based on its ID, raising an exception if not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subfield_id (str): The ID of the subfield to retrieve.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundException: If the subfield with the specified ID is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Subfield: The subfield matching the provided ID.
|
||||||
|
"""
|
||||||
|
subfield = await get_subfield_by_id(subfield_id)
|
||||||
|
if subfield is None:
|
||||||
|
raise NotFoundException(f"Subfield with ID {subfield_id} not found.")
|
||||||
|
return subfield
|
||||||
|
|
||||||
|
|
||||||
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
||||||
"""Retrieves topics based on a list of topic IDs.
|
"""Retrieves topics based on a list of topic IDs.
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
@@ -11,6 +12,17 @@ logger = logging.getLogger(__name__)
|
|||||||
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
||||||
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
||||||
|
|
||||||
|
# Reserved characters and boolean operators of the Lucene query_string syntax
|
||||||
|
_LUCENE_SPECIAL_CHARS = re.compile(r'([+\-=&|><!(){}\[\]^"~*?:\\/])')
|
||||||
|
_LUCENE_BOOL_OPERATORS = re.compile(r"\b(AND|OR|NOT)\b")
|
||||||
|
|
||||||
|
|
||||||
|
def escape_lucene_query(term: str) -> str:
|
||||||
|
"""Escapes a free-text search term so it is safe inside a ``query_string`` query."""
|
||||||
|
if not term:
|
||||||
|
return ""
|
||||||
|
escaped = _LUCENE_SPECIAL_CHARS.sub(r"\\\1", term)
|
||||||
|
return _LUCENE_BOOL_OPERATORS.sub(lambda m: f'"{m.group(1)}"', escaped)
|
||||||
|
|
||||||
|
|
||||||
def clean_inst_id(id_str: str) -> str:
|
def clean_inst_id(id_str: str) -> str:
|
||||||
@@ -407,6 +419,56 @@ class TrendQueryBuilder:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_cc_news_year_agg_body(
|
||||||
|
term: str,
|
||||||
|
start_year: int,
|
||||||
|
end_year: int,
|
||||||
|
languages: list[str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Builds a size=0 yearly-count aggregation over the Common Crawl News indices. Buckets
|
||||||
|
by year with a `date_histogram`, since cc-news has a real `content_date` date field rather than
|
||||||
|
the integer `date_year` of `aktuell`.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"size": 0,
|
||||||
|
"track_total_hits": False,
|
||||||
|
"_source": False,
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"filter": [
|
||||||
|
{
|
||||||
|
"query_string": {
|
||||||
|
"query": escape_lucene_query(term),
|
||||||
|
"fields": CC_NEWS_SEARCH_FIELDS,
|
||||||
|
"default_operator": "AND",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{"terms": {"language_code": languages or CC_NEWS_LANGUAGES}},
|
||||||
|
{
|
||||||
|
"range": {
|
||||||
|
"content_date": {
|
||||||
|
"gte": f"{start_year}-01-01",
|
||||||
|
"lte": f"{end_year}-12-31",
|
||||||
|
"format": "yyyy-MM-dd",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"by_year": {
|
||||||
|
"date_histogram": {
|
||||||
|
"field": "content_date",
|
||||||
|
"calendar_interval": "year",
|
||||||
|
"format": "yyyy",
|
||||||
|
"min_doc_count": 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]:
|
def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]:
|
||||||
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
|
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
|
||||||
@@ -443,4 +505,7 @@ DFG_PROJECT_TEXT_FIELDS = [
|
|||||||
|
|
||||||
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
|
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
|
||||||
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
||||||
|
CC_NEWS_SEARCH_FIELDS = ["title", "body"]
|
||||||
|
CC_NEWS_LANGUAGES = ["de", "en"]
|
||||||
|
CC_NEWS_START_YEAR = 2017
|
||||||
|
|
||||||
|
|||||||
@@ -16,11 +16,13 @@ from .model import (
|
|||||||
)
|
)
|
||||||
from .trend_query_builder import (
|
from .trend_query_builder import (
|
||||||
AKTUELLES_SEARCH_FIELDS,
|
AKTUELLES_SEARCH_FIELDS,
|
||||||
|
CC_NEWS_START_YEAR,
|
||||||
DEFAULT_INSTITUTION_ID,
|
DEFAULT_INSTITUTION_ID,
|
||||||
DEFAULT_INSTITUTION_NAME,
|
DEFAULT_INSTITUTION_NAME,
|
||||||
TrendMetadataResolver,
|
TrendMetadataResolver,
|
||||||
TrendQueryBuilder,
|
TrendQueryBuilder,
|
||||||
clean_inst_id,
|
clean_inst_id,
|
||||||
|
escape_lucene_query,
|
||||||
to_full_inst_url,
|
to_full_inst_url,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -47,6 +49,13 @@ EPO_PATENT_FIELDS = [
|
|||||||
"openalex_topics.topic_id",
|
"openalex_topics.topic_id",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# Synthetic entity id prefixes for the news trend series. The webapp keys colouring, chip
|
||||||
|
# visibility and pie filtering off these, so keep them in sync with uni-trend-parent.component.ts.
|
||||||
|
NEWS_ENTITY_PREFIX = "news_topic_"
|
||||||
|
CC_NEWS_ENTITY_PREFIX = "ccnews_topic_"
|
||||||
|
# Entity id of the collapsed CC-News series in the cross-domain ("all") view.
|
||||||
|
CC_NEWS_COMPOSITE_ID = "ccnews"
|
||||||
|
|
||||||
DFG_INSTITUTION_FIELDS = [
|
DFG_INSTITUTION_FIELDS = [
|
||||||
"Antragstellende Institution",
|
"Antragstellende Institution",
|
||||||
"Mitantragstellende Institution",
|
"Mitantragstellende Institution",
|
||||||
@@ -1042,6 +1051,18 @@ class ProjectsTrendStrategy(TrendStrategy):
|
|||||||
|
|
||||||
|
|
||||||
class NewsTrendStrategy(TrendStrategy):
|
class NewsTrendStrategy(TrendStrategy):
|
||||||
|
"""Yearly news counts per topic.
|
||||||
|
|
||||||
|
Produces one series per topic from the UDE-internal `aktuell` index (entity id
|
||||||
|
``news_topic_<topic>``). When keyword matching is active (``fuzzy=False``) it additionally
|
||||||
|
produces an external Common Crawl News baseline per topic (``ccnews_topic_<topic>``) so the
|
||||||
|
internal coverage can be compared against the wider web. CC-News has no OpenAlex topic
|
||||||
|
mapping, so it is skipped entirely in topic-mapping mode.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, include_cc_news: bool = True):
|
||||||
|
self.include_cc_news = include_cc_news
|
||||||
|
|
||||||
async def get_trend(
|
async def get_trend(
|
||||||
self,
|
self,
|
||||||
topics: list[str],
|
topics: list[str],
|
||||||
@@ -1054,20 +1075,40 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
) -> TrendResponse:
|
) -> TrendResponse:
|
||||||
years_range = self._get_years_range()
|
years_range = self._get_years_range()
|
||||||
start_year, end_year = years_range[0], years_range[-1]
|
start_year, end_year = years_range[0], years_range[-1]
|
||||||
|
years_set = set(years_range)
|
||||||
|
|
||||||
|
cc_news_enabled = self.include_cc_news and not fuzzy
|
||||||
|
|
||||||
accumulated_data = {
|
accumulated_data = {
|
||||||
f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
||||||
for t in topics
|
for t in topics
|
||||||
}
|
}
|
||||||
|
if cc_news_enabled:
|
||||||
|
accumulated_data.update({
|
||||||
|
f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
||||||
|
for t in topics
|
||||||
|
})
|
||||||
|
|
||||||
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
|
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
|
||||||
|
|
||||||
|
def resolve_keyword_term(idx: int, t_name: str) -> str:
|
||||||
|
"""Picks the raw keyword for a topic, falling back to the topic name itself."""
|
||||||
|
if keywords and idx < len(keywords) and keywords[idx]:
|
||||||
|
raw_kw = keywords[idx]
|
||||||
|
term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw
|
||||||
|
if term:
|
||||||
|
return term
|
||||||
|
return t_name
|
||||||
|
|
||||||
|
def is_searchable_term(term: str) -> bool:
|
||||||
|
return bool(term) and term.lower() not in STOP_WORDS and len(term.strip()) > 1
|
||||||
|
|
||||||
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
|
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
|
||||||
async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]:
|
async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]:
|
||||||
news_ids: Set[str] = set()
|
news_ids: Set[str] = set()
|
||||||
if fuzzy:
|
if fuzzy:
|
||||||
term = t_name
|
term = t_name
|
||||||
es_query = {"term": {"topic_matches.topic_display_name.keyword": term}}
|
es_query = {"match_phrase": {"topic_matches.topic_display_name": term}}
|
||||||
try:
|
try:
|
||||||
async for hit in elasticsearch.scan(
|
async for hit in elasticsearch.scan(
|
||||||
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
|
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
|
||||||
@@ -1081,20 +1122,14 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
|
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
|
||||||
else:
|
else:
|
||||||
if keywords and idx < len(keywords) and keywords[idx]:
|
term = resolve_keyword_term(idx, t_name)
|
||||||
raw_kw = keywords[idx]
|
|
||||||
term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw
|
|
||||||
if not term:
|
|
||||||
term = t_name
|
|
||||||
else:
|
|
||||||
term = t_name
|
|
||||||
|
|
||||||
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
|
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
|
||||||
if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
|
if is_searchable_term(term):
|
||||||
try:
|
try:
|
||||||
content_query = {
|
content_query = {
|
||||||
"query_string": {
|
"query_string": {
|
||||||
"query": term,
|
"query": escape_lucene_query(term),
|
||||||
"fields": AKTUELLES_SEARCH_FIELDS,
|
"fields": AKTUELLES_SEARCH_FIELDS,
|
||||||
"default_operator": "AND",
|
"default_operator": "AND",
|
||||||
}
|
}
|
||||||
@@ -1113,12 +1148,59 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
|
|
||||||
return list(news_ids)
|
return list(news_ids)
|
||||||
|
|
||||||
matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)))
|
async def fetch_cc_news_counts() -> dict[int, dict[int, int]]:
|
||||||
|
"""Yearly CC-News counts per topic index, from a single _msearch over cc-news-*.
|
||||||
|
The year buckets are read straight off a size=0 date_histogram instead.
|
||||||
|
"""
|
||||||
|
searchable = [
|
||||||
|
(idx, term)
|
||||||
|
for idx, t_name in enumerate(topics)
|
||||||
|
if is_searchable_term(term := resolve_keyword_term(idx, t_name))
|
||||||
|
]
|
||||||
|
if not searchable:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
searches = [
|
||||||
|
(
|
||||||
|
ESIndex.CC_NEWS_WILDCARD.value,
|
||||||
|
TrendQueryBuilder.build_cc_news_year_agg_body(term, CC_NEWS_START_YEAR, end_year),
|
||||||
|
)
|
||||||
|
for _, term in searchable
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
responses = await elasticsearch.msearch(
|
||||||
|
searches, cluster=ESCluster.NES, request_cache=True
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to aggregate CC-News years via msearch: %s", e)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
counts: dict[int, dict[int, int]] = {}
|
||||||
|
for (topic_idx, term), res in zip(searchable, responses):
|
||||||
|
if not isinstance(res, dict) or "error" in res:
|
||||||
|
logger.warning("CC-News msearch entry for %r failed: %s", term, (res or {}).get("error"))
|
||||||
|
continue
|
||||||
|
by_year: dict[int, int] = {}
|
||||||
|
for b in res.get("aggregations", {}).get("by_year", {}).get("buckets", []):
|
||||||
|
try:
|
||||||
|
yr = int(b.get("key_as_string"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if yr in years_set:
|
||||||
|
by_year[yr] = int(b.get("doc_count", 0))
|
||||||
|
counts[topic_idx] = by_year
|
||||||
|
return counts
|
||||||
|
|
||||||
|
news_ids_future = asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)))
|
||||||
|
if cc_news_enabled:
|
||||||
|
matching_ids_list, cc_news_counts = await asyncio.gather(news_ids_future, fetch_cc_news_counts())
|
||||||
|
else:
|
||||||
|
matching_ids_list, cc_news_counts = await news_ids_future, {}
|
||||||
|
|
||||||
async def count_by_year(t_name: str, news_ids: list[str]):
|
async def count_by_year(t_name: str, news_ids: list[str]):
|
||||||
if not news_ids:
|
if not news_ids:
|
||||||
return
|
return
|
||||||
entity_key = f"news_topic_{t_name}"
|
entity_key = f"{NEWS_ENTITY_PREFIX}{t_name}"
|
||||||
|
|
||||||
# Prepare multi-search payloads for chunks of news_ids to avoid payload limits
|
# Prepare multi-search payloads for chunks of news_ids to avoid payload limits
|
||||||
chunk_queries = []
|
chunk_queries = []
|
||||||
@@ -1164,13 +1246,15 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
|
|
||||||
await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list)))
|
await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list)))
|
||||||
|
|
||||||
|
for topic_idx, t_name in enumerate(topics):
|
||||||
|
entity_key = f"{CC_NEWS_ENTITY_PREFIX}{t_name}"
|
||||||
|
for yr, count in cc_news_counts.get(topic_idx, {}).items():
|
||||||
|
prev_count, _ = accumulated_data[entity_key][t_name][yr]
|
||||||
|
accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1)
|
||||||
|
|
||||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||||
|
|
||||||
series_list: list[TrendSeries] = []
|
def build_series(entity_key: str, t_name: str, entity_name: str) -> TrendSeries:
|
||||||
for t_name in topics:
|
|
||||||
entity_key = f"news_topic_{t_name}"
|
|
||||||
topic_data_map: dict[str, list[TopicYearlyData]] = {}
|
|
||||||
|
|
||||||
lookup = normalized_lookup.get((entity_key, t_name), {})
|
lookup = normalized_lookup.get((entity_key, t_name), {})
|
||||||
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||||
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||||
@@ -1188,16 +1272,22 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
for topic in topics:
|
topic_data_map: dict[str, list[TopicYearlyData]] = {topic: yearly_data_items for topic in topics}
|
||||||
topic_data_map[topic] = yearly_data_items
|
|
||||||
|
|
||||||
series_list.append(
|
return TrendSeries(
|
||||||
TrendSeries(
|
entity_id=entity_key,
|
||||||
entity_id=entity_key,
|
entity_name=entity_name,
|
||||||
entity_name=t_name,
|
entity_type="institution",
|
||||||
entity_type="institution",
|
topic_data=topic_data_map,
|
||||||
topic_data=topic_data_map,
|
)
|
||||||
)
|
|
||||||
|
series_list: list[TrendSeries] = [
|
||||||
|
build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics
|
||||||
|
]
|
||||||
|
if cc_news_enabled:
|
||||||
|
series_list.extend(
|
||||||
|
build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)")
|
||||||
|
for t_name in topics
|
||||||
)
|
)
|
||||||
|
|
||||||
return TrendResponse(series=series_list, years=years_range)
|
return TrendResponse(series=series_list, years=years_range)
|
||||||
@@ -1269,25 +1359,40 @@ class AllTrendStrategy(TrendStrategy):
|
|||||||
add_composite(pat_series, "patents", "Patentanmeldungen")
|
add_composite(pat_series, "patents", "Patentanmeldungen")
|
||||||
add_composite(proj_series, "projects", "Drittmittelförderung")
|
add_composite(proj_series, "projects", "Drittmittelförderung")
|
||||||
|
|
||||||
if is_ude and news_res:
|
def merge_news_composite(prefix: str, c_id: str, c_name: str) -> bool:
|
||||||
merged_news_topic_data: dict[str, list[TopicYearlyData]] = {}
|
"""Collapses the per-topic news series of one source into a single composite.
|
||||||
|
|
||||||
|
Returns False when the source produced no series at all.
|
||||||
|
"""
|
||||||
|
if not news_res or not any(s.entity_id.startswith(prefix) for s in news_res.series):
|
||||||
|
return False
|
||||||
|
|
||||||
|
merged_topic_data: dict[str, list[TopicYearlyData]] = {}
|
||||||
for topic in topics:
|
for topic in topics:
|
||||||
term_key = f"news_topic_{topic}"
|
term_key = f"{prefix}{topic}"
|
||||||
matching_series = next((s for s in news_res.series if s.entity_id == term_key), None)
|
matching_series = next((s for s in news_res.series if s.entity_id == term_key), None)
|
||||||
if matching_series and topic in matching_series.topic_data:
|
if matching_series and topic in matching_series.topic_data:
|
||||||
merged_news_topic_data[topic] = matching_series.topic_data[topic]
|
merged_topic_data[topic] = matching_series.topic_data[topic]
|
||||||
else:
|
else:
|
||||||
merged_news_topic_data[topic] = [
|
merged_topic_data[topic] = [
|
||||||
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
|
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
|
||||||
for yr in years_range
|
for yr in years_range
|
||||||
]
|
]
|
||||||
|
|
||||||
news_series = TrendSeries(
|
add_composite(
|
||||||
entity_id="news",
|
TrendSeries(
|
||||||
entity_name="UDE Campus Aktuell Beiträge",
|
entity_id=c_id,
|
||||||
entity_type="institution",
|
entity_name=c_name,
|
||||||
topic_data=merged_news_topic_data,
|
entity_type="institution",
|
||||||
|
topic_data=merged_topic_data,
|
||||||
|
),
|
||||||
|
c_id,
|
||||||
|
c_name,
|
||||||
)
|
)
|
||||||
add_composite(news_series, "news", "UDE Campus Aktuell Beiträge")
|
return True
|
||||||
|
|
||||||
|
if is_ude:
|
||||||
|
merge_news_composite(NEWS_ENTITY_PREFIX, "news", "UDE Campus Aktuell Beiträge")
|
||||||
|
merge_news_composite(CC_NEWS_ENTITY_PREFIX, CC_NEWS_COMPOSITE_ID, "Web-Nachrichten (CC-News)")
|
||||||
|
|
||||||
return TrendResponse(series=composite_series, years=years_range)
|
return TrendResponse(series=composite_series, years=years_range)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2])
|
|||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/{raw_oa_work_id}",
|
"/single/{raw_oa_work_id}",
|
||||||
operation_id="getWorkById",
|
operation_id="getWorkById",
|
||||||
summary="Returns a work based on its ID.",
|
summary="Returns a work based on its ID.",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -654,6 +654,7 @@ async def _search_works(
|
|||||||
size=size,
|
size=size,
|
||||||
offset=page * size,
|
offset=page * size,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
|
track_total_hits=True
|
||||||
)
|
)
|
||||||
|
|
||||||
hits_block = response.get("hits", {})
|
hits_block = response.get("hits", {})
|
||||||
|
|||||||
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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "pluggy"
|
name = "pluggy"
|
||||||
version = "1.6.0"
|
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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "python-dotenv"
|
name = "python-dotenv"
|
||||||
version = "1.2.2"
|
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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "pyyaml"
|
name = "pyyaml"
|
||||||
version = "6.0.3"
|
version = "6.0.3"
|
||||||
@@ -1143,6 +1211,7 @@ dependencies = [
|
|||||||
{ name = "fastapi" },
|
{ name = "fastapi" },
|
||||||
{ name = "httpx" },
|
{ name = "httpx" },
|
||||||
{ name = "openai" },
|
{ name = "openai" },
|
||||||
|
{ name = "pandas" },
|
||||||
{ name = "pydantic" },
|
{ name = "pydantic" },
|
||||||
{ name = "pydantic-settings" },
|
{ name = "pydantic-settings" },
|
||||||
{ name = "pyjwt" },
|
{ name = "pyjwt" },
|
||||||
@@ -1165,6 +1234,7 @@ requires-dist = [
|
|||||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||||
{ name = "httpx", specifier = "~=0.27.0" },
|
{ name = "httpx", specifier = "~=0.27.0" },
|
||||||
{ name = "openai", specifier = "~=2.41.0" },
|
{ name = "openai", specifier = "~=2.41.0" },
|
||||||
|
{ name = "pandas", specifier = "~=2.3.3" },
|
||||||
{ name = "pydantic", specifier = "~=2.7.1" },
|
{ name = "pydantic", specifier = "~=2.7.1" },
|
||||||
{ name = "pydantic-settings", specifier = "~=2.2.1" },
|
{ name = "pydantic-settings", specifier = "~=2.2.1" },
|
||||||
{ name = "pyjwt", specifier = "~=2.8.0" },
|
{ 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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "sniffio"
|
name = "sniffio"
|
||||||
version = "1.3.1"
|
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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "uvicorn"
|
name = "uvicorn"
|
||||||
version = "0.29.0"
|
version = "0.29.0"
|
||||||
|
|||||||
@@ -103,11 +103,11 @@ model/dfgPersonSummary.ts
|
|||||||
model/dfgPersonSummaryPage.ts
|
model/dfgPersonSummaryPage.ts
|
||||||
model/dfgProjectDetails.ts
|
model/dfgProjectDetails.ts
|
||||||
model/dfgProjectInstitutionRole.ts
|
model/dfgProjectInstitutionRole.ts
|
||||||
|
model/dfgProjectKeyword.ts
|
||||||
model/dfgProjectPage.ts
|
model/dfgProjectPage.ts
|
||||||
model/dfgProjectPersonRole.ts
|
model/dfgProjectPersonRole.ts
|
||||||
model/dfgProjectPublicationSummary.ts
|
model/dfgProjectPublicationSummary.ts
|
||||||
model/dfgProjectStatusStatistics.ts
|
model/dfgProjectStatusStatistics.ts
|
||||||
model/dfgProjectSubjectArea.ts
|
|
||||||
model/dfgProjectSubprojectSummary.ts
|
model/dfgProjectSubprojectSummary.ts
|
||||||
model/dfgProjectSummary.ts
|
model/dfgProjectSummary.ts
|
||||||
model/dfgProjectTopic.ts
|
model/dfgProjectTopic.ts
|
||||||
@@ -169,6 +169,8 @@ model/idTokenMetadata.ts
|
|||||||
model/inseAccountManagementModelOrganizationProfile.ts
|
model/inseAccountManagementModelOrganizationProfile.ts
|
||||||
model/inseOrganizationManagementModelOrganizationProfile.ts
|
model/inseOrganizationManagementModelOrganizationProfile.ts
|
||||||
model/institution.ts
|
model/institution.ts
|
||||||
|
model/institutionAssociation.ts
|
||||||
|
model/institutionAssociationsResponse.ts
|
||||||
model/institutionFunderSummary.ts
|
model/institutionFunderSummary.ts
|
||||||
model/institutionGeo.ts
|
model/institutionGeo.ts
|
||||||
model/institutionIds.ts
|
model/institutionIds.ts
|
||||||
|
|||||||
@@ -65,6 +65,71 @@ export class AuthService extends BaseService {
|
|||||||
super(basePath, configuration);
|
super(basePath, configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if user can fetch GDPR-relevant data
|
||||||
|
* Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.
|
||||||
|
* @endpoint get /api/auth/v2/can-fetch-gdpr-relevant-data
|
||||||
|
* @param rawOaAuthorId OpenAlex author ID to check access for
|
||||||
|
* @param rawOaInstitutionId OpenAlex institution ID to check access for
|
||||||
|
* @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 canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<boolean>;
|
||||||
|
public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<boolean>>;
|
||||||
|
public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<boolean>>;
|
||||||
|
public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, 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>rawOaAuthorId, 'raw_oa_author_id');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>rawOaInstitutionId, 'raw_oa_institution_id');
|
||||||
|
|
||||||
|
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/auth/v2/can-fetch-gdpr-relevant-data`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<boolean>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Change Password
|
* Change Password
|
||||||
* Change the user\'s password and invalidate existing tokens.
|
* Change the user\'s password and invalidate existing tokens.
|
||||||
|
|||||||
+1528
-526
File diff suppressed because it is too large
Load Diff
@@ -9,12 +9,18 @@
|
|||||||
*/
|
*/
|
||||||
/* tslint:disable:no-unused-variable member-ordering */
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
import { Inject, Injectable, Optional } from '@angular/core';
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
import { HttpClient, HttpHeaders, HttpParams,
|
import {
|
||||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
HttpClient,
|
||||||
} from '@angular/common/http';
|
HttpHeaders,
|
||||||
import { CustomHttpParameterCodec } from '../encoder';
|
HttpParams,
|
||||||
import { Observable } from 'rxjs';
|
HttpResponse,
|
||||||
|
HttpEvent,
|
||||||
|
HttpParameterCodec,
|
||||||
|
HttpContext,
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
|
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
|
||||||
@@ -23,292 +29,679 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile';
|
import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { InstitutionAssociationsResponse } from '../model/institutionAssociationsResponse';
|
||||||
|
// @ts-ignore
|
||||||
import { OrganizationPage } from '../model/organizationPage';
|
import { OrganizationPage } from '../model/organizationPage';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
|
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
import { Configuration } from '../configuration';
|
import { Configuration } from '../configuration';
|
||||||
import { BaseService } from '../api.base.service';
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class OrganizationService extends BaseService {
|
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.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
let localVarHeaders = this.defaultHeaders;
|
||||||
* 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;
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||||
|
'HTTPBearer',
|
||||||
|
'Authorization',
|
||||||
|
localVarHeaders,
|
||||||
|
'Bearer ',
|
||||||
|
);
|
||||||
|
|
||||||
// authentication (HTTPBearer) required
|
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
options?.httpHeaderAccept ??
|
||||||
|
this.configuration.selectHeaderAccept(['application/json']);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set(
|
||||||
|
'Accept',
|
||||||
|
localVarHttpHeaderAcceptSelected,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpContext: HttpContext =
|
||||||
'application/json'
|
options?.context ?? new HttpContext();
|
||||||
]);
|
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
|
||||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
let localVarPath = `/api/organizations`;
|
||||||
const consumes: string[] = [
|
const { basePath, withCredentials } = this.configuration;
|
||||||
'application/json'
|
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
|
||||||
];
|
'post',
|
||||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
`${basePath}${localVarPath}`,
|
||||||
if (httpContentTypeSelected !== undefined) {
|
{
|
||||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
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) {
|
* Delete Organization
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
* @endpoint delete /api/organizations/{organization_id}
|
||||||
responseType_ = 'text';
|
* @param organizationId
|
||||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
* @param secureFgpAcc
|
||||||
responseType_ = 'json';
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
} else {
|
* @param reportProgress flag to report request and response progress.
|
||||||
responseType_ = 'blob';
|
*/
|
||||||
}
|
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`;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
const { basePath, withCredentials } = this.configuration;
|
|
||||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('post', `${basePath}${localVarPath}`,
|
// authentication (HTTPBearer) required
|
||||||
{
|
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||||
context: localVarHttpContext,
|
'HTTPBearer',
|
||||||
body: createOrganizationRequest,
|
'Authorization',
|
||||||
responseType: <any>responseType_,
|
localVarHeaders,
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
'Bearer ',
|
||||||
headers: localVarHeaders,
|
);
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||||
reportProgress: reportProgress
|
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',
|
||||||
);
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
let localVarHeaders = this.defaultHeaders;
|
||||||
* 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;
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||||
|
'HTTPBearer',
|
||||||
|
'Authorization',
|
||||||
|
localVarHeaders,
|
||||||
|
'Bearer ',
|
||||||
|
);
|
||||||
|
|
||||||
// authentication (HTTPBearer) required
|
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
options?.httpHeaderAccept ??
|
||||||
|
this.configuration.selectHeaderAccept(['application/json']);
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
'application/json'
|
localVarHeaders = localVarHeaders.set(
|
||||||
]);
|
'Accept',
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
localVarHttpHeaderAcceptSelected,
|
||||||
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 localVarHttpContext: HttpContext =
|
||||||
* Get Organizations
|
options?.context ?? new HttpContext();
|
||||||
* @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});
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
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;
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
// authentication (HTTPBearer) required
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
responseType_ = 'text';
|
||||||
|
} else if (
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||||
'application/json'
|
) {
|
||||||
]);
|
responseType_ = 'json';
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
} else {
|
||||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
responseType_ = 'blob';
|
||||||
}
|
}
|
||||||
|
|
||||||
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 localVarPath = `/api/organizations/institutions/associations`;
|
||||||
* Update Organization
|
const { basePath, withCredentials } = this.configuration;
|
||||||
* @endpoint put /api/organizations/{organization_id}
|
return this.httpClient.request<Array<InstitutionAssociationsResponse>>(
|
||||||
* @param organizationId
|
'get',
|
||||||
* @param updateOrganizationRequest
|
`${basePath}${localVarPath}`,
|
||||||
* @param secureFgpAcc
|
{
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
context: localVarHttpContext,
|
||||||
* @param reportProgress flag to report request and response progress.
|
params: localVarQueryParameters,
|
||||||
*/
|
responseType: <any>responseType_,
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
headers: localVarHeaders,
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
observe: observe,
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
...(localVarTransferCache !== undefined
|
||||||
if (organizationId === null || organizationId === undefined) {
|
? { transferCache: localVarTransferCache }
|
||||||
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
|
: {}),
|
||||||
}
|
reportProgress: reportProgress,
|
||||||
if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) {
|
},
|
||||||
throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.');
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
/**
|
||||||
|
* Update Organization
|
||||||
// authentication (HTTPBearer) required
|
* @endpoint put /api/organizations/{organization_id}
|
||||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
* @param organizationId
|
||||||
|
* @param updateOrganizationRequest
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
* @param secureFgpAcc
|
||||||
'application/json'
|
* @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.
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
*/
|
||||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
public updateOrganisation(
|
||||||
}
|
organizationId: string,
|
||||||
|
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
secureFgpAcc?: string,
|
||||||
|
observe?: 'body',
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
reportProgress?: boolean,
|
||||||
|
options?: {
|
||||||
|
httpHeaderAccept?: 'application/json';
|
||||||
// to determine the Content-Type header
|
context?: HttpContext;
|
||||||
const consumes: string[] = [
|
transferCache?: boolean;
|
||||||
'application/json'
|
},
|
||||||
];
|
): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
public updateOrganisation(
|
||||||
if (httpContentTypeSelected !== undefined) {
|
organizationId: string,
|
||||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||||
}
|
secureFgpAcc?: string,
|
||||||
|
observe?: 'response',
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
reportProgress?: boolean,
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
options?: {
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
httpHeaderAccept?: 'application/json';
|
||||||
responseType_ = 'text';
|
context?: HttpContext;
|
||||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
transferCache?: boolean;
|
||||||
responseType_ = 'json';
|
},
|
||||||
} else {
|
): Observable<
|
||||||
responseType_ = 'blob';
|
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
|
||||||
}
|
>;
|
||||||
}
|
public updateOrganisation(
|
||||||
|
organizationId: string,
|
||||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
updateOrganizationRequest: UpdateOrganizationRequest,
|
||||||
const { basePath, withCredentials } = this.configuration;
|
secureFgpAcc?: string,
|
||||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('put', `${basePath}${localVarPath}`,
|
observe?: 'events',
|
||||||
{
|
reportProgress?: boolean,
|
||||||
context: localVarHttpContext,
|
options?: {
|
||||||
body: updateOrganizationRequest,
|
httpHeaderAccept?: 'application/json';
|
||||||
responseType: <any>responseType_,
|
context?: HttpContext;
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
transferCache?: boolean;
|
||||||
headers: localVarHeaders,
|
},
|
||||||
observe: observe,
|
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
public updateOrganisation(
|
||||||
reportProgress: reportProgress
|
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,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export class ProjectsService extends BaseService {
|
|||||||
/**
|
/**
|
||||||
* Get DFG projects.
|
* Get DFG projects.
|
||||||
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
|
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
|
||||||
* @endpoint get /api/projects/person/dfg/search
|
* @endpoint get /api/projects/dfg/search
|
||||||
* @param rawOaInstitutionId The openalex institution ID to filter by.
|
* @param rawOaInstitutionId The openalex institution ID to filter by.
|
||||||
* @param authorId The openalex author ID to filter by.
|
* @param authorId The openalex author ID to filter by.
|
||||||
* @param authorFilterIds The dfg author IDs to filter by.
|
* @param authorFilterIds The dfg author IDs to filter by.
|
||||||
@@ -82,13 +82,14 @@ export class ProjectsService extends BaseService {
|
|||||||
* @param sortBy The field to sort by.
|
* @param sortBy The field to sort by.
|
||||||
* @param sortDirection The sort direction (asc or desc).
|
* @param sortDirection The sort direction (asc or desc).
|
||||||
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
|
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
|
||||||
|
* @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 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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, 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});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
@@ -152,6 +153,9 @@ export class ProjectsService extends BaseService {
|
|||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
@@ -175,7 +179,7 @@ export class ProjectsService extends BaseService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarPath = `/api/projects/person/dfg/search`;
|
let localVarPath = `/api/projects/dfg/search`;
|
||||||
const { basePath, withCredentials } = this.configuration;
|
const { basePath, withCredentials } = this.configuration;
|
||||||
return this.httpClient.request<DfgProjectPage>('get', `${basePath}${localVarPath}`,
|
return this.httpClient.request<DfgProjectPage>('get', `${basePath}${localVarPath}`,
|
||||||
{
|
{
|
||||||
@@ -846,13 +850,14 @@ export class ProjectsService extends BaseService {
|
|||||||
* @param sortBy Sort field.
|
* @param sortBy Sort field.
|
||||||
* @param sortDirection Sort direction: asc or desc.
|
* @param sortDirection Sort direction: asc or desc.
|
||||||
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
||||||
|
* @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 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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, 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});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
if (executingAgency) {
|
if (executingAgency) {
|
||||||
@@ -920,6 +925,9 @@ export class ProjectsService extends BaseService {
|
|||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
@@ -984,13 +992,14 @@ export class ProjectsService extends BaseService {
|
|||||||
* @param sortBy Sort field.
|
* @param sortBy Sort field.
|
||||||
* @param sortDirection Sort direction: asc or desc.
|
* @param sortDirection Sort direction: asc or desc.
|
||||||
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
||||||
|
* @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 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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, 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});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
@@ -1090,6 +1099,9 @@ export class ProjectsService extends BaseService {
|
|||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -511,7 +511,7 @@ export class WorksV2Service extends BaseService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a work based on its ID.
|
* Returns a work based on its ID.
|
||||||
* @endpoint get /api/works/v2/{raw_oa_work_id}
|
* @endpoint get /api/works/v2/single/{raw_oa_work_id}
|
||||||
* @param rawOaWorkId The raw OpenAlex work id.
|
* @param rawOaWorkId The raw OpenAlex work id.
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
@@ -549,7 +549,7 @@ export class WorksV2Service extends BaseService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarPath = `/api/works/v2/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
let localVarPath = `/api/works/v2/single/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||||
const { basePath, withCredentials } = this.configuration;
|
const { basePath, withCredentials } = this.configuration;
|
||||||
return this.httpClient.request<Work>('get', `${basePath}${localVarPath}`,
|
return this.httpClient.request<Work>('get', `${basePath}${localVarPath}`,
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,9 +8,8 @@
|
|||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
export interface CreateOrganizationRequest {
|
export interface CreateOrganizationRequest {
|
||||||
name: string;
|
name: string;
|
||||||
other_inst_id?: string | null;
|
other_inst_id?: string | null;
|
||||||
|
selected_openalex_institution_ids?: Array<string> | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
import { DfgProjectPersonRole } from './dfgProjectPersonRole';
|
import { DfgProjectPersonRole } from './dfgProjectPersonRole';
|
||||||
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
|
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
|
||||||
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
|
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
|
||||||
import { DfgProjectSubjectArea } from './dfgProjectSubjectArea';
|
import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner';
|
||||||
import { Topic } from './topic';
|
import { Topic } from './topic';
|
||||||
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
|
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ export interface DfgProjectDetails {
|
|||||||
/**
|
/**
|
||||||
* Detailed DFG subject-area classification entries (Fachsystematik)
|
* Detailed DFG subject-area classification entries (Fachsystematik)
|
||||||
*/
|
*/
|
||||||
subject_classifications?: Array<DfgProjectSubjectArea>;
|
subject_classifications?: Array<DFGProjectFachgebieteInner>;
|
||||||
international_relation_de?: string | null;
|
international_relation_de?: string | null;
|
||||||
international_relation_en?: string | null;
|
international_relation_en?: string | null;
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
export interface DfgProjectKeyword {
|
||||||
|
name: string;
|
||||||
|
project_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A single subject-area classification entry (DFG \'Fachsystematik\').
|
|
||||||
*/
|
|
||||||
export interface DfgProjectSubjectArea {
|
|
||||||
fach?: string | null;
|
|
||||||
fachgebiet?: string | null;
|
|
||||||
fachkollegium?: string | null;
|
|
||||||
wissenschaftsbereich?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
import { DfgProjectKeyword } from './dfgProjectKeyword';
|
||||||
|
|
||||||
|
|
||||||
export interface DfgProjectTopic {
|
export interface DfgProjectTopic {
|
||||||
@@ -16,5 +17,5 @@ export interface DfgProjectTopic {
|
|||||||
field?: string | null;
|
field?: string | null;
|
||||||
domain?: string | null;
|
domain?: string | null;
|
||||||
project_count: number;
|
project_count: number;
|
||||||
|
keywords: Array<DfgProjectKeyword>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* 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 { DomainFieldsInner } from './domainFieldsInner';
|
||||||
|
import { DomainIds } from './domainIds';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Top-level category in the topic hierarchy (4 total)
|
||||||
|
*/
|
||||||
|
export interface Domain {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
display_name_alternatives?: Array<string> | null;
|
||||||
|
fields?: Array<DomainFieldsInner> | null;
|
||||||
|
siblings?: Array<DomainFieldsInner> | null;
|
||||||
|
ids?: DomainIds | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
cited_by_count?: number | null;
|
||||||
|
works_api_url?: string | null;
|
||||||
|
created_date?: string | null;
|
||||||
|
updated_date?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DomainFieldsInner
|
||||||
|
*/
|
||||||
|
export interface DomainFieldsInner {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* External identifiers:
|
||||||
|
*/
|
||||||
|
export interface DomainIds {
|
||||||
|
openalex?: string | null;
|
||||||
|
wikidata?: string | null;
|
||||||
|
wikipedia?: string | null;
|
||||||
|
}
|
||||||
@@ -8,12 +8,11 @@
|
|||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
export interface InseOrganizationManagementModelOrganizationProfile {
|
export interface InseOrganizationManagementModelOrganizationProfile {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
other_inst_id?: string | null;
|
other_inst_id?: string | null;
|
||||||
deleted: boolean;
|
selected_openalex_institution_ids?: Array<string>;
|
||||||
member_count: number;
|
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>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/**
|
||||||
|
* 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 { DomainFieldsInner } from './domainFieldsInner';
|
||||||
|
import { DomainIds } from './domainIds';
|
||||||
|
import { WorkTopicDomain } from './workTopicDomain';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Second-level category in the topic hierarchy (26 total)
|
||||||
|
*/
|
||||||
|
export interface ModelField {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
display_name_alternatives?: Array<string> | null;
|
||||||
|
domain?: WorkTopicDomain | null;
|
||||||
|
subfields?: Array<DomainFieldsInner> | null;
|
||||||
|
siblings?: Array<DomainFieldsInner> | null;
|
||||||
|
ids?: DomainIds | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
cited_by_count?: number | null;
|
||||||
|
works_api_url?: string | null;
|
||||||
|
created_date?: string | null;
|
||||||
|
updated_date?: string | null;
|
||||||
|
}
|
||||||
@@ -68,16 +68,19 @@ export * from './dfgPersonSummary';
|
|||||||
export * from './dfgPersonSummaryPage';
|
export * from './dfgPersonSummaryPage';
|
||||||
export * from './dfgProjectDetails';
|
export * from './dfgProjectDetails';
|
||||||
export * from './dfgProjectInstitutionRole';
|
export * from './dfgProjectInstitutionRole';
|
||||||
|
export * from './dfgProjectKeyword';
|
||||||
export * from './dfgProjectPage';
|
export * from './dfgProjectPage';
|
||||||
export * from './dfgProjectPersonRole';
|
export * from './dfgProjectPersonRole';
|
||||||
export * from './dfgProjectPublicationSummary';
|
export * from './dfgProjectPublicationSummary';
|
||||||
export * from './dfgProjectStatusStatistics';
|
export * from './dfgProjectStatusStatistics';
|
||||||
export * from './dfgProjectSubjectArea';
|
|
||||||
export * from './dfgProjectSubprojectSummary';
|
export * from './dfgProjectSubprojectSummary';
|
||||||
export * from './dfgProjectSummary';
|
export * from './dfgProjectSummary';
|
||||||
export * from './dfgProjectTopic';
|
export * from './dfgProjectTopic';
|
||||||
export * from './dfgProjectTopics';
|
export * from './dfgProjectTopics';
|
||||||
export * from './dockerHealth';
|
export * from './dockerHealth';
|
||||||
|
export * from './domain';
|
||||||
|
export * from './domainFieldsInner';
|
||||||
|
export * from './domainIds';
|
||||||
export * from './edge';
|
export * from './edge';
|
||||||
export * from './euCordisEurosciVocSummary';
|
export * from './euCordisEurosciVocSummary';
|
||||||
export * from './euCordisOrganizationSelectorPage';
|
export * from './euCordisOrganizationSelectorPage';
|
||||||
@@ -134,6 +137,8 @@ export * from './idTokenMetadata';
|
|||||||
export * from './inseAccountManagementModelOrganizationProfile';
|
export * from './inseAccountManagementModelOrganizationProfile';
|
||||||
export * from './inseOrganizationManagementModelOrganizationProfile';
|
export * from './inseOrganizationManagementModelOrganizationProfile';
|
||||||
export * from './institution';
|
export * from './institution';
|
||||||
|
export * from './institutionAssociation';
|
||||||
|
export * from './institutionAssociationsResponse';
|
||||||
export * from './institutionFunderSummary';
|
export * from './institutionFunderSummary';
|
||||||
export * from './institutionGeo';
|
export * from './institutionGeo';
|
||||||
export * from './institutionIds';
|
export * from './institutionIds';
|
||||||
@@ -172,6 +177,7 @@ export * from './matchedTopic';
|
|||||||
export * from './mentionedPerson';
|
export * from './mentionedPerson';
|
||||||
export * from './meta';
|
export * from './meta';
|
||||||
export * from './model2YrMeanCitedness';
|
export * from './model2YrMeanCitedness';
|
||||||
|
export * from './modelField';
|
||||||
export * from './newsArticle';
|
export * from './newsArticle';
|
||||||
export * from './newsArticleDetail';
|
export * from './newsArticleDetail';
|
||||||
export * from './newsPage';
|
export * from './newsPage';
|
||||||
@@ -206,6 +212,9 @@ export * from './score';
|
|||||||
export * from './selectedAuthorsRequest';
|
export * from './selectedAuthorsRequest';
|
||||||
export * from './sortDirection';
|
export * from './sortDirection';
|
||||||
export * from './startCollaborationGraphResponse';
|
export * from './startCollaborationGraphResponse';
|
||||||
|
export * from './subfield';
|
||||||
|
export * from './subfieldDomain';
|
||||||
|
export * from './subfieldField';
|
||||||
export * from './subfieldShare';
|
export * from './subfieldShare';
|
||||||
export * from './timespan';
|
export * from './timespan';
|
||||||
export * from './tokenType';
|
export * from './tokenType';
|
||||||
|
|||||||
@@ -7,16 +7,16 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
import { MatchedTopic } from './matchedTopic';
|
||||||
|
|
||||||
export interface NewsArticle {
|
export interface NewsArticle {
|
||||||
id: string;
|
id: string;
|
||||||
date?: string | null;
|
date?: string | null;
|
||||||
maintitle?: string | null;
|
maintitle?: string | null;
|
||||||
author?: string | null;
|
author?: string | null;
|
||||||
url?: string | null;
|
url?: string | null;
|
||||||
relevant?: boolean | null;
|
relevant?: boolean | null;
|
||||||
snippet?: string | null;
|
snippet?: string | null;
|
||||||
related?: boolean | null;
|
related?: boolean | null;
|
||||||
|
topics?: Array<MatchedTopic> | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,19 +10,17 @@
|
|||||||
import { MatchedTopic } from './matchedTopic';
|
import { MatchedTopic } from './matchedTopic';
|
||||||
import { MentionedPerson } from './mentionedPerson';
|
import { MentionedPerson } from './mentionedPerson';
|
||||||
|
|
||||||
|
|
||||||
export interface NewsArticleDetail {
|
export interface NewsArticleDetail {
|
||||||
id: string;
|
id: string;
|
||||||
date?: string | null;
|
date?: string | null;
|
||||||
maintitle?: string | null;
|
maintitle?: string | null;
|
||||||
author?: string | null;
|
author?: string | null;
|
||||||
url?: string | null;
|
url?: string | null;
|
||||||
relevant?: boolean | null;
|
relevant?: boolean | null;
|
||||||
snippet?: string | null;
|
snippet?: string | null;
|
||||||
related?: boolean | null;
|
related?: boolean | null;
|
||||||
full_content?: string | null;
|
topics?: Array<MatchedTopic>;
|
||||||
authors?: Array<MentionedPerson>;
|
full_content?: string | null;
|
||||||
keywords?: Array<string>;
|
authors?: Array<MentionedPerson>;
|
||||||
topics?: Array<MatchedTopic>;
|
keywords?: Array<string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* 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 { DomainFieldsInner } from './domainFieldsInner';
|
||||||
|
import { DomainIds } from './domainIds';
|
||||||
|
import { SubfieldDomain } from './subfieldDomain';
|
||||||
|
import { SubfieldField } from './subfieldField';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Third-level category in the topic hierarchy (254 total)
|
||||||
|
*/
|
||||||
|
export interface Subfield {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
display_name_alternatives?: Array<string> | null;
|
||||||
|
field?: SubfieldField | null;
|
||||||
|
domain?: SubfieldDomain | null;
|
||||||
|
topics?: Array<DomainFieldsInner> | null;
|
||||||
|
siblings?: Array<DomainFieldsInner> | null;
|
||||||
|
ids?: DomainIds | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
cited_by_count?: number | null;
|
||||||
|
works_api_url?: string | null;
|
||||||
|
created_date?: string | null;
|
||||||
|
updated_date?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The domain containing this subfield (top level of hierarchy).
|
||||||
|
*/
|
||||||
|
export interface SubfieldDomain {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The field containing this subfield (parent level).
|
||||||
|
*/
|
||||||
|
export interface SubfieldField {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
}
|
||||||
@@ -8,10 +8,9 @@
|
|||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
export interface UpdateOrganizationRequest {
|
export interface UpdateOrganizationRequest {
|
||||||
name?: string | null;
|
name?: string | null;
|
||||||
other_inst_id?: string | null;
|
other_inst_id?: string | null;
|
||||||
deleted?: boolean | null;
|
selected_openalex_institution_ids?: Array<string> | null;
|
||||||
|
deleted?: boolean | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { personPatentsResolver } from './resolvers/person-patents.resolver';
|
|||||||
import { personResolver } from './resolvers/person.resolver';
|
import { personResolver } from './resolvers/person.resolver';
|
||||||
import { personNewsResolver } from './resolvers/person-news.resolver';
|
import { personNewsResolver } from './resolvers/person-news.resolver';
|
||||||
import { institutionResolver } from './resolvers/institution.resolver';
|
import { institutionResolver } from './resolvers/institution.resolver';
|
||||||
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
|
||||||
import {
|
import {
|
||||||
dfgProjectsResolver,
|
dfgProjectsResolver,
|
||||||
RESOLVING_PROJECT_PAGE_FOR,
|
RESOLVING_PROJECT_PAGE_FOR,
|
||||||
@@ -37,6 +36,7 @@ import {
|
|||||||
workPageResolver,
|
workPageResolver,
|
||||||
workQueryParamKeys,
|
workQueryParamKeys,
|
||||||
} from './resolvers/work-page.resolver';
|
} from './resolvers/work-page.resolver';
|
||||||
|
import { keywordsNewsPageResolver } from './resolvers/keywords-news-page.resolver';
|
||||||
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
|
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
|
||||||
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
|
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
|
||||||
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
|
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
|
||||||
@@ -65,6 +65,7 @@ import {
|
|||||||
topicQueryParamKeys,
|
topicQueryParamKeys,
|
||||||
} from './resolvers/topic-page.resolver';
|
} from './resolvers/topic-page.resolver';
|
||||||
import { topicResolver } from './resolvers/topic.resolver';
|
import { topicResolver } from './resolvers/topic.resolver';
|
||||||
|
import { canFetchGdprRelevantDataResolver } from './resolvers/can-fetch-gdpr-relevant-data.resolver';
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
@@ -273,7 +274,14 @@ export const routes: Routes = [
|
|||||||
resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH,
|
resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ path: 'news', component: KeywordsToNewsResultsComponent },
|
{
|
||||||
|
path: 'news',
|
||||||
|
component: KeywordsToNewsResultsComponent,
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
resolve: {
|
||||||
|
newsPage: keywordsNewsPageResolver,
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'trends',
|
path: 'trends',
|
||||||
component: UniTrendParentComponent,
|
component: UniTrendParentComponent,
|
||||||
@@ -493,6 +501,7 @@ export const routes: Routes = [
|
|||||||
personData: personResolver,
|
personData: personResolver,
|
||||||
personBio: personBioResolver,
|
personBio: personBioResolver,
|
||||||
personPatents: personPatentsResolver,
|
personPatents: personPatentsResolver,
|
||||||
|
canFetchGdprRelevantData: canFetchGdprRelevantDataResolver,
|
||||||
},
|
},
|
||||||
runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'],
|
runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'],
|
||||||
children: [
|
children: [
|
||||||
@@ -658,16 +667,12 @@ export const routes: Routes = [
|
|||||||
import('./modules/institution/institution.component').then(
|
import('./modules/institution/institution.component').then(
|
||||||
(mod) => mod.InstitutionComponent,
|
(mod) => mod.InstitutionComponent,
|
||||||
),
|
),
|
||||||
resolve: { institution: institutionResolver },
|
resolve: {
|
||||||
|
institution: institutionResolver,
|
||||||
|
canFetchGdprRelevantData: canFetchGdprRelevantDataResolver,
|
||||||
|
},
|
||||||
children: [
|
children: [
|
||||||
{ path: '', pathMatch: 'full', redirectTo: 'overview' },
|
{ path: '', pathMatch: 'full', redirectTo: 'publications' },
|
||||||
{
|
|
||||||
path: 'overview',
|
|
||||||
loadComponent: () =>
|
|
||||||
import('./modules/institution-overview/institution-overview.component').then(
|
|
||||||
(mod) => mod.InstitutionOverviewComponent,
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: 'publications',
|
path: 'publications',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
@@ -696,7 +701,9 @@ export const routes: Routes = [
|
|||||||
bundProjectsFunding: bundProjectsFundingResolver,
|
bundProjectsFunding: bundProjectsFundingResolver,
|
||||||
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
||||||
},
|
},
|
||||||
runGuardsAndResolvers: 'always',
|
data: {
|
||||||
|
enableFilters: false,
|
||||||
|
},
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
@@ -746,18 +753,6 @@ export const routes: Routes = [
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
// resolve: {
|
|
||||||
// bundProjectPage: bundProjectPageResolver,
|
|
||||||
// bundProjectsFunding: bundProjectsFundingResolver,
|
|
||||||
// cordisEuProjectPage: euCordisProjectsResolver,
|
|
||||||
// cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
|
||||||
// },
|
|
||||||
// runGuardsAndResolvers: (from, to) => {
|
|
||||||
// const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
|
||||||
// return keys.some(
|
|
||||||
// (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
|
||||||
// );
|
|
||||||
// },
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'patents',
|
path: 'patents',
|
||||||
|
|||||||
@@ -1,76 +1,80 @@
|
|||||||
import {
|
import {
|
||||||
Directive,
|
Directive,
|
||||||
OnChanges,
|
|
||||||
Input,
|
|
||||||
ElementRef,
|
ElementRef,
|
||||||
|
Input,
|
||||||
|
OnChanges,
|
||||||
Renderer2,
|
Renderer2,
|
||||||
|
SimpleChanges,
|
||||||
|
effect,
|
||||||
|
inject,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { SimpleChanges } from '@angular/core';
|
import { ResolverStateService } from '../../app/shared/services/resolver-state.service';
|
||||||
@Directive({ selector: '[skText]', standalone: true })
|
|
||||||
|
@Directive({
|
||||||
|
selector: 'span, [skText]',
|
||||||
|
standalone: true,
|
||||||
|
})
|
||||||
export class SkTextDirective implements OnChanges {
|
export class SkTextDirective implements OnChanges {
|
||||||
@Input() skText = false;
|
@Input() skText = false;
|
||||||
|
|
||||||
private originalText = '';
|
private readonly el = inject(ElementRef<HTMLElement>);
|
||||||
private originalColor = '';
|
private readonly renderer = inject(Renderer2);
|
||||||
|
private readonly resolverStateService = inject(ResolverStateService);
|
||||||
|
|
||||||
constructor(
|
constructor() {
|
||||||
private el: ElementRef,
|
effect(() => {
|
||||||
private renderer: Renderer2,
|
const loading = this.skText || this.resolverStateService.isResolving();
|
||||||
) {}
|
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
if (loading) {
|
||||||
const change = changes['skText'];
|
this.showSkeleton();
|
||||||
|
} else {
|
||||||
// skip if value didn't actually change, or is undefined
|
this.hideSkeleton();
|
||||||
if (!change) return;
|
}
|
||||||
|
});
|
||||||
this.skText ? this.showSkeleton() : this.hideSkeleton();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private showSkeleton() {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
const el: HTMLElement = this.el.nativeElement;
|
if (!changes['skText']) {
|
||||||
this.originalText = el.textContent ?? '';
|
return;
|
||||||
this.originalColor = el.style.color;
|
}
|
||||||
|
|
||||||
// measure natural width before blanking text
|
if (this.skText || this.resolverStateService.isResolving()) {
|
||||||
const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60);
|
this.showSkeleton();
|
||||||
const height = 20;
|
} else {
|
||||||
this.renderer.addClass(el, 'sk-text-loading');
|
this.hideSkeleton();
|
||||||
this.renderer.setStyle(el, 'color', 'transparent');
|
}
|
||||||
this.renderer.setStyle(
|
}
|
||||||
el,
|
|
||||||
'background',
|
|
||||||
'linear-gradient(90deg, #e2e8f0 25%, #f8fafc 50%, #e2e8f0 75%)',
|
|
||||||
);
|
|
||||||
this.renderer.setStyle(el, 'background-size', '600px 100%');
|
|
||||||
this.renderer.setStyle(el, 'animation', 'sk-shimmer 1.6s infinite linear');
|
|
||||||
this.renderer.setStyle(el, 'border-radius', '4px');
|
|
||||||
this.renderer.setStyle(el, 'min-width', `${width}px`);
|
|
||||||
this.renderer.setStyle(el, 'max-height', `${height}px`);
|
|
||||||
this.renderer.setStyle(el, 'display', 'inline-block');
|
|
||||||
this.renderer.setStyle(el, 'overflow', 'hidden');
|
|
||||||
this.renderer.setStyle(el, 'pointer-events', 'none');
|
|
||||||
|
|
||||||
Array.from(el.children).forEach((child) => {
|
private showSkeleton(): void {
|
||||||
|
const element = this.el.nativeElement;
|
||||||
|
|
||||||
|
if (element.classList.contains('sk-text-loading')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = element.textContent?.trim() ?? '';
|
||||||
|
|
||||||
|
// For ordinary text elements only. Table cells use CSS width naturally.
|
||||||
|
if (element.tagName.toLowerCase() !== 'td') {
|
||||||
|
this.renderer.setStyle(element, 'min-width', `${20}px`);
|
||||||
|
this.renderer.setStyle(element, 'height', '20px');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.renderer.addClass(element, 'sk-text-loading');
|
||||||
|
|
||||||
|
Array.from(element.children).forEach((child) => {
|
||||||
this.renderer.setStyle(child, 'visibility', 'hidden');
|
this.renderer.setStyle(child, 'visibility', 'hidden');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private hideSkeleton() {
|
private hideSkeleton(): void {
|
||||||
const el: HTMLElement = this.el.nativeElement;
|
const element = this.el.nativeElement;
|
||||||
this.renderer.removeClass(el, 'sk-text-loading');
|
|
||||||
this.renderer.removeStyle(el, 'color');
|
|
||||||
this.renderer.removeStyle(el, 'background');
|
|
||||||
this.renderer.removeStyle(el, 'background-size');
|
|
||||||
this.renderer.removeStyle(el, 'animation');
|
|
||||||
this.renderer.removeStyle(el, 'border-radius');
|
|
||||||
this.renderer.removeStyle(el, 'min-width');
|
|
||||||
this.renderer.removeStyle(el, 'max-height');
|
|
||||||
this.renderer.removeStyle(el, 'display');
|
|
||||||
this.renderer.removeStyle(el, 'overflow');
|
|
||||||
this.renderer.removeStyle(el, 'pointer-events');
|
|
||||||
|
|
||||||
Array.from(el.children).forEach((child) => {
|
this.renderer.removeClass(element, 'sk-text-loading');
|
||||||
|
this.renderer.removeStyle(element, 'min-width');
|
||||||
|
this.renderer.removeStyle(element, 'height');
|
||||||
|
|
||||||
|
Array.from(element.children).forEach((child) => {
|
||||||
this.renderer.removeStyle(child, 'visibility');
|
this.renderer.removeStyle(child, 'visibility');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,12 +130,14 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
|
|||||||
.flexibleConnectedTo(this.elementRef)
|
.flexibleConnectedTo(this.elementRef)
|
||||||
.withPositions(positions)
|
.withPositions(positions)
|
||||||
.withFlexibleDimensions(false)
|
.withFlexibleDimensions(false)
|
||||||
|
.withViewportMargin(12)
|
||||||
.withPush(true);
|
.withPush(true);
|
||||||
|
|
||||||
this.overlayRef = this.overlay.create({
|
this.overlayRef = this.overlay.create({
|
||||||
positionStrategy,
|
positionStrategy,
|
||||||
scrollStrategy: this.overlay.scrollStrategies.reposition(),
|
scrollStrategy: this.overlay.scrollStrategies.reposition(),
|
||||||
panelClass: 'app-tooltip-panel',
|
panelClass: 'app-tooltip-panel',
|
||||||
|
maxWidth: this.tooltipMaxWidth() ?? 'calc(100vw - 24px)',
|
||||||
});
|
});
|
||||||
|
|
||||||
const portal = new ComponentPortal(this.component(), null, this.injector);
|
const portal = new ComponentPortal(this.component(), null, this.injector);
|
||||||
|
|||||||
@@ -10,8 +10,22 @@
|
|||||||
}}
|
}}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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) {
|
@if (!isReadOnly) {
|
||||||
<button
|
<button
|
||||||
|
class="create-account-button"
|
||||||
mat-flat-button
|
mat-flat-button
|
||||||
color="primary"
|
color="primary"
|
||||||
type="button"
|
type="button"
|
||||||
@@ -21,19 +35,6 @@
|
|||||||
Neuer Account
|
Neuer Account
|
||||||
</button>
|
</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>
|
</section>
|
||||||
<mat-card appearance="outlined">
|
<mat-card appearance="outlined">
|
||||||
<mat-card-content>
|
<mat-card-content>
|
||||||
|
|||||||
@@ -19,6 +19,25 @@
|
|||||||
gap: 16px;
|
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,
|
h1,
|
||||||
h2,
|
h2,
|
||||||
p {
|
p {
|
||||||
@@ -155,6 +174,22 @@ tr.deactivated:not(.deleted) {
|
|||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
flex-direction: column;
|
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,
|
mat-card,
|
||||||
|
|||||||
@@ -13,10 +13,11 @@
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
@if (loading()) {
|
@if (loading()) {
|
||||||
<div class="loading-state">
|
<app-loading
|
||||||
<mat-spinner diameter="42"></mat-spinner>
|
text="Bookmarks werden geladen …"
|
||||||
<p>Bookmarks werden geladen …</p>
|
icon="bookmarks"
|
||||||
</div>
|
[size]="60"
|
||||||
|
[diameter]="60" />
|
||||||
} @else if (persons().length) {
|
} @else if (persons().length) {
|
||||||
<section class="person-grid" aria-label="Gespeicherte Personen">
|
<section class="person-grid" aria-label="Gespeicherte Personen">
|
||||||
@for (person of persons(); track person.id) {
|
@for (person of persons(); track person.id) {
|
||||||
|
|||||||
@@ -65,7 +65,6 @@
|
|||||||
gap: 20px;
|
gap: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading-state,
|
|
||||||
.empty-state {
|
.empty-state {
|
||||||
display: flex;
|
display: flex;
|
||||||
min-height: 320px;
|
min-height: 320px;
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import { CommonModule } from '@angular/common';
|
|||||||
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
|
||||||
import { catchError, forkJoin, map, of, switchMap } from 'rxjs';
|
import { catchError, forkJoin, map, of, switchMap } from 'rxjs';
|
||||||
|
|
||||||
import { CustomAuthor, PersonsService } from '../../api';
|
import { CustomAuthor, PersonsService } from '../../api';
|
||||||
import { BookmarkService } from '../../shared/services/bookmark.service';
|
import { BookmarkService } from '../../shared/services/bookmark.service';
|
||||||
import { PersonCardComponent } from '../person-card/person-card.component';
|
import { PersonCardComponent } from '../person-card/person-card.component';
|
||||||
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
|
|
||||||
const PERSON_INCLUDE_TAGS =
|
const PERSON_INCLUDE_TAGS =
|
||||||
'display_name,works_count,cited_by_count,summary_stats,ids,' +
|
'display_name,works_count,cited_by_count,summary_stats,ids,' +
|
||||||
@@ -17,12 +17,7 @@ const PERSON_INCLUDE_TAGS =
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-bookmarks',
|
selector: 'app-bookmarks',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [
|
imports: [CommonModule, MatIconModule, PersonCardComponent, LoadingComponent],
|
||||||
CommonModule,
|
|
||||||
MatIconModule,
|
|
||||||
MatProgressSpinnerModule,
|
|
||||||
PersonCardComponent,
|
|
||||||
],
|
|
||||||
templateUrl: './bookmarks.component.html',
|
templateUrl: './bookmarks.component.html',
|
||||||
styleUrl: './bookmarks.component.scss',
|
styleUrl: './bookmarks.component.scss',
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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 { HttpClient } from '@angular/common/http';
|
||||||
import { Injectable, inject } from '@angular/core';
|
import { Injectable, inject } from '@angular/core';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable, catchError, forkJoin, map, of } from 'rxjs';
|
||||||
|
|
||||||
import { Configuration } from '../../api';
|
import { Configuration } from '../../api';
|
||||||
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
|
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
|
||||||
@@ -10,6 +10,11 @@ export interface DashboardPeriodBounds {
|
|||||||
toYear?: number;
|
toYear?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DashboardInstitution {
|
||||||
|
id: string;
|
||||||
|
display_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface DashboardStatistics {
|
export interface DashboardStatistics {
|
||||||
institution_id: string;
|
institution_id: string;
|
||||||
organization_name: string;
|
organization_name: string;
|
||||||
@@ -59,6 +64,8 @@ export interface DfgProjectTopic {
|
|||||||
field?: string | null;
|
field?: string | null;
|
||||||
domain?: string | null;
|
domain?: string | null;
|
||||||
project_count: number;
|
project_count: number;
|
||||||
|
field_project_count: number;
|
||||||
|
subfield_project_count: number;
|
||||||
keywords: DfgProjectKeyword[];
|
keywords: DfgProjectKeyword[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +82,9 @@ export interface DfgProjectTopics {
|
|||||||
topics: DfgProjectTopic[];
|
topics: DfgProjectTopic[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface EuProjectTopics extends DfgProjectTopics {}
|
||||||
|
export interface BundProjectTopics extends DfgProjectTopics {}
|
||||||
|
|
||||||
export interface TopAuthor {
|
export interface TopAuthor {
|
||||||
id?: string | null;
|
id?: string | null;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -90,6 +100,11 @@ export interface TopAuthorStatistics {
|
|||||||
news: TopAuthor[];
|
news: TopAuthor[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface TopAuthorAnalysis {
|
||||||
|
institution_id: string;
|
||||||
|
authors: TopAuthor[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface TopicWordCloudWord {
|
export interface TopicWordCloudWord {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -106,6 +121,12 @@ export class DashboardStatisticsService {
|
|||||||
private readonly httpClient = inject(HttpClient);
|
private readonly httpClient = inject(HttpClient);
|
||||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||||
|
|
||||||
|
getInstitutions(): Observable<DashboardInstitution[]> {
|
||||||
|
return this.httpClient.get<DashboardInstitution[]>(
|
||||||
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/institutions`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
getStatistics(): Observable<DashboardStatistics> {
|
getStatistics(): Observable<DashboardStatistics> {
|
||||||
return this.httpClient.get<DashboardStatistics>(
|
return this.httpClient.get<DashboardStatistics>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics`,
|
||||||
@@ -114,108 +135,171 @@ export class DashboardStatisticsService {
|
|||||||
|
|
||||||
getPublicationCount(
|
getPublicationCount(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DashboardStatisticValue> {
|
): Observable<DashboardStatisticValue> {
|
||||||
return this.httpClient.get<DashboardStatisticValue>(
|
return this.httpClient.get<DashboardStatisticValue>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/publications`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.statisticParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getPersonCount(
|
getPersonCount(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DashboardStatisticValue> {
|
): Observable<DashboardStatisticValue> {
|
||||||
return this.httpClient.get<DashboardStatisticValue>(
|
return this.httpClient.get<DashboardStatisticValue>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/persons`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/persons`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.statisticParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getPatentCount(
|
getPatentCount(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DashboardStatisticValue> {
|
): Observable<DashboardStatisticValue> {
|
||||||
return this.httpClient.get<DashboardStatisticValue>(
|
return this.httpClient.get<DashboardStatisticValue>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.statisticParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getEuProjectCount(
|
getEuProjectCount(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DashboardStatisticValue> {
|
): Observable<DashboardStatisticValue> {
|
||||||
return this.httpClient.get<DashboardStatisticValue>(
|
return this.httpClient.get<DashboardStatisticValue>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.statisticParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getEuProjectStatuses(
|
getEuProjectStatuses(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<EuProjectStatusStatistics> {
|
): Observable<EuProjectStatusStatistics> {
|
||||||
return this.httpClient.get<EuProjectStatusStatistics>(
|
return this.httpClient.get<EuProjectStatusStatistics>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.analyticalParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getBmbfProjectStatuses(
|
getBmbfProjectStatuses(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<BmbfProjectStatusStatistics> {
|
): Observable<BmbfProjectStatusStatistics> {
|
||||||
return this.httpClient.get<BmbfProjectStatusStatistics>(
|
return this.httpClient.get<BmbfProjectStatusStatistics>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.analyticalParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getDfgProjectStatuses(
|
getDfgProjectStatuses(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DfgProjectStatusStatistics> {
|
): Observable<DfgProjectStatusStatistics> {
|
||||||
return this.httpClient.get<DfgProjectStatusStatistics>(
|
return this.httpClient.get<DfgProjectStatusStatistics>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.analyticalParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getBmbfProjectCount(
|
getBmbfProjectCount(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DashboardStatisticValue> {
|
): Observable<DashboardStatisticValue> {
|
||||||
return this.httpClient.get<DashboardStatisticValue>(
|
return this.httpClient.get<DashboardStatisticValue>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.statisticParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getDfgProjectCount(
|
getDfgProjectCount(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DashboardStatisticValue> {
|
): Observable<DashboardStatisticValue> {
|
||||||
return this.httpClient.get<DashboardStatisticValue>(
|
return this.httpClient.get<DashboardStatisticValue>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/dfg`,
|
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/dfg`,
|
||||||
{ params: this.periodParams(period) },
|
{ params: this.statisticParams(period, institutionId) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getDfgProjectTopics(
|
getDfgProjectTopics(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<DfgProjectTopics> {
|
): Observable<DfgProjectTopics> {
|
||||||
return this.httpClient.get<DfgProjectTopics>(
|
return this.httpClient.get<DfgProjectTopics>(
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`,
|
`${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(
|
getTopAuthors(
|
||||||
period: DashboardPeriodBounds = {},
|
period: DashboardPeriodBounds = {},
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<TopAuthorStatistics> {
|
): Observable<TopAuthorStatistics> {
|
||||||
return this.httpClient.get<TopAuthorStatistics>(
|
const analysis = (source: string) =>
|
||||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`,
|
this.httpClient
|
||||||
{ params: this.periodParams(period) },
|
.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(
|
getTopicTreemap(
|
||||||
fromYear?: number,
|
fromYear?: number,
|
||||||
toYear?: number,
|
toYear?: number,
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<TopicTreemapData> {
|
): Observable<TopicTreemapData> {
|
||||||
const params: Record<string, number> = {};
|
const params: Record<string, string | number> = {
|
||||||
|
institution_id: institutionId,
|
||||||
|
};
|
||||||
if (fromYear !== undefined) params['from_year'] = fromYear;
|
if (fromYear !== undefined) params['from_year'] = fromYear;
|
||||||
if (toYear !== undefined) params['to_year'] = toYear;
|
if (toYear !== undefined) params['to_year'] = toYear;
|
||||||
|
|
||||||
@@ -229,8 +313,12 @@ export class DashboardStatisticsService {
|
|||||||
topicId: string,
|
topicId: string,
|
||||||
fromYear?: number,
|
fromYear?: number,
|
||||||
toYear?: number,
|
toYear?: number,
|
||||||
|
institutionId = 'all',
|
||||||
): Observable<TopicWordCloud> {
|
): 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 (fromYear !== undefined) params['from_year'] = fromYear;
|
||||||
if (toYear !== undefined) params['to_year'] = toYear;
|
if (toYear !== undefined) params['to_year'] = toYear;
|
||||||
return this.httpClient.get<TopicWordCloud>(
|
return this.httpClient.get<TopicWordCloud>(
|
||||||
@@ -245,4 +333,24 @@ export class DashboardStatisticsService {
|
|||||||
if (period.toYear !== undefined) params['to_year'] = period.toYear;
|
if (period.toYear !== undefined) params['to_year'] = period.toYear;
|
||||||
return params;
|
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()">
|
(endYearChange)="onDashboardPeriodRangeChange()">
|
||||||
</app-year-range-slider>
|
</app-year-range-slider>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
<section class="statistics-grid" aria-label="Kennzahlen">
|
<section class="statistics-grid" aria-label="Kennzahlen">
|
||||||
@@ -40,7 +59,9 @@
|
|||||||
[attr.aria-disabled]="!institutionRouteId()"
|
[attr.aria-disabled]="!institutionRouteId()"
|
||||||
[attr.aria-label]="
|
[attr.aria-label]="
|
||||||
'Publikationen von ' + organizationName() + ' anzeigen'
|
'Publikationen von ' + organizationName() + ' anzeigen'
|
||||||
">
|
"
|
||||||
|
matTooltip="Anzahl der Publikationen im ausgewählten Zeitraum"
|
||||||
|
matTooltipPosition="above">
|
||||||
<div class="statistics-icon statistics-icon--publications">
|
<div class="statistics-icon statistics-icon--publications">
|
||||||
<mat-icon>menu_book</mat-icon>
|
<mat-icon>menu_book</mat-icon>
|
||||||
</div>
|
</div>
|
||||||
@@ -60,7 +81,9 @@
|
|||||||
class="statistics-card"
|
class="statistics-card"
|
||||||
routerLink="/persons"
|
routerLink="/persons"
|
||||||
[queryParams]="personListQueryParams()"
|
[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">
|
<div class="statistics-icon statistics-icon--persons">
|
||||||
<mat-icon>groups</mat-icon>
|
<mat-icon>groups</mat-icon>
|
||||||
</div>
|
</div>
|
||||||
@@ -81,9 +104,11 @@
|
|||||||
[routerLink]="['/institution', institutionRouteId(), 'patents']"
|
[routerLink]="['/institution', institutionRouteId(), 'patents']"
|
||||||
[class.disabled]="!institutionRouteId()"
|
[class.disabled]="!institutionRouteId()"
|
||||||
[attr.aria-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">
|
<div class="statistics-icon statistics-icon--patents">
|
||||||
<mat-icon>description</mat-icon>
|
<mat-icon>{{ patentIcon }}</mat-icon>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span>Patente</span>
|
<span>Patente</span>
|
||||||
@@ -101,7 +126,9 @@
|
|||||||
class="statistics-card"
|
class="statistics-card"
|
||||||
routerLink="/projects"
|
routerLink="/projects"
|
||||||
[queryParams]="{ selected_project_types: 'eu' }"
|
[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">
|
<div class="statistics-icon statistics-icon--eu-projects">
|
||||||
<mat-icon>public</mat-icon>
|
<mat-icon>public</mat-icon>
|
||||||
</div>
|
</div>
|
||||||
@@ -121,7 +148,9 @@
|
|||||||
class="statistics-card"
|
class="statistics-card"
|
||||||
routerLink="/projects"
|
routerLink="/projects"
|
||||||
[queryParams]="{ selected_project_types: 'bund' }"
|
[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">
|
<div class="statistics-icon statistics-icon--bund-projects">
|
||||||
<mat-icon>account_balance</mat-icon>
|
<mat-icon>account_balance</mat-icon>
|
||||||
</div>
|
</div>
|
||||||
@@ -141,7 +170,9 @@
|
|||||||
class="statistics-card"
|
class="statistics-card"
|
||||||
routerLink="/projects"
|
routerLink="/projects"
|
||||||
[queryParams]="{ selected_project_types: 'dfg' }"
|
[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">
|
<div class="statistics-icon statistics-icon--dfg-projects">
|
||||||
<mat-icon>science</mat-icon>
|
<mat-icon>science</mat-icon>
|
||||||
</div>
|
</div>
|
||||||
@@ -162,6 +193,32 @@
|
|||||||
<p class="statistics-error">Die Kennzahlen konnten nicht geladen werden.</p>
|
<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 (
|
@if (
|
||||||
euProjectStatusesLoading ||
|
euProjectStatusesLoading ||
|
||||||
bmbfProjectStatusesLoading ||
|
bmbfProjectStatusesLoading ||
|
||||||
@@ -223,8 +280,8 @@
|
|||||||
diameter="64"></app-loading>
|
diameter="64"></app-loading>
|
||||||
</div>
|
</div>
|
||||||
} @else if (
|
} @else if (
|
||||||
euProjectStatusesError ||
|
euProjectStatusesError &&
|
||||||
bmbfProjectStatusesError ||
|
bmbfProjectStatusesError &&
|
||||||
dfgProjectStatusesError
|
dfgProjectStatusesError
|
||||||
) {
|
) {
|
||||||
<p class="statistics-error">
|
<p class="statistics-error">
|
||||||
@@ -234,6 +291,17 @@
|
|||||||
} @else if (
|
} @else if (
|
||||||
euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses
|
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
|
<app-eu-project-status-chart
|
||||||
[statuses]="euProjectStatuses"
|
[statuses]="euProjectStatuses"
|
||||||
[bmbfStatuses]="bmbfProjectStatuses"
|
[bmbfStatuses]="bmbfProjectStatuses"
|
||||||
@@ -317,6 +385,92 @@
|
|||||||
</section>
|
</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()) {
|
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
|
||||||
<section class="top-authors-section">
|
<section class="top-authors-section">
|
||||||
<header class="top-authors-header">
|
<header class="top-authors-header">
|
||||||
@@ -355,6 +509,8 @@
|
|||||||
class="author-name author-link"
|
class="author-name author-link"
|
||||||
[routerLink]="authorLink(dataset, entry)"
|
[routerLink]="authorLink(dataset, entry)"
|
||||||
[queryParams]="authorQueryParams(dataset, entry)"
|
[queryParams]="authorQueryParams(dataset, entry)"
|
||||||
|
[appComponentTooltip]="AuthorTooltipComponent"
|
||||||
|
[tooltipInputs]="{ authorId: entry.id }"
|
||||||
[title]="authorDisplayName(dataset, entry)">
|
[title]="authorDisplayName(dataset, entry)">
|
||||||
{{ authorDisplayName(dataset, entry) }}
|
{{ authorDisplayName(dataset, entry) }}
|
||||||
</a>
|
</a>
|
||||||
@@ -391,4 +547,5 @@
|
|||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -39,7 +39,22 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.dashboard-period-slider {
|
.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 {
|
.statistics-grid {
|
||||||
@@ -137,6 +152,74 @@
|
|||||||
color: var(--sg-error);
|
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 {
|
.top-authors-section {
|
||||||
margin-bottom: 2.5rem;
|
margin-bottom: 2.5rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe } from '@angular/common';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { Observable, finalize } from 'rxjs';
|
import { Observable, finalize } from 'rxjs';
|
||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||||
import { MatDialog } from '@angular/material/dialog';
|
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 { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component';
|
||||||
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
|
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
|
||||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
@@ -18,6 +24,8 @@ import {
|
|||||||
} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component';
|
} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component';
|
||||||
import {
|
import {
|
||||||
BmbfProjectStatusStatistics,
|
BmbfProjectStatusStatistics,
|
||||||
|
BundProjectTopics,
|
||||||
|
DashboardInstitution,
|
||||||
DashboardPeriodBounds,
|
DashboardPeriodBounds,
|
||||||
DashboardStatisticValue,
|
DashboardStatisticValue,
|
||||||
DashboardStatistics,
|
DashboardStatistics,
|
||||||
@@ -26,6 +34,7 @@ import {
|
|||||||
DfgProjectTopic,
|
DfgProjectTopic,
|
||||||
DfgProjectTopics,
|
DfgProjectTopics,
|
||||||
EuProjectStatusStatistics,
|
EuProjectStatusStatistics,
|
||||||
|
EuProjectTopics,
|
||||||
TopAuthor,
|
TopAuthor,
|
||||||
TopAuthorStatistics,
|
TopAuthorStatistics,
|
||||||
} from './dashboard-statistics.service';
|
} from './dashboard-statistics.service';
|
||||||
@@ -55,7 +64,11 @@ type DashboardPeriodMode =
|
|||||||
selector: 'dashboard',
|
selector: 'dashboard',
|
||||||
imports: [
|
imports: [
|
||||||
DecimalPipe,
|
DecimalPipe,
|
||||||
|
MatFormFieldModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
|
MatSelectModule,
|
||||||
|
MatTooltipModule,
|
||||||
|
ComponentTooltipDirective,
|
||||||
RouterLink,
|
RouterLink,
|
||||||
LoadingComponent,
|
LoadingComponent,
|
||||||
EuProjectStatusChartComponent,
|
EuProjectStatusChartComponent,
|
||||||
@@ -66,6 +79,8 @@ type DashboardPeriodMode =
|
|||||||
styleUrl: './dashboard.component.scss',
|
styleUrl: './dashboard.component.scss',
|
||||||
})
|
})
|
||||||
export class DashboardComponent implements OnInit {
|
export class DashboardComponent implements OnInit {
|
||||||
|
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
|
||||||
|
readonly patentIcon = PATENT_ICON;
|
||||||
statistics?: Partial<DashboardStatistics>;
|
statistics?: Partial<DashboardStatistics>;
|
||||||
statisticsLoading = false;
|
statisticsLoading = false;
|
||||||
statisticsError = false;
|
statisticsError = false;
|
||||||
@@ -96,6 +111,14 @@ export class DashboardComponent implements OnInit {
|
|||||||
dfgTopicTreemap?: TopicTreemapData;
|
dfgTopicTreemap?: TopicTreemapData;
|
||||||
dfgTopicsLoading = false;
|
dfgTopicsLoading = false;
|
||||||
dfgTopicsError = false;
|
dfgTopicsError = false;
|
||||||
|
euProjectTopics?: EuProjectTopics;
|
||||||
|
euTopicTreemap?: TopicTreemapData;
|
||||||
|
euTopicsLoading = false;
|
||||||
|
euTopicsError = false;
|
||||||
|
bundProjectTopics?: BundProjectTopics;
|
||||||
|
bundTopicTreemap?: TopicTreemapData;
|
||||||
|
bundTopicsLoading = false;
|
||||||
|
bundTopicsError = false;
|
||||||
euProjectStatuses?: EuProjectStatusStatistics;
|
euProjectStatuses?: EuProjectStatusStatistics;
|
||||||
euProjectStatusesLoading = false;
|
euProjectStatusesLoading = false;
|
||||||
euProjectStatusesError = false;
|
euProjectStatusesError = false;
|
||||||
@@ -108,12 +131,20 @@ export class DashboardComponent implements OnInit {
|
|||||||
readonly topicTreemapMinYear = 1900;
|
readonly topicTreemapMinYear = 1900;
|
||||||
readonly topicTreemapMaxYear = new Date().getFullYear();
|
readonly topicTreemapMaxYear = new Date().getFullYear();
|
||||||
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
|
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
|
||||||
dashboardFromYear = this.topicTreemapMaxYear - 4;
|
dashboardFromYear = this.topicTreemapMinYear;
|
||||||
dashboardToYear = this.topicTreemapMaxYear;
|
dashboardToYear = this.topicTreemapMaxYear;
|
||||||
|
dashboardInstitutions: DashboardInstitution[] = [];
|
||||||
|
selectedDashboardInstitutionId = 'all';
|
||||||
|
selectedAnalyticalInstitutionId = '';
|
||||||
|
dashboardInstitutionsLoading = false;
|
||||||
|
dashboardInstitutionsError = false;
|
||||||
selectedTopicTreemapNode?: string;
|
selectedTopicTreemapNode?: string;
|
||||||
selectedDfgTopicTreemapNode?: string;
|
selectedDfgTopicTreemapNode?: string;
|
||||||
|
selectedEuTopicTreemapNode?: string;
|
||||||
|
selectedBundTopicTreemapNode?: string;
|
||||||
private topicTreemapReloadQueued = false;
|
private topicTreemapReloadQueued = false;
|
||||||
private topicTreemapRequestId = 0;
|
private topicTreemapRequestId = 0;
|
||||||
|
private analyticalRequestId = 0;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private statisticsService: DashboardStatisticsService,
|
private statisticsService: DashboardStatisticsService,
|
||||||
@@ -124,41 +155,73 @@ export class DashboardComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.restoreDashboardPeriodState();
|
this.restoreDashboardPeriodState();
|
||||||
|
this.loadDashboardInstitutions();
|
||||||
this.loadStatistics();
|
this.loadStatistics();
|
||||||
this.loadTopAuthors();
|
}
|
||||||
this.loadTopicTreemap();
|
|
||||||
this.loadDfgProjectTopics();
|
private loadDashboardInstitutions(): void {
|
||||||
this.loadEuProjectStatuses();
|
this.dashboardInstitutionsLoading = true;
|
||||||
this.loadBmbfProjectStatuses();
|
this.dashboardInstitutionsError = false;
|
||||||
this.loadDfgProjectStatuses();
|
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 {
|
private loadStatistics(): void {
|
||||||
this.statisticsError = false;
|
this.statisticsError = false;
|
||||||
const period = this.selectedPeriodBounds();
|
const period = this.selectedPeriodBounds();
|
||||||
|
const institutionId = this.selectedDashboardInstitutionId;
|
||||||
this.loadStatistic(
|
this.loadStatistic(
|
||||||
'publications',
|
'publications',
|
||||||
this.statisticsService.getPublicationCount(period),
|
this.statisticsService.getPublicationCount(period, institutionId),
|
||||||
);
|
);
|
||||||
this.loadStatistic(
|
this.loadStatistic(
|
||||||
'persons',
|
'persons',
|
||||||
this.statisticsService.getPersonCount(period),
|
this.statisticsService.getPersonCount(period, institutionId),
|
||||||
);
|
);
|
||||||
this.loadStatistic(
|
this.loadStatistic(
|
||||||
'patents',
|
'patents',
|
||||||
this.statisticsService.getPatentCount(period),
|
this.statisticsService.getPatentCount(period, institutionId),
|
||||||
);
|
);
|
||||||
this.loadStatistic(
|
this.loadStatistic(
|
||||||
'eu_projects',
|
'eu_projects',
|
||||||
this.statisticsService.getEuProjectCount(period),
|
this.statisticsService.getEuProjectCount(period, institutionId),
|
||||||
);
|
);
|
||||||
this.loadStatistic(
|
this.loadStatistic(
|
||||||
'bmbf_projects',
|
'bmbf_projects',
|
||||||
this.statisticsService.getBmbfProjectCount(period),
|
this.statisticsService.getBmbfProjectCount(period, institutionId),
|
||||||
);
|
);
|
||||||
this.loadStatistic(
|
this.loadStatistic(
|
||||||
'dfg_projects',
|
'dfg_projects',
|
||||||
this.statisticsService.getDfgProjectCount(period),
|
this.statisticsService.getDfgProjectCount(period, institutionId),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,10 +308,12 @@ export class DashboardComponent implements OnInit {
|
|||||||
([subfieldName, group]) => ({
|
([subfieldName, group]) => ({
|
||||||
id: `${fieldName}::${subfieldName}`,
|
id: `${fieldName}::${subfieldName}`,
|
||||||
name: subfieldName,
|
name: subfieldName,
|
||||||
total: group.topics.reduce(
|
total:
|
||||||
(sum, topic) => sum + topic.project_count,
|
group.topics[0]?.subfield_project_count ??
|
||||||
0,
|
group.topics.reduce(
|
||||||
),
|
(sum, topic) => sum + topic.project_count,
|
||||||
|
0,
|
||||||
|
),
|
||||||
values: [],
|
values: [],
|
||||||
topics: group.topics.map((topic) => ({
|
topics: group.topics.map((topic) => ({
|
||||||
id: topic.id,
|
id: topic.id,
|
||||||
@@ -261,10 +326,12 @@ export class DashboardComponent implements OnInit {
|
|||||||
return {
|
return {
|
||||||
id: fieldName,
|
id: fieldName,
|
||||||
name: fieldName,
|
name: fieldName,
|
||||||
total: mappedSubfields.reduce(
|
total:
|
||||||
(sum, subfield) => sum + subfield.total,
|
[...subfields.values()][0]?.topics[0]?.field_project_count ??
|
||||||
0,
|
mappedSubfields.reduce(
|
||||||
),
|
(sum, subfield) => sum + subfield.total,
|
||||||
|
0,
|
||||||
|
),
|
||||||
values: [],
|
values: [],
|
||||||
subfields: mappedSubfields,
|
subfields: mappedSubfields,
|
||||||
};
|
};
|
||||||
@@ -314,11 +381,22 @@ export class DashboardComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
institutionRouteId(): string {
|
institutionRouteId(): string {
|
||||||
return (
|
const selectedInstitutionId = this.routeableInstitutionId(
|
||||||
this.statistics?.institution_id?.replace('https://openalex.org/', '') ??
|
this.selectedDashboardInstitutionId,
|
||||||
this.topAuthors?.institution_id?.replace('https://openalex.org/', '') ??
|
|
||||||
''
|
|
||||||
);
|
);
|
||||||
|
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 {
|
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 {
|
onTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||||
this.selectedTopicTreemapNode = nodeId;
|
this.selectedTopicTreemapNode = nodeId;
|
||||||
this.updateDashboardPeriodUrl();
|
this.updateDashboardPeriodUrl();
|
||||||
@@ -352,6 +465,7 @@ export class DashboardComponent implements OnInit {
|
|||||||
|
|
||||||
onDfgTopicTreemapNodeChange(nodeId: string | undefined): void {
|
onDfgTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||||
this.selectedDfgTopicTreemapNode = nodeId;
|
this.selectedDfgTopicTreemapNode = nodeId;
|
||||||
|
this.updateDashboardPeriodUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
onDfgTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
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 {
|
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
||||||
const period = this.selectedPeriodBounds();
|
const period = this.selectedPeriodBounds();
|
||||||
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
|
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
|
||||||
@@ -389,6 +561,7 @@ export class DashboardComponent implements OnInit {
|
|||||||
...topic,
|
...topic,
|
||||||
fromYear: period.fromYear,
|
fromYear: period.fromYear,
|
||||||
toYear: period.toYear,
|
toYear: period.toYear,
|
||||||
|
institutionId: this.selectedAnalyticalInstitutionId,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -406,23 +579,34 @@ export class DashboardComponent implements OnInit {
|
|||||||
this.dashboardPeriodMode = mode;
|
this.dashboardPeriodMode = mode;
|
||||||
}
|
}
|
||||||
this.applyPresetPeriod();
|
this.applyPresetPeriod();
|
||||||
this.dashboardFromYear = this.parseDashboardYear(
|
if (this.dashboardPeriodMode !== 'all_time') {
|
||||||
params.get('fromYear'),
|
this.dashboardFromYear = this.parseDashboardYear(
|
||||||
this.dashboardFromYear,
|
params.get('fromYear'),
|
||||||
);
|
this.dashboardFromYear,
|
||||||
this.dashboardToYear = this.parseDashboardYear(
|
);
|
||||||
params.get('toYear'),
|
this.dashboardToYear = this.parseDashboardYear(
|
||||||
this.dashboardToYear,
|
params.get('toYear'),
|
||||||
);
|
this.dashboardToYear,
|
||||||
|
);
|
||||||
|
}
|
||||||
if (this.dashboardFromYear > this.dashboardToYear) {
|
if (this.dashboardFromYear > this.dashboardToYear) {
|
||||||
this.dashboardFromYear = this.dashboardToYear;
|
this.dashboardFromYear = this.dashboardToYear;
|
||||||
}
|
}
|
||||||
this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined;
|
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 {
|
private applyPresetPeriod(): void {
|
||||||
const currentYear = this.topicTreemapMaxYear;
|
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.dashboardFromYear = currentYear - 9;
|
||||||
this.dashboardToYear = currentYear;
|
this.dashboardToYear = currentYear;
|
||||||
} else if (this.dashboardPeriodMode === 'last_5_years') {
|
} else if (this.dashboardPeriodMode === 'last_5_years') {
|
||||||
@@ -440,6 +624,11 @@ export class DashboardComponent implements OnInit {
|
|||||||
fromYear: period.fromYear ?? null,
|
fromYear: period.fromYear ?? null,
|
||||||
toYear: period.toYear ?? null,
|
toYear: period.toYear ?? null,
|
||||||
treemapNode: this.selectedTopicTreemapNode ?? 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',
|
queryParamsHandling: 'merge',
|
||||||
replaceUrl: true,
|
replaceUrl: true,
|
||||||
@@ -466,12 +655,23 @@ export class DashboardComponent implements OnInit {
|
|||||||
|
|
||||||
private reloadPeriodData(): void {
|
private reloadPeriodData(): void {
|
||||||
this.loadStatistics();
|
this.loadStatistics();
|
||||||
this.loadTopAuthors();
|
this.reloadAnalyticalData();
|
||||||
this.loadTopicTreemap();
|
}
|
||||||
this.loadDfgProjectTopics();
|
|
||||||
this.loadEuProjectStatuses();
|
private reloadAnalyticalData(): void {
|
||||||
this.loadBmbfProjectStatuses();
|
if (!this.selectedAnalyticalInstitutionId) return;
|
||||||
this.loadDfgProjectStatuses();
|
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(
|
private loadStatistic(
|
||||||
@@ -519,115 +719,269 @@ export class DashboardComponent implements OnInit {
|
|||||||
this.statistics = nextStatistics;
|
this.statistics = nextStatistics;
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadTopAuthors(): void {
|
private loadTopAuthors(requestId = this.analyticalRequestId): void {
|
||||||
this.topAuthorsLoading = true;
|
this.topAuthorsLoading = true;
|
||||||
this.topAuthorsError = false;
|
this.topAuthorsError = false;
|
||||||
this.statisticsService
|
this.statisticsService
|
||||||
.getTopAuthors(this.selectedPeriodBounds())
|
.getTopAuthors(
|
||||||
.pipe(finalize(() => (this.topAuthorsLoading = false)))
|
this.selectedPeriodBounds(),
|
||||||
|
this.selectedAnalyticalInstitutionId,
|
||||||
|
)
|
||||||
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.topAuthorsLoading = false;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (statistics) => {
|
next: (statistics) => {
|
||||||
this.topAuthors = statistics;
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.topAuthors = statistics;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
error: () => {
|
||||||
this.topAuthorsError = true;
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.topAuthorsError = true;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadDfgProjectTopics(): void {
|
private loadDfgProjectTopics(requestId = this.analyticalRequestId): void {
|
||||||
this.dfgTopicsLoading = true;
|
this.dfgTopicsLoading = true;
|
||||||
this.dfgTopicsError = false;
|
this.dfgTopicsError = false;
|
||||||
this.statisticsService
|
this.statisticsService
|
||||||
.getDfgProjectTopics(this.selectedPeriodBounds())
|
.getDfgProjectTopics(
|
||||||
.pipe(finalize(() => (this.dfgTopicsLoading = false)))
|
this.selectedPeriodBounds(),
|
||||||
|
this.selectedAnalyticalInstitutionId,
|
||||||
|
)
|
||||||
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.dfgTopicsLoading = false;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (topics) => {
|
next: (topics) => {
|
||||||
this.dfgProjectTopics = topics;
|
if (requestId === this.analyticalRequestId) {
|
||||||
this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics);
|
this.dfgProjectTopics = topics;
|
||||||
|
this.dfgTopicTreemap = this.buildDfgTopicTreemapData(topics);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
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.euProjectStatusesLoading = true;
|
||||||
this.euProjectStatusesError = false;
|
this.euProjectStatusesError = false;
|
||||||
this.statisticsService
|
this.statisticsService
|
||||||
.getEuProjectStatuses(this.selectedPeriodBounds())
|
.getEuProjectStatuses(
|
||||||
.pipe(finalize(() => (this.euProjectStatusesLoading = false)))
|
this.selectedPeriodBounds(),
|
||||||
|
this.selectedAnalyticalInstitutionId,
|
||||||
|
)
|
||||||
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.euProjectStatusesLoading = false;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (statuses) => {
|
next: (statuses) => {
|
||||||
this.euProjectStatuses = statuses;
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.euProjectStatuses = statuses;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
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.bmbfProjectStatusesLoading = true;
|
||||||
this.bmbfProjectStatusesError = false;
|
this.bmbfProjectStatusesError = false;
|
||||||
this.statisticsService
|
this.statisticsService
|
||||||
.getBmbfProjectStatuses(this.selectedPeriodBounds())
|
.getBmbfProjectStatuses(
|
||||||
.pipe(finalize(() => (this.bmbfProjectStatusesLoading = false)))
|
this.selectedPeriodBounds(),
|
||||||
|
this.selectedAnalyticalInstitutionId,
|
||||||
|
)
|
||||||
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.bmbfProjectStatusesLoading = false;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (statuses) => {
|
next: (statuses) => {
|
||||||
this.bmbfProjectStatuses = statuses;
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.bmbfProjectStatuses = statuses;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
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.dfgProjectStatusesLoading = true;
|
||||||
this.dfgProjectStatusesError = false;
|
this.dfgProjectStatusesError = false;
|
||||||
this.statisticsService
|
this.statisticsService
|
||||||
.getDfgProjectStatuses(this.selectedPeriodBounds())
|
.getDfgProjectStatuses(
|
||||||
.pipe(finalize(() => (this.dfgProjectStatusesLoading = false)))
|
this.selectedPeriodBounds(),
|
||||||
|
this.selectedAnalyticalInstitutionId,
|
||||||
|
)
|
||||||
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.dfgProjectStatusesLoading = false;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (statuses) => {
|
next: (statuses) => {
|
||||||
this.dfgProjectStatuses = statuses;
|
if (requestId === this.analyticalRequestId) {
|
||||||
|
this.dfgProjectStatuses = statuses;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
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) {
|
if (this.dashboardFromYear > this.dashboardToYear) {
|
||||||
this.topicTreemapLoading = false;
|
this.topicTreemapLoading = false;
|
||||||
this.topicTreemapError = true;
|
this.topicTreemapError = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const requestId = ++this.topicTreemapRequestId;
|
const treemapRequestId = ++this.topicTreemapRequestId;
|
||||||
const period = this.selectedPeriodBounds();
|
const period = this.selectedPeriodBounds();
|
||||||
this.topicTreemapLoading = true;
|
this.topicTreemapLoading = true;
|
||||||
this.topicTreemapError = false;
|
this.topicTreemapError = false;
|
||||||
this.statisticsService
|
this.statisticsService
|
||||||
.getTopicTreemap(period.fromYear, period.toYear)
|
.getTopicTreemap(
|
||||||
|
period.fromYear,
|
||||||
|
period.toYear,
|
||||||
|
this.selectedAnalyticalInstitutionId,
|
||||||
|
)
|
||||||
.pipe(
|
.pipe(
|
||||||
finalize(() => {
|
finalize(() => {
|
||||||
if (requestId === this.topicTreemapRequestId) {
|
if (
|
||||||
|
analyticalRequestId === this.analyticalRequestId &&
|
||||||
|
treemapRequestId === this.topicTreemapRequestId
|
||||||
|
) {
|
||||||
this.topicTreemapLoading = false;
|
this.topicTreemapLoading = false;
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (treemap) => {
|
next: (treemap) => {
|
||||||
if (requestId === this.topicTreemapRequestId) {
|
if (
|
||||||
|
analyticalRequestId === this.analyticalRequestId &&
|
||||||
|
treemapRequestId === this.topicTreemapRequestId
|
||||||
|
) {
|
||||||
this.topicTreemap = treemap;
|
this.topicTreemap = treemap;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
error: () => {
|
||||||
if (requestId === this.topicTreemapRequestId) {
|
if (
|
||||||
|
analyticalRequestId === this.analyticalRequestId &&
|
||||||
|
treemapRequestId === this.topicTreemapRequestId
|
||||||
|
) {
|
||||||
this.topicTreemapError = true;
|
this.topicTreemapError = true;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+3
-1
@@ -22,8 +22,9 @@ export interface TopicWordCloudDialogData {
|
|||||||
subfieldName?: string;
|
subfieldName?: string;
|
||||||
fromYear?: number;
|
fromYear?: number;
|
||||||
toYear?: number;
|
toYear?: number;
|
||||||
|
institutionId?: string;
|
||||||
words?: TopicWordCloudWord[];
|
words?: TopicWordCloudWord[];
|
||||||
source?: 'publications' | 'dfg';
|
source?: 'publications' | 'dfg' | 'eu' | 'bund';
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DisplayWord extends TopicWordCloudWord {
|
interface DisplayWord extends TopicWordCloudWord {
|
||||||
@@ -82,6 +83,7 @@ export class TopicWordCloudDialogComponent {
|
|||||||
this.data.topicId,
|
this.data.topicId,
|
||||||
this.data.fromYear,
|
this.data.fromYear,
|
||||||
this.data.toYear,
|
this.data.toYear,
|
||||||
|
this.data.institutionId,
|
||||||
)
|
)
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
<p>institution-overview works!</p>
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
|
||||||
|
|
||||||
import { InstitutionOverviewComponent } from './institution-overview.component';
|
|
||||||
|
|
||||||
describe('InstitutionOverviewComponent', () => {
|
|
||||||
let component: InstitutionOverviewComponent;
|
|
||||||
let fixture: ComponentFixture<InstitutionOverviewComponent>;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [InstitutionOverviewComponent],
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(InstitutionOverviewComponent);
|
|
||||||
component = fixture.componentInstance;
|
|
||||||
fixture.detectChanges();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should create', () => {
|
|
||||||
expect(component).toBeTruthy();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { Component } from '@angular/core';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-institution-overview',
|
|
||||||
imports: [],
|
|
||||||
templateUrl: './institution-overview.component.html',
|
|
||||||
styleUrl: './institution-overview.component.scss',
|
|
||||||
})
|
|
||||||
export class InstitutionOverviewComponent {}
|
|
||||||
@@ -54,11 +54,13 @@
|
|||||||
subscriptSizing="dynamic">
|
subscriptSizing="dynamic">
|
||||||
<mat-icon matPrefix fontIcon="sort"></mat-icon>
|
<mat-icon matPrefix fontIcon="sort"></mat-icon>
|
||||||
<mat-select
|
<mat-select
|
||||||
[value]="sortMode"
|
[value]="sortColumn"
|
||||||
(selectionChange)="setSortMode($event.value)">
|
(selectionChange)="setSort($event.value)">
|
||||||
<mat-select-trigger>Sortieren nach</mat-select-trigger>
|
<mat-select-trigger>Sortieren nach</mat-select-trigger>
|
||||||
<mat-option value="date">Datum</mat-option>
|
<mat-option value="year">Jahr</mat-option>
|
||||||
<mat-option value="title">Titel</mat-option>
|
<mat-option value="title">Titel</mat-option>
|
||||||
|
<mat-option value="source">Quelle</mat-option>
|
||||||
|
<mat-option value="matchType">Match-Typ</mat-option>
|
||||||
</mat-select>
|
</mat-select>
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
</div>
|
</div>
|
||||||
@@ -67,11 +69,41 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Patent</th>
|
<th>Patent</th>
|
||||||
<th>Quelle</th>
|
<th
|
||||||
<th>Jahr</th>
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn === 'source'"
|
||||||
|
(click)="setSort('source')">
|
||||||
|
Quelle
|
||||||
|
@if (sortColumn === 'source') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
|
<th
|
||||||
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn === 'year'"
|
||||||
|
(click)="setSort('year')">
|
||||||
|
Jahr
|
||||||
|
@if (sortColumn === 'year') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
<th>Erfinder</th>
|
<th>Erfinder</th>
|
||||||
<th>Applicant/Assignee</th>
|
<th>Applicant/Assignee</th>
|
||||||
<th>Match-Typ</th>
|
<th
|
||||||
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn === 'matchType'"
|
||||||
|
(click)="setSort('matchType')">
|
||||||
|
Match-Typ
|
||||||
|
@if (sortColumn === 'matchType') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
<th>Personen</th>
|
<th>Personen</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -94,33 +126,119 @@
|
|||||||
{{ patent.source }}
|
{{ patent.source }}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ patent.publication_year ?? '-' }}</td>
|
<td>
|
||||||
<td class="cell-preview">{{ getInventorsPreview(patent) }}</td>
|
@if (patent.publication_year) {
|
||||||
<td class="cell-preview">{{ getAssigneesPreview(patent) }}</td>
|
<span class="year-badge">{{
|
||||||
|
patent.publication_year
|
||||||
|
}}</span>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="patent-people">
|
||||||
|
@if (patent.inventors && patent.inventors.length) {
|
||||||
|
<div class="person-chips">
|
||||||
|
@for (
|
||||||
|
inventor of patent.inventors.slice(0, 2);
|
||||||
|
track inventor
|
||||||
|
) {
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>person</mat-icon>
|
||||||
|
{{ inventor }}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
@if (patent.inventors.length > 2) {
|
||||||
|
<span class="person-chip-row">
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>person</mat-icon>
|
||||||
|
{{ patent.inventors[2] }}
|
||||||
|
</span>
|
||||||
|
@if (patent.inventors.length > 3) {
|
||||||
|
<span class="person-chip person-chip--more"
|
||||||
|
>+{{ patent.inventors.length - 3 }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="patent-people">
|
||||||
|
@if (patent.assignees && patent.assignees.length) {
|
||||||
|
<div class="person-chips">
|
||||||
|
@for (
|
||||||
|
assignee of patent.assignees.slice(0, 2);
|
||||||
|
track assignee
|
||||||
|
) {
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>{{
|
||||||
|
isAssigneeLikelyPerson(assignee, patent)
|
||||||
|
? 'person'
|
||||||
|
: 'apartment'
|
||||||
|
}}</mat-icon>
|
||||||
|
{{ assignee }}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
@if (patent.assignees.length > 2) {
|
||||||
|
<span class="person-chip-row">
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>{{
|
||||||
|
isAssigneeLikelyPerson(
|
||||||
|
patent.assignees[2],
|
||||||
|
patent
|
||||||
|
)
|
||||||
|
? 'person'
|
||||||
|
: 'apartment'
|
||||||
|
}}</mat-icon>
|
||||||
|
{{ patent.assignees[2] }}
|
||||||
|
</span>
|
||||||
|
@if (patent.assignees.length > 3) {
|
||||||
|
<span class="person-chip person-chip--more"
|
||||||
|
>+{{ patent.assignees.length - 3 }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<span
|
<span
|
||||||
class="match-badge match-badge--{{ patent.match_type }}">
|
class="match-badge match-badge--{{ patent.match_type }}">
|
||||||
{{ getMatchTypeLabel(patent) }}
|
{{ getMatchTypeLabel(patent) }}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td class="cell-authors">
|
<td>
|
||||||
@if (
|
<div class="cell-authors">
|
||||||
patent.matched_authors && patent.matched_authors.length
|
@if (
|
||||||
) {
|
patent.matched_authors && patent.matched_authors.length
|
||||||
@for (
|
|
||||||
author of patent.matched_authors.slice(0, 2);
|
|
||||||
track author.openalex_author_id
|
|
||||||
) {
|
) {
|
||||||
<a
|
@for (
|
||||||
class="author-link"
|
author of patent.matched_authors.slice(0, 2);
|
||||||
[routerLink]="['/person', author.openalex_author_id]"
|
track author.openalex_author_id
|
||||||
(click)="$event.stopPropagation()">
|
) {
|
||||||
{{ author.author_name }}
|
<a
|
||||||
</a>
|
class="author-link"
|
||||||
|
[routerLink]="[
|
||||||
|
'/person',
|
||||||
|
author.openalex_author_id,
|
||||||
|
]"
|
||||||
|
[appComponentTooltip]="AuthorTooltipComponent"
|
||||||
|
[tooltipInputs]="{
|
||||||
|
authorId: author.openalex_author_id,
|
||||||
|
}"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
{{ author.author_name }}
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
}
|
}
|
||||||
} @else {
|
</div>
|
||||||
<span>-</span>
|
|
||||||
}
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
@@ -192,7 +310,11 @@
|
|||||||
<li>
|
<li>
|
||||||
<a
|
<a
|
||||||
class="tag author-link"
|
class="tag author-link"
|
||||||
[routerLink]="['/person', author.openalex_author_id]">
|
[routerLink]="['/person', author.openalex_author_id]"
|
||||||
|
[appComponentTooltip]="AuthorTooltipComponent"
|
||||||
|
[tooltipInputs]="{
|
||||||
|
authorId: author.openalex_author_id,
|
||||||
|
}">
|
||||||
{{ author.author_name }}
|
{{ author.author_name }}
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -60,22 +60,30 @@ app-query-param-paginator {
|
|||||||
|
|
||||||
table {
|
table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-collapse: separate;
|
border-collapse: collapse;
|
||||||
border-spacing: 0;
|
|
||||||
border: 1px solid var(--sg-border);
|
|
||||||
border-radius: var(--sg-radius-sm);
|
|
||||||
overflow: hidden;
|
|
||||||
|
|
||||||
th {
|
th {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
padding: 12px 16px;
|
padding: 12px 16px;
|
||||||
background: var(--sg-surface-muted);
|
|
||||||
border-bottom: 1px solid var(--sg-border);
|
border-bottom: 1px solid var(--sg-border);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
color: var(--sg-text-muted);
|
color: var(--sg-text-muted);
|
||||||
|
|
||||||
|
&.sortable {
|
||||||
|
display: table-cell;
|
||||||
|
cursor: pointer;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sort-icon {
|
||||||
|
vertical-align: middle;
|
||||||
|
margin-left: 2px;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tr {
|
tr {
|
||||||
@@ -90,10 +98,6 @@ app-query-param-paginator {
|
|||||||
&.selected td {
|
&.selected td {
|
||||||
background: var(--sg-primary-soft);
|
background: var(--sg-primary-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
&:last-child td {
|
|
||||||
border-bottom: 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
td {
|
td {
|
||||||
@@ -107,19 +111,13 @@ app-query-param-paginator {
|
|||||||
.patent-title {
|
.patent-title {
|
||||||
color: var(--sg-text);
|
color: var(--sg-text);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
max-width: 280px;
|
max-width: 320px;
|
||||||
white-space: nowrap;
|
white-space: normal;
|
||||||
overflow: hidden;
|
word-break: break-word;
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.cell-preview {
|
.patent-people {
|
||||||
max-width: 160px;
|
max-width: 220px;
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.cell-authors {
|
.cell-authors {
|
||||||
@@ -131,6 +129,64 @@ app-query-param-paginator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.year-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 26px;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chip-row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
border-radius: var(--sg-radius-sm);
|
||||||
|
background: var(--sg-surface-soft);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--sg-text-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
&--more {
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.match-badge {
|
.match-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -13,8 +13,11 @@ import {
|
|||||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
import { PageEvent } from '@angular/material/paginator';
|
import { PageEvent } from '@angular/material/paginator';
|
||||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||||
|
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
|
||||||
|
import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component';
|
||||||
|
|
||||||
type SortMode = 'date' | 'title';
|
type SortColumn = 'title' | 'year' | 'source' | 'matchType';
|
||||||
|
type SortDirection = 'asc' | 'desc';
|
||||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||||
type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
|
type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
|
||||||
|
|
||||||
@@ -28,11 +31,13 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
|
|||||||
MatSelectModule,
|
MatSelectModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
QueryParamPaginatorComponent,
|
QueryParamPaginatorComponent,
|
||||||
|
ComponentTooltipDirective,
|
||||||
],
|
],
|
||||||
templateUrl: './institution-patents.component.html',
|
templateUrl: './institution-patents.component.html',
|
||||||
styleUrl: './institution-patents.component.scss',
|
styleUrl: './institution-patents.component.scss',
|
||||||
})
|
})
|
||||||
export class InstitutionPatentsComponent implements OnInit {
|
export class InstitutionPatentsComponent implements OnInit {
|
||||||
|
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
|
||||||
private route = inject(ActivatedRoute);
|
private route = inject(ActivatedRoute);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private patentsApi = inject(PatentsService);
|
private patentsApi = inject(PatentsService);
|
||||||
@@ -48,7 +53,8 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
|
|
||||||
activeFilter: SourceFilter = 'all';
|
activeFilter: SourceFilter = 'all';
|
||||||
activeMatchType: OrgPatentMatchTypeFilter = 'all';
|
activeMatchType: OrgPatentMatchTypeFilter = 'all';
|
||||||
sortMode: SortMode = 'date';
|
sortColumn: SortColumn = 'year';
|
||||||
|
sortDirection: SortDirection = 'desc';
|
||||||
|
|
||||||
pageIndex = 0;
|
pageIndex = 0;
|
||||||
pageSize = 20;
|
pageSize = 20;
|
||||||
@@ -59,7 +65,8 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
const institutionId = params.get('institutionId') ?? '';
|
const institutionId = params.get('institutionId') ?? '';
|
||||||
|
|
||||||
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
|
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
|
||||||
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
|
const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
|
||||||
|
const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir');
|
||||||
const matchTypeFromUrl =
|
const matchTypeFromUrl =
|
||||||
this.route.snapshot.queryParamMap.get('matchType');
|
this.route.snapshot.queryParamMap.get('matchType');
|
||||||
this.pageIndex = this.parsePageIndexParam(
|
this.pageIndex = this.parsePageIndexParam(
|
||||||
@@ -72,8 +79,11 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
if (this.isValidFilter(filterFromUrl)) {
|
if (this.isValidFilter(filterFromUrl)) {
|
||||||
this.activeFilter = filterFromUrl;
|
this.activeFilter = filterFromUrl;
|
||||||
}
|
}
|
||||||
if (this.isValidSortMode(sortFromUrl)) {
|
if (this.isValidSortColumn(sortByFromUrl)) {
|
||||||
this.sortMode = sortFromUrl;
|
this.sortColumn = sortByFromUrl;
|
||||||
|
}
|
||||||
|
if (this.isValidSortDirection(sortDirFromUrl)) {
|
||||||
|
this.sortDirection = sortDirFromUrl;
|
||||||
}
|
}
|
||||||
if (this.isValidMatchType(matchTypeFromUrl)) {
|
if (this.isValidMatchType(matchTypeFromUrl)) {
|
||||||
this.activeMatchType = matchTypeFromUrl;
|
this.activeMatchType = matchTypeFromUrl;
|
||||||
@@ -101,8 +111,13 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
this.reloadPatents();
|
this.reloadPatents();
|
||||||
}
|
}
|
||||||
|
|
||||||
setSortMode(sortMode: SortMode): void {
|
setSort(column: SortColumn): void {
|
||||||
this.sortMode = sortMode;
|
if (this.sortColumn === column) {
|
||||||
|
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
|
||||||
|
} else {
|
||||||
|
this.sortColumn = column;
|
||||||
|
this.sortDirection = column === 'year' ? 'desc' : 'asc';
|
||||||
|
}
|
||||||
this.filteredPatents = this.sortPatents(this.patents);
|
this.filteredPatents = this.sortPatents(this.patents);
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
@@ -168,14 +183,27 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
|
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
|
||||||
if (this.sortMode === 'title') {
|
const direction = this.sortDirection === 'asc' ? 1 : -1;
|
||||||
return [...patents].sort((a, b) =>
|
return [...patents].sort((a, b) => {
|
||||||
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
|
switch (this.sortColumn) {
|
||||||
sensitivity: 'base',
|
case 'year': {
|
||||||
}),
|
const yearA = a.publication_date ?? String(a.publication_year ?? '');
|
||||||
);
|
const yearB = b.publication_date ?? String(b.publication_year ?? '');
|
||||||
}
|
return direction * yearA.localeCompare(yearB);
|
||||||
return [...patents];
|
}
|
||||||
|
case 'source':
|
||||||
|
return direction * a.source.localeCompare(b.source);
|
||||||
|
case 'matchType':
|
||||||
|
return direction * a.match_type.localeCompare(b.match_type);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
direction *
|
||||||
|
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
|
||||||
|
sensitivity: 'base',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateQueryParams(): void {
|
private updateQueryParams(): void {
|
||||||
@@ -183,7 +211,8 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
relativeTo: this.route,
|
relativeTo: this.route,
|
||||||
queryParams: {
|
queryParams: {
|
||||||
filter: this.activeFilter,
|
filter: this.activeFilter,
|
||||||
sortBy: this.sortMode,
|
sortBy: this.sortColumn,
|
||||||
|
sortDir: this.sortDirection,
|
||||||
matchType: this.activeMatchType,
|
matchType: this.activeMatchType,
|
||||||
page: this.pageIndex,
|
page: this.pageIndex,
|
||||||
size: this.pageSize,
|
size: this.pageSize,
|
||||||
@@ -207,8 +236,17 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
return value === 'all' || value === 'EPO' || value === 'USPTO';
|
return value === 'all' || value === 'EPO' || value === 'USPTO';
|
||||||
}
|
}
|
||||||
|
|
||||||
private isValidSortMode(value: string | null): value is SortMode {
|
private isValidSortColumn(value: string | null): value is SortColumn {
|
||||||
return value === 'date' || value === 'title';
|
return (
|
||||||
|
value === 'title' ||
|
||||||
|
value === 'year' ||
|
||||||
|
value === 'source' ||
|
||||||
|
value === 'matchType'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isValidSortDirection(value: string | null): value is SortDirection {
|
||||||
|
return value === 'asc' || value === 'desc';
|
||||||
}
|
}
|
||||||
|
|
||||||
private isValidMatchType(
|
private isValidMatchType(
|
||||||
@@ -287,18 +325,40 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getInventorsPreview(patent: OrgPatentEntry): string {
|
private static readonly ORG_SUFFIX_PATTERN =
|
||||||
if (!patent.inventors?.length) {
|
/\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i;
|
||||||
return '-';
|
private static readonly PERSON_SUFFIX_PATTERN =
|
||||||
}
|
/\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i;
|
||||||
return patent.inventors.slice(0, 2).join(', ');
|
|
||||||
|
private normalizeNameForComparison(name: string): string {
|
||||||
|
return name
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[̀-ͯ]/g, '')
|
||||||
|
.replace(/[.,]/g, '')
|
||||||
|
.toUpperCase()
|
||||||
|
.split(/\s+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.sort()
|
||||||
|
.join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
getAssigneesPreview(patent: OrgPatentEntry): string {
|
isAssigneeLikelyPerson(assignee: string, patent: OrgPatentEntry): boolean {
|
||||||
if (!patent.assignees?.length) {
|
if (InstitutionPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) {
|
||||||
return '-';
|
return false;
|
||||||
}
|
}
|
||||||
return patent.assignees.slice(0, 2).join(', ');
|
|
||||||
|
const normalizedAssignee = this.normalizeNameForComparison(
|
||||||
|
assignee.replace(InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN, ''),
|
||||||
|
);
|
||||||
|
const matchesInventor = (patent.inventors ?? []).some(
|
||||||
|
(inventor) =>
|
||||||
|
this.normalizeNameForComparison(inventor) === normalizedAssignee,
|
||||||
|
);
|
||||||
|
if (matchesInventor) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee);
|
||||||
}
|
}
|
||||||
|
|
||||||
getMatchedAuthorsPreview(patent: OrgPatentEntry): string {
|
getMatchedAuthorsPreview(patent: OrgPatentEntry): string {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user