Compare commits

...
Author SHA1 Message Date
spsaefan 1e8e82f1d9 Support multiple roles in account UI
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-13 11:03:57 +02:00
spsaefan 13507c2ae8 Support multiple roles in account services 2026-07-13 11:03:57 +02:00
spsaefan 1c535a872f Add multi-role account 2026-07-13 11:03:57 +02:00
Mats Paul Tončik baf5b17239 Merge remote-tracking branch 'origin/dev' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 23:47:09 +02:00
Mats Paul Tončik fa5e42a5eb fix(person/publications): made URL stateful and moved retrieval logic to resolvers 2026-07-12 23:39:25 +02:00
farajollahi 304ce0f1ab Merge pull request 'remove dfg projects analyse' (#211) from dfg-projects-analyse into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #211
2026-07-12 21:04:45 +02:00
38 changed files with 1430 additions and 606 deletions
@@ -1,9 +1,9 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, model_validator
from inse.auth.model import UserRole
from inse.auth.model import UserRole, normalize_roles
class OrganizationProfile(BaseModel):
@@ -16,7 +16,7 @@ class AccountProfile(BaseModel):
id: uuid.UUID
email: str
name: str
role: UserRole
roles: List[UserRole]
organization_id: uuid.UUID
organization_name: str
deleted: bool
@@ -34,20 +34,45 @@ class AccountPage(BaseModel):
class CreateAccountRequest(BaseModel):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
email: str = Field(min_length=3)
name: str = Field(min_length=1)
role: UserRole = UserRole.USER
roles: List[UserRole] = Field(default_factory=lambda: [UserRole.USER])
organization_id: uuid.UUID
password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None
@model_validator(mode="after")
def _normalize_roles(self):
self.roles = normalize_roles(self.roles)
return self
class UpdateAccountRequest(BaseModel):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
email: Optional[str] = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1)
role: Optional[UserRole] = None
roles: Optional[List[UserRole]] = None
organization_id: Optional[uuid.UUID] = None
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
activated: Optional[bool] = None
@model_validator(mode="after")
def _normalize_roles(self):
if self.roles is not None:
self.roles = normalize_roles(self.roles)
return self
@@ -5,7 +5,13 @@ from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
from inse.auth.model import (
AccessTokenMetadata,
Account,
Organization,
UserRole,
normalize_roles,
)
from .model import (
AccountPage,
@@ -28,13 +34,17 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
return False
def _roles_allowed_for_editor(editor_role: UserRole, roles: list[UserRole]) -> bool:
return all(_role_allowed_for_editor(editor_role, role) for role in roles)
def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
organization_name = account.organization.name if account.organization else ""
return AccountProfile(
id=account.id,
email=account.email,
name=account.name,
role=account.role,
roles=normalize_roles(account.roles),
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
@@ -175,7 +185,7 @@ def create_account(
detail="Admins can only create accounts in their own organization.",
)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
@@ -194,7 +204,7 @@ def create_account(
account = Account(
email=email,
name=payload.name.strip(),
role=payload.role,
roles=payload.roles,
organization_id=payload.organization_id,
password_hash=auth_service._hash_password(payload.password),
openalex_person_id=payload.openalex_person_id,
@@ -261,15 +271,15 @@ def update_account(
if payload.openalex_person_id is not None:
account.openalex_person_id = payload.openalex_person_id
if payload.role is not None:
if payload.roles is not None:
if not can_admin_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
account.role = payload.role
account.roles = payload.roles
account.epoch += 1
if payload.organization_id is not None:
+80 -7
View File
@@ -3,8 +3,8 @@ from datetime import datetime
from enum import StrEnum
from typing import List
from pydantic import BaseModel
from sqlalchemy import UniqueConstraint
from pydantic import BaseModel, model_validator
from sqlalchemy import JSON, Column, UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
@@ -15,6 +15,35 @@ class UserRole(StrEnum):
USER = "USER"
ROLE_PRIORITY = {
UserRole.SUPER_ADMIN: 0,
UserRole.ADMIN: 1,
UserRole.MANAGER: 2,
UserRole.USER: 3,
}
def normalize_roles(roles: List[UserRole] | List[str] | UserRole | str | None) -> List[UserRole]:
if roles is None:
return [UserRole.USER]
if isinstance(roles, (str, UserRole)):
roles = [roles]
normalized = []
seen = set()
for role in roles:
user_role = role if isinstance(role, UserRole) else UserRole(role)
if user_role not in seen:
normalized.append(user_role)
seen.add(user_role)
return sorted(normalized or [UserRole.USER], key=lambda role: ROLE_PRIORITY[role])
def effective_role_for_roles(roles: List[UserRole] | List[str] | UserRole | str | None) -> UserRole:
return normalize_roles(roles)[0]
class TokenType(StrEnum):
ID_TOKEN = "ID_TOKEN"
REFRESH_TOKEN = "REFRESH_TOKEN"
@@ -57,6 +86,13 @@ class Organization(Durable, table=True):
class Account(Durable, table=True):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
@@ -101,15 +137,22 @@ class Account(Durable, table=True):
nullable=False,
description="The unique identifier of the organization strictly associated with this account.",
)
role: UserRole = Field(
default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this account holds within its organization.",
roles: List[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
description="The roles this account holds within its organization.",
)
organization: Organization = Relationship(back_populates="accounts")
@property
def role(self) -> UserRole:
return effective_role_for_roles(self.roles)
@role.setter
def role(self, value: UserRole) -> None:
self.roles = normalize_roles(value)
class Secret(SQLModel, table=True):
__table_args__ = (
@@ -176,6 +219,17 @@ class IdTokenMetadata(BaseTokenData):
class AccessTokenMetadata(BaseTokenData):
@model_validator(mode="before")
@classmethod
def _effective_role_to_roles(cls, values):
if (
isinstance(values, dict)
and "effective_roles" not in values
and "effective_role" in values
):
values = {**values, "effective_roles": [values["effective_role"]]}
return values
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
@@ -191,6 +245,10 @@ class AccessTokenMetadata(BaseTokenData):
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: List[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
@@ -211,6 +269,17 @@ class AccessToken(AccessTokenMetadata):
class RefreshTokenMetadata(BaseTokenData):
@model_validator(mode="before")
@classmethod
def _effective_role_to_roles(cls, values):
if (
isinstance(values, dict)
and "effective_roles" not in values
and "effective_role" in values
):
values = {**values, "effective_roles": [values["effective_role"]]}
return values
token_type: TokenType = Field(
default=TokenType.REFRESH_TOKEN,
const=True,
@@ -223,6 +292,10 @@ class RefreshTokenMetadata(BaseTokenData):
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: List[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
+36 -8
View File
@@ -28,6 +28,8 @@ from inse.auth.model import (
SecretPurpose,
TokenType,
UserRole,
effective_role_for_roles,
normalize_roles,
)
from inse.config import get_settings
from inse.database import get_session
@@ -44,6 +46,7 @@ PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
REAL_ACCOUNT_ID_KEY = "real_account_id"
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
EFFECTIVE_ROLE_KEY = "effective_role"
EFFECTIVE_ROLES_KEY = "effective_roles"
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EPOCH_KEY = "epoch"
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
@@ -110,14 +113,14 @@ def create_predefined_accounts(session: Session, file_path: str):
session.add(organization)
for account_data in data.get("accounts", []):
organization_id = uuid.UUID(account_data["organization_id"])
role = UserRole(account_data["role"])
roles = normalize_roles(account_data.get("roles", account_data.get("role")))
email = account_data["email"]
password_hash = _hash_password(account_data["password"])
account = Account(
email=email,
name=account_data["name"],
organization_id=organization_id,
role=role,
roles=roles,
password_hash=password_hash,
epoch=0,
)
@@ -609,6 +612,11 @@ def _get_current_user_access_token_payload(
),
epoch=access_token_payload[EPOCH_KEY],
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
effective_roles=normalize_roles(
access_token_payload.get(
EFFECTIVE_ROLES_KEY, access_token_payload[EFFECTIVE_ROLE_KEY]
)
),
effective_organization_id=uuid.UUID(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
@@ -649,6 +657,11 @@ def _get_current_user_refresh_token_payload(
),
epoch=refresh_token_payload[EPOCH_KEY],
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
effective_roles=normalize_roles(
refresh_token_payload.get(
EFFECTIVE_ROLES_KEY, refresh_token_payload[EFFECTIVE_ROLE_KEY]
)
),
effective_organization_id=uuid.UUID(
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
@@ -728,7 +741,7 @@ def _get_account_epoch(
return account.epoch
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
def _get_account_roles(session: Session, account_id: uuid.UUID) -> list[UserRole]:
"""Retrieves the role for the given account ID.
Args:
@@ -736,14 +749,14 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
Returns:
UserRole: The role associated with the given account ID.
list[UserRole]: The roles associated with the given account ID.
"""
account = session.get(Account, account_id)
if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.role
return normalize_roles(account.roles)
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
@@ -794,13 +807,16 @@ def _is_valid_impersonation(
):
raise AccountNotFoundException
if real_account.role == UserRole.SUPER_ADMIN:
real_account_role = effective_role_for_roles(real_account.roles)
effective_account_role = effective_role_for_roles(effective_account.roles)
if real_account_role == UserRole.SUPER_ADMIN:
return True # Super admins can impersonate any account
if real_account.organization_id != effective_account.organization_id:
return False # Cannot impersonate accounts from different organizations
if real_account.role == UserRole.ADMIN and effective_account.role in [
if real_account_role == UserRole.ADMIN and effective_account_role in [
UserRole.MANAGER,
UserRole.USER,
]:
@@ -847,7 +863,8 @@ def get_access_token(
detail="Impersonation not allowed",
)
role = _get_account_role(session=session, account_id=effective_account_id)
roles = _get_account_roles(session=session, account_id=effective_account_id)
role = effective_role_for_roles(roles)
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
organization_id = _get_account_organization(
session=session, account_id=effective_account_id
@@ -862,6 +879,7 @@ def get_access_token(
effective_organization_id=organization_id,
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=roles,
)
_set_refresh_token(
response=response,
@@ -870,6 +888,7 @@ def get_access_token(
effective_role=role,
effective_organization_id=organization_id,
epoch=epoch,
effective_roles=roles,
)
return AccessResponse(
access_token=access_token,
@@ -974,6 +993,7 @@ def refresh_access_token(
effective_organization_id=refresh_token.effective_organization_id,
epoch=refresh_token.epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=refresh_token.effective_roles,
)
@@ -1020,6 +1040,7 @@ def _set_refresh_token(
effective_role: UserRole,
effective_organization_id: uuid.UUID,
epoch: int,
effective_roles: list[UserRole] | None = None,
) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1038,10 +1059,12 @@ def _set_refresh_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
}
@@ -1058,6 +1081,7 @@ def _set_refresh_token(
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
)
@@ -1069,6 +1093,7 @@ def _build_access_token(
effective_organization_id: uuid.UUID,
epoch: int,
user_fingerprint_hash: str,
effective_roles: list[UserRole] | None = None,
) -> AccessToken:
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1087,10 +1112,12 @@ def _build_access_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
@@ -1108,6 +1135,7 @@ def _build_access_token(
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
user_fingerprint_hash=user_fingerprint_hash,
raw_token=raw_token,
+15
View File
@@ -91,6 +91,21 @@ def create_db_and_tables():
"BOOLEAN NOT NULL DEFAULT TRUE"
)
)
if "roles" not in columns:
with engine.begin() as connection:
connection.execute(
text(
"ALTER TABLE account ADD COLUMN roles "
"JSON NOT NULL DEFAULT '[\"USER\"]'"
)
)
if "role" in columns:
connection.execute(
text(
"UPDATE account SET roles = '[\"' || role || '\"]' "
"WHERE role IS NOT NULL"
)
)
def get_session():
@@ -107,6 +107,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
def _wrap_exception(e: Exception) -> Exception:
logger.exception(f"Elasticsearch raised an exception: {e}")
if isinstance(e, httpx.HTTPStatusError):
if e.response.status_code == 404:
return ElasticsearchNotFoundException(
+3
View File
@@ -54,6 +54,7 @@ from inse.patents.service import (
)
from inse.works.purpose_router import router as works_purpose_router
from inse.works.v2.router import router as works_v2_router
logger = logging.getLogger(__name__)
@@ -103,6 +104,8 @@ app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.include_router(works_v2_router)
app.include_router(dashboard_router)
app.include_router(bookmarks_router)
+17 -8
View File
@@ -16,6 +16,7 @@ else:
def __str__(self) -> str:
return self.value
from pydantic import BaseModel
from pydantic import Field
from typing import List
@@ -28,11 +29,16 @@ T = TypeVar("T", bound=BaseModel)
class Page(BaseModel, Generic[T]):
elements: List[T] = Field(default=[], description="The elements of the page.")
offset: int = Field(default=0, description="The page number. (0-based)")
page: int = Field(default=0, description="The page number. (0-based)")
size: int = Field(default=20, description="The page size in elements.")
total: int = Field(default=0, description="The total number of elements.")
class SortDirection(StrEnum):
ASCENDING = "asc"
DESCENDING = "desc"
class ESCluster(StrEnum):
NES = "nes"
INSE = "inse"
@@ -40,6 +46,7 @@ class ESCluster(StrEnum):
class ESIndex(StrEnum):
OPENALEX_WORKS = "openalex-works"
OPENALEX_WORKS_WILDCARD = "openalex-works*"
OPENALEX_AUTHORS = "openalex-authors"
OPENALEX_INSTITUTIONS = "openalex-institutions"
OPENALEX_PUBLICATIONS = "openalex-publications"
@@ -47,17 +54,17 @@ class ESIndex(StrEnum):
OPENALEX_CONTINENTS = "openalex-continents"
OPENALEX_TOPICS = "openalex-topics"
OPENALEX_TOPIC_VECTORS = "topicvectors"
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations"
# FP7
CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations"
@@ -84,8 +91,10 @@ class ESIndex(StrEnum):
CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations"
CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications"
CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables"
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries"
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = (
"cordis_eu_horizon_europe_report_summaries"
)
CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics"
CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links"
CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc"
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
+1
View File
@@ -7,6 +7,7 @@ class Tags(StrEnum):
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
WORKS_V2 = "Works V2"
NEWS = "News"
PROJECTS = "Projects"
AUTH = "Auth"
@@ -20,7 +20,7 @@ router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
async def get_work_purpose(
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
) -> SpecificWorkPurpose:
return await purpose_service.get_work_purpose(raw_oa_work_id)
return await purpose_service.get_work_purpose(raw_oa_work_id=raw_oa_work_id)
@router.get(
@@ -31,4 +31,6 @@ async def get_work_purpose(
async def get_author_work_purposes(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
) -> AuthorWorkPurposes:
return await purpose_service.get_author_work_purposes(raw_oa_author_id)
return await purpose_service.get_author_work_purposes(
raw_oa_author_id=raw_oa_author_id
)
@@ -2,7 +2,6 @@ import logging
import random
from typing import List
from fastapi import HTTPException, status
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
@@ -10,13 +9,14 @@ from inse.model import ESIndex
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
raw_oa_work_id = raw_oa_work_id.strip().upper()
response = await elasticsearch.get(
index=ESIndex.OPENALEX_WORKS,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
doc_id=raw_oa_work_id,
source=["title", "abstract"],
)
@@ -41,7 +41,7 @@ async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
raw_oa_author_id = raw_oa_author_id.strip().upper()
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=["id", "publication_year"],
query={
"nested": {
+48
View File
@@ -0,0 +1,48 @@
from enum import StrEnum
from typing import List
from pydantic import BaseModel, Field
from inse.model import Page
from inse.models.openalex.work_topic import WorkTopic
class WorkSortBy(StrEnum):
TITLE = "title"
TYPE = "type"
PUBLICATION_YEAR = "publication_year"
LANGUAGE = "language"
CITED_BY_COUNT = "cited_by_count"
class AuthorWorkInstitution(BaseModel):
institution_id: str = Field(
description="The ID of the institution associated with the work"
)
institution_name: str = Field(
description="The name of the institution associated with the work"
)
institution_country_code: str = Field(
description="The country code of the institution associated with the work"
)
class AuthorWork(BaseModel):
id: str = Field(description="The ID of the work")
title: str = Field(description="The title of the work")
type: str = Field(description="The type of the work")
publication_year: int = Field(description="The year the work was published")
language_code: str = Field(description="The language code of the work")
institutions: List[AuthorWorkInstitution] = Field(
description="A list of institutions associated with the work"
)
topics: List[WorkTopic] = Field(
description="A list of topics associated with the work"
)
cited_by_count: int = Field(
description="The number of citations the work has received"
)
class AuthorWorkPage(Page[AuthorWork]):
pass
+101
View File
@@ -0,0 +1,101 @@
from typing import Annotated, List
from fastapi import APIRouter, Path, Query
from inse.tags import Tags
from inse.model import SortDirection
from inse.works.v2.model import AuthorWorkPage, WorkSortBy
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2])
@router.get(
"/{raw_oa_author_id}",
operation_id="getAuthorWorkPage",
summary="Returns a paginated list of works for a given author based on their ID.",
)
async def get_author_works(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
publication_years: Annotated[
list[int],
Query(description="A list of publication years to filter by."),
] = [],
publication_types: Annotated[
list[str],
Query(description="A list of publication types to filter by."),
] = [],
institution_ids: Annotated[
list[str],
Query(description="A list of institution IDs to filter by."),
] = [],
topic_ids: Annotated[
list[str],
Query(description="A list of topic IDs to filter by."),
] = [],
language_codes: Annotated[
list[str],
Query(description="A list of language codes to filter by."),
] = [],
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> AuthorWorkPage:
from inse.works.v2.service import get_author_works
return await get_author_works(
raw_oa_author_id=raw_oa_author_id,
page=page,
size=size,
publication_years=publication_years or [],
publication_types=publication_types or [],
institution_ids=institution_ids or [],
topic_ids=topic_ids or [],
language_codes=language_codes or [],
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/topics/search",
operation_id="getWorkTopicsByIds",
summary="Returns a list of work topics based on their IDs.",
)
async def get_work_topics_by_ids(
topic_ids: Annotated[
list[str],
Query(description="A list of topic IDs to retrieve."),
] = [],
) -> List[WorkTopic]:
from inse.works.v2.service import get_work_topics_by_ids
return await get_work_topics_by_ids(topic_ids=topic_ids or [])
@router.get(
"/institutions/search",
operation_id="getInstitutionsByIds",
summary="Returns a list of institutions based on their IDs.",
)
async def get_institutions_by_ids(
institution_ids: Annotated[
list[str],
Query(description="A list of institution IDs to retrieve."),
] = [],
) -> List[Institution]:
from inse.works.v2.service import get_work_institutions_by_ids
return await get_work_institutions_by_ids(institution_ids=institution_ids or [])
+188
View File
@@ -0,0 +1,188 @@
import logging
from typing import List, Optional, Dict
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
from inse.works.v2.model import (
AuthorWork,
AuthorWorkInstitution,
AuthorWorkPage,
WorkSortBy,
)
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_author_works(
raw_oa_author_id: str,
page: int,
size: int,
publication_years: Optional[List[int]] = None,
publication_types: Optional[List[str]] = None,
institution_ids: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
language_codes: Optional[List[str]] = None,
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
sort_order: SortDirection = SortDirection.DESCENDING,
) -> AuthorWorkPage:
must = [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
}
},
}
}
]
if publication_years:
must.append({"terms": {"publication_year": publication_years}})
if publication_types:
must.append({"terms": {"type": publication_types}})
if language_codes:
must.append({"terms": {"language": language_codes}})
if institution_ids:
must.append(
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": institution_ids
}
},
}
},
}
}
)
if topic_ids:
must.append(
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
)
if sort_by == WorkSortBy.TITLE:
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
response = await elasticsearch.search(
ESIndex.OPENALEX_WORKS_WILDCARD,
source=[
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"authorships.institutions.id",
"authorships.institutions.display_name",
"authorships.institutions.country_code",
"topics",
],
query={"bool": {"must": must}},
size=size,
offset=page * size,
sort=sort,
)
logger.debug(f"Elasticsearch response for author {raw_oa_author_id} v2: {response}")
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
hits = hits_block.get("hits", [])
elements: List[AuthorWork] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for author {raw_oa_author_id} v2: {source}")
institutions: Dict[str, AuthorWorkInstitution] = {}
for authorship in source.get("authorships", []):
for institution in authorship.get("institutions", []):
institution_id = institution.get("id", "")
if institution_id not in institutions:
institutions[institution_id] = AuthorWorkInstitution(
institution_id=institution.get("id", ""),
institution_name=institution.get("display_name", ""),
institution_country_code=institution.get("country_code", ""),
)
topics: List[WorkTopic] = [
WorkTopic.from_dict(topic) for topic in source.get("topics", [])
] # type: ignore
elements.append(
AuthorWork(
id=source.get("id", ""),
title=source.get("title", ""),
type=source.get("type", ""),
publication_year=source.get("publication_year", 0),
language_code=source.get("language") or "",
institutions=list(institutions.values()),
topics=topics,
cited_by_count=source.get("cited_by_count", 0),
)
)
return AuthorWorkPage(
elements=elements,
total=total,
page=page,
size=size,
)
async def get_work_topics_by_ids(topic_ids: List[str]) -> List[WorkTopic]:
logger.debug(f"Fetching work topics for IDs: {topic_ids}")
if not topic_ids:
return []
must = [{"terms": {"id": topic_ids}}]
response = await elasticsearch.search(
ESIndex.OPENALEX_TOPICS,
source=["id", "display_name", "field", "domain"],
query={"bool": {"must": must}},
size=len(topic_ids),
)
logger.debug(f"Elasticsearch response for work topics {topic_ids}: {response}")
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
topics: List[WorkTopic] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for work topic {source.get('id', '')}: {source}")
topics.append(WorkTopic.from_dict(source)) # type: ignore
return topics
async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Institution]:
logger.debug(f"Fetching institutions for IDs: {institution_ids}")
if not institution_ids:
return []
must = [{"terms": {"id": institution_ids}}]
response = await elasticsearch.search(
ESIndex.OPENALEX_INSTITUTIONS,
source=["id", "display_name", "country_code"],
query={"bool": {"must": must}},
size=len(institution_ids),
)
logger.debug(
f"Elasticsearch response for institutions {institution_ids}: {response}"
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[Institution] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for institution {source.get('id', '')}: {source}")
institutions.append(Institution.from_dict(source)) # type: ignore
return institutions
+6
View File
@@ -1147,6 +1147,12 @@ Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-topics/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
@@ -19,6 +19,7 @@ api/projects.service.ts
api/topics.service.ts
api/universityRankings.service.ts
api/works.service.ts
api/worksV2.service.ts
configuration.ts
encoder.ts
git_push.sh
@@ -36,6 +37,9 @@ model/authorNetworkNode.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
model/authorSummaryStats.ts
model/authorWork.ts
model/authorWorkInstitution.ts
model/authorWorkPage.ts
model/authorWorkPurposes.ts
model/authorsFilterProperties.ts
model/authorsListResponse.ts
@@ -212,6 +216,7 @@ model/workMeshInner.ts
model/workNetworkNode.ts
model/workPage.ts
model/workPurpose.ts
model/workSortBy.ts
model/workSustainableDevelopmentGoalsInner.ts
model/workTopic.ts
model/workTopicDomain.ts
+3 -1
View File
@@ -28,4 +28,6 @@ export * from './universityRankings.service';
import { UniversityRankingsService } from './universityRankings.service';
export * from './works.service';
import { WorksService } from './works.service';
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService];
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService, WorksV2Service];
+275
View File
@@ -0,0 +1,275 @@
/**
* 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.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorWorkPage } from '../model/authorWorkPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { Institution } from '../model/institution';
// @ts-ignore
import { SortDirection } from '../model/sortDirection';
// @ts-ignore
import { WorkSortBy } from '../model/workSortBy';
// @ts-ignore
import { WorkTopic } from '../model/workTopic';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class WorksV2Service extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Returns a paginated list of works for a given author based on their ID.
* @endpoint get /api/v2/works/{raw_oa_author_id}
* @param rawOaAuthorId The raw OpenAlex author id.
* @param page The page number to retrieve. (0-based)
* @param size The number of works to retrieve per page.
* @param publicationYears A list of publication years to filter by.
* @param publicationTypes A list of publication types to filter by.
* @param institutionIds A list of institution IDs to filter by.
* @param topicIds A list of topic IDs to filter by.
* @param languageCodes A list of language codes to filter by.
* @param sortBy The field to sort by.
* @param sortOrder The order to sort by.
* @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 getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorWorkPage>;
public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorWorkPage>>;
public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorWorkPage>>;
public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorWorkPage.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
if (publicationYears) {
publicationYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_years');
})
}
if (publicationTypes) {
publicationTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_types');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
if (languageCodes) {
languageCodes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language_codes');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sort_order');
let localVarHeaders = this.defaultHeaders;
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/v2/works/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorWorkPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a list of institutions based on their IDs.
* @endpoint get /api/v2/works/institutions/search
* @param institutionIds A list of institution IDs to retrieve.
* @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 getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<Institution>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<Institution>>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<Institution>>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
let localVarHeaders = this.defaultHeaders;
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/v2/works/institutions/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<Institution>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a list of work topics based on their IDs.
* @endpoint get /api/v2/works/topics/search
* @param topicIds A list of topic IDs to retrieve.
* @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 getWorkTopicsByIds(topicIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<WorkTopic>>;
public getWorkTopicsByIds(topicIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<WorkTopic>>>;
public getWorkTopicsByIds(topicIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<WorkTopic>>>;
public getWorkTopicsByIds(topicIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
let localVarHeaders = this.defaultHeaders;
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/v2/works/topics/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<WorkTopic>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+1
View File
@@ -40,6 +40,7 @@ export interface AccessToken {
* The specific role this access token grants within its organization.
*/
effective_role?: UserRole;
effective_roles?: Array<UserRole>;
/**
* The unique identifier of the organization associated with this access token.
*/
+1 -1
View File
@@ -14,7 +14,7 @@ export interface AccountProfile {
id: string;
email: string;
name: string;
role: UserRole;
roles: Array<UserRole>;
organization_id: string;
organization_name: string;
deleted: boolean;
+48
View File
@@ -0,0 +1,48 @@
/**
* 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 { AuthorWorkInstitution } from './authorWorkInstitution';
import { WorkTopic } from './workTopic';
export interface AuthorWork {
/**
* The ID of the work
*/
id: string;
/**
* The title of the work
*/
title: string;
/**
* The type of the work
*/
type: string;
/**
* The year the work was published
*/
publication_year: number;
/**
* The language code of the work
*/
language_code: string;
/**
* A list of institutions associated with the work
*/
institutions: Array<AuthorWorkInstitution>;
/**
* A list of topics associated with the work
*/
topics: Array<WorkTopic>;
/**
* The number of citations the work has received
*/
cited_by_count: number;
}
@@ -0,0 +1,26 @@
/**
* 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 AuthorWorkInstitution {
/**
* The ID of the institution associated with the work
*/
institution_id: string;
/**
* The name of the institution associated with the work
*/
institution_name: string;
/**
* The country code of the institution associated with the work
*/
institution_country_code: string;
}
@@ -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 { AuthorWork } from './authorWork';
export interface AuthorWorkPage {
/**
* The elements of the page.
*/
elements?: Array<AuthorWork>;
/**
* The page number. (0-based)
*/
page?: number;
/**
* The page size in elements.
*/
size?: number;
/**
* The total number of elements.
*/
total?: number;
}
@@ -13,7 +13,7 @@ import { UserRole } from './userRole';
export interface CreateAccountRequest {
email: string;
name: string;
role?: UserRole;
roles?: Array<UserRole>;
organization_id: string;
password: string;
openalex_person_id?: string | null;
+4
View File
@@ -11,6 +11,9 @@ export * from './authorNetworkNode';
export * from './authorParsedLongestName';
export * from './authorPositionCount';
export * from './authorSummaryStats';
export * from './authorWork';
export * from './authorWorkInstitution';
export * from './authorWorkPage';
export * from './authorWorkPurposes';
export * from './authorsFilterProperties';
export * from './authorsListResponse';
@@ -185,6 +188,7 @@ export * from './workMeshInner';
export * from './workNetworkNode';
export * from './workPage';
export * from './workPurpose';
export * from './workSortBy';
export * from './workSustainableDevelopmentGoalsInner';
export * from './workTopic';
export * from './workTopicDomain';
@@ -13,7 +13,7 @@ import { UserRole } from './userRole';
export interface UpdateAccountRequest {
email?: string | null;
name?: string | null;
role?: UserRole | null;
roles?: Array<UserRole> | null;
organization_id?: string | null;
password?: string | null;
openalex_person_id?: string | null;
+20
View File
@@ -0,0 +1,20 @@
/**
* 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 const WorkSortBy = {
Title: 'title',
Type: 'type',
PublicationYear: 'publication_year',
Language: 'language',
CitedByCount: 'cited_by_count'
} as const;
export type WorkSortBy = typeof WorkSortBy[keyof typeof WorkSortBy];
+7
View File
@@ -31,6 +31,9 @@ import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/sea
import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component';
import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component';
import { authorWorkPurposesResolver } from './resolvers/author-work-purposes.resolver';
import { workPageResolver } from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
export const routes: Routes = [
{
path: '',
@@ -279,7 +282,11 @@ export const routes: Routes = [
import('./modules/person-publications/person-publications.component').then(
(mod) => mod.PersonPublicationsComponent,
),
runGuardsAndResolvers: 'always',
resolve: {
selectedTopics: selectedTopicsResolver,
selectedInstitutions: selectedInstitutionsResolver,
authorWorkPage: workPageResolver,
authorWorkPurposes: authorWorkPurposesResolver,
},
},
@@ -186,7 +186,7 @@ export class AccountComponent {
constructor() {
effect(() => {
this.roles = [this.accountProfile().role];
this.roles = this.accountProfile().roles;
});
}
}
@@ -24,7 +24,7 @@
<mat-form-field appearance="outline">
<mat-label>Rolle</mat-label>
<mat-select formControlName="role">
<mat-select formControlName="roles" multiple>
@for (role of data.roles; track role) {
<mat-option [value]="role">{{ role }}</mat-option>
}
@@ -35,7 +35,7 @@ export interface AccountDialogData {
export interface AccountPayload {
email?: string;
name?: string;
role?: UserRole;
roles?: UserRole[];
organization_id?: string;
password?: string;
deleted?: boolean;
@@ -45,7 +45,7 @@ export interface AccountPayload {
export interface CreateAccountPayload {
email: string;
name: string;
role: UserRole;
roles: UserRole[];
organization_id: string;
password: string;
}
@@ -85,7 +85,7 @@ export class AccountDialogComponent {
name: new FormControl<string>(this.data.account?.name ?? '', [
Validators.required,
]),
role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
roles: new FormControl<UserRole[]>(this.data.account?.roles ?? ['USER'], [
Validators.required,
]),
organizationId: new FormControl<string>(
@@ -115,7 +115,7 @@ export class AccountDialogComponent {
payload: {
email: value.email ?? '',
name: value.name ?? '',
role: value.role ?? 'USER',
roles: value.roles ?? ['USER'],
organization_id: value.organizationId ?? '',
password: value.password ?? '',
},
@@ -128,7 +128,7 @@ export class AccountDialogComponent {
const email = (value.email ?? '').trim();
const name = (value.name ?? '').trim();
const role = value.role ?? account.role;
const roles = value.roles ?? account.roles;
const organizationId = value.organizationId ?? account.organization_id;
const password = value.password?.trim() ?? '';
@@ -140,8 +140,8 @@ export class AccountDialogComponent {
payload.name = name;
}
if (role !== account.role) {
payload.role = role;
if (!this.sameRoles(roles, account.roles)) {
payload.roles = roles;
}
if (password) {
@@ -166,4 +166,10 @@ export class AccountDialogComponent {
protected close(): void {
this.dialogRef.close();
}
private sameRoles(left: UserRole[], right: UserRole[]): boolean {
return (
left.length === right.length && left.every((role) => right.includes(role))
);
}
}
@@ -44,7 +44,9 @@
</section>
<ng-template #accountRoleTmp let-row>
<span class="role">{{ row.role | role }}</span>
@for (role of row.roles; track role) {
<span class="role">{{ role | role }}</span>
}
</ng-template>
<ng-template #accountStatusTmp let-row>
@@ -126,10 +126,10 @@ export class AccountsComponent implements OnInit {
accessorKey: 'organization_name',
},
{
id: 'role',
id: 'roles',
header: 'Rolle',
type: 'accessor',
accessorKey: 'role',
accessorKey: 'roles',
cellTemplate: this.accountRoleTmp(),
},
{
@@ -325,7 +325,22 @@ export class AccountsComponent implements OnInit {
return (
this.credentialService.isEffectiveAdmin() &&
(account.role === 'MANAGER' || account.role === 'USER')
(this.effectiveRole(account) === 'MANAGER' ||
this.effectiveRole(account) === 'USER')
);
}
protected effectiveRole(account: AccountProfile): UserRole {
const roles = account.roles;
if (roles.includes('SUPER_ADMIN')) {
return 'SUPER_ADMIN';
}
if (roles.includes('ADMIN')) {
return 'ADMIN';
}
if (roles.includes('MANAGER')) {
return 'MANAGER';
}
return 'USER';
}
}
@@ -21,22 +21,23 @@
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>Publikationsliste</mat-panel-title>
<mat-panel-description>{{ total }} Publikationen</mat-panel-description>
<mat-panel-description
>{{ totalElements() }} Publikationen</mat-panel-description
>
</mat-expansion-panel-header>
<div class="publication-filter-stack">
<form class="publication-filters" [formGroup]="filterForm">
<form class="publication-filters">
<mat-form-field>
<mat-icon matPrefix class="filter-prefix-icon"
>calendar_today</mat-icon
>
<mat-select
placeholder="Jahr"
formControlName="publicationYears"
multiple
[panelWidth]="null"
(selectionChange)="applyFilters()"
(selectionChange)="handleYearSelectionChange($event)"
(opened)="focusSelectSearch(yearSearchInput)"
(closed)="yearSearchControl.setValue('')">
[value]="this.selectedYearsQueryParams()">
<mat-select-trigger>{{
yearSelectionSummary()
}}</mat-select-trigger>
@@ -46,7 +47,6 @@
#yearSearchInput
type="text"
class="select-search__input"
[formControl]="yearSearchControl"
placeholder="Jahr suchen…"
(keydown)="$event.stopPropagation()" />
</div>
@@ -62,12 +62,11 @@
<mat-icon matPrefix class="filter-prefix-icon">category</mat-icon>
<mat-select
placeholder="Typ"
formControlName="types"
multiple
[panelWidth]="null"
(selectionChange)="applyFilters()"
(selectionChange)="handleTypeSelectionChange($event)"
(opened)="focusSelectSearch(typeSearchInput)"
(closed)="typeSearchControl.setValue('')">
[value]="this.selectedTypesQueryParams()">
<mat-select-trigger>{{
typeSelectionSummary()
}}</mat-select-trigger>
@@ -93,12 +92,11 @@
<mat-icon matPrefix class="filter-prefix-icon">translate</mat-icon>
<mat-select
placeholder="Sprache"
formControlName="languages"
multiple
[panelWidth]="null"
(selectionChange)="applyFilters()"
(selectionChange)="handleLanguageSelectionChange($event)"
(opened)="focusSelectSearch(languageSearchInput)"
(closed)="languageSearchControl.setValue('')">
[value]="this.selectedLanguagesQueryParams()">
<mat-select-trigger>{{
languageSelectionSummary()
}}</mat-select-trigger>
@@ -185,21 +183,6 @@
</mat-autocomplete>
</mat-form-field>
<mat-form-field class="sort-field">
<mat-icon matPrefix class="filter-prefix-icon">sort</mat-icon>
<mat-select
[formControl]="sortControl"
[panelWidth]="null"
aria-label="Sortierung"
(selectionChange)="onSortChange()">
@for (option of sortOptions; track option.value) {
<mat-option [value]="option.value">{{
option.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
<button
class="reset-filter-btn"
mat-stroked-button
@@ -211,20 +194,17 @@
</button>
</form>
@let selectedYears = filterForm.controls.publicationYears.value;
@let selectedTypes = filterForm.controls.types.value;
@let selectedLanguages = filterForm.controls.languages.value;
@if (
selectedInstitutions.length ||
selectedTopics.length ||
selectedYears.length ||
selectedTypes.length ||
selectedLanguages.length
selectedInstitutionIdsQueryParams().length ||
selectedTopicIdsQueryParams().length ||
selectedYearsQueryParams().length ||
selectedTypesQueryParams().length ||
selectedLanguagesQueryParams().length
) {
<div class="active-filters-row" aria-label="Aktive Filter">
<span class="active-filters-label">Aktive Filter:</span>
<div class="chips-container">
@for (year of selectedYears; track year) {
@for (year of selectedYearsQueryParams(); track year) {
<span class="active-meta-filter">
<span class="filter-meta-chip">
<mat-icon class="filter-meta-chip__icon"
@@ -241,7 +221,7 @@
</button>
</span>
}
@for (type of selectedTypes; track type) {
@for (type of selectedTypesQueryParams(); track type) {
<span class="active-meta-filter">
<span class="filter-meta-chip">
<mat-icon class="filter-meta-chip__icon">category</mat-icon>
@@ -256,14 +236,17 @@
</button>
</span>
}
@for (language of selectedLanguages; track language) {
@for (
language of selectedLanguagesQueryParams();
track language
) {
<span class="active-meta-filter">
<span class="filter-meta-chip">
<mat-icon class="filter-meta-chip__icon"
>translate</mat-icon
>
<span class="filter-meta-chip__label">{{
languageLabel(language)
language | languageCode
}}</span>
</span>
<button
@@ -271,20 +254,20 @@
class="remove-chip-btn"
(click)="toggleLanguageFilter(language)"
[attr.aria-label]="
'Sprachfilter ' + languageLabel(language) + ' entfernen'
'Sprachfilter ' + (language | languageCode) + ' entfernen'
">
<mat-icon>close</mat-icon>
</button>
</span>
}
@for (topic of selectedTopics; track topic.id) {
@for (topic of selectedTopics(); track topic.id) {
<span class="active-meta-filter">
<span
class="filter-topic-chip"
[style.--topic-color]="getSelectedTopicColor(topic)"
[matTooltip]="getSelectedTopicTooltip(topic)"
[style.--topic-color]="getWorkTopicColor(topic)"
[matTooltip]="getSelectedWorkTopicTooltip(topic)"
matTooltipClass="topic-chip-tooltip"
[matTooltipDisabled]="!getSelectedTopicTooltip(topic)">
[matTooltipDisabled]="!getSelectedWorkTopicTooltip(topic)">
<mat-icon class="filter-topic-chip__icon">label</mat-icon>
<span class="filter-topic-chip__label">{{
topic.display_name
@@ -301,7 +284,10 @@
</button>
</span>
}
@for (institution of selectedInstitutions; track institution.id) {
@for (
institution of selectedInstitutions();
track institution.id
) {
@let instCountry = selectedInstitutionCountry(institution);
<span class="active-institution-filter">
<span class="filter-institution-chip">
@@ -325,7 +311,10 @@
}
<mat-icon
class="institution-open-icon"
(click)="openInstitutionPage(institution.id, $event)"
[routerLink]="[
'/institution',
extractRawId(institution.id),
]"
aria-label="Institutionsseite öffnen"
>open_in_new</mat-icon
>
@@ -344,13 +333,16 @@
}
</div>
<app-data-table [columns]="workColumns" [data]="publications" />
<app-data-table
[columns]="workColumns"
[data]="elements()"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
<app-query-param-paginator
[total]="total"
queryParamPageKey="publicationPage"
queryParamSizeKey="publicationPageSize"
[pageSizeOptions]="paginationService.options"
(handlePageChange)="onPage($event)" />
[total]="totalElements()"
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="paginationService.options" />
</mat-expansion-panel>
</mat-accordion>
</div>
@@ -398,11 +390,11 @@
<button
type="button"
class="cell-filter-pill"
[class.active]="isLanguageActive(work.language)"
[class.active]="isLanguageActive(work.language_code)"
matTooltip="Nach Sprache filtern"
matTooltipPosition="above"
(click)="toggleLanguageFilter(work.language)">
{{ work.language | languageCode }}
(click)="toggleLanguageFilter(work.language_code)">
{{ work.language_code | languageCode }}
</button>
} @else {
<span class="empty-text">-</span>
@@ -410,43 +402,49 @@
</ng-template>
<ng-template #institutionsTmp let-work>
@let publicationInstitutions = getInstitutions(work);
@let publicationInstitutions = work.institutions ?? [];
@let institutionsExpanded = true;
@let visibleInstitutions =
institutionsExpanded
? publicationInstitutions
: publicationInstitutions.slice(0, 3);
<div class="institution-tags" aria-label="Institutionen">
@for (institution of visibleInstitutions; track institution.id) {
<div
class="institution-tags"
aria-label="Institutionen"
style="padding: 0.5rem 0">
@for (
institution of visibleInstitutions;
track institution.institution_id
) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institution.id!)"
[matTooltip]="institution.display_name"
[class.active]="isInstitutionActive(institution.institution_id!)"
[matTooltip]="institution.institution_name"
matTooltipPosition="above"
[attr.aria-label]="
'Nach Institution ' + institution.display_name + ' filtern'
'Nach Institution ' + institution.institution_name + ' filtern'
"
(click)="
filterByInstitution({
id: institution.id!,
name: institution.display_name || '',
id: institution.institution_id!,
name: institution.institution_name || '',
})
">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{ institution.display_name }}</span>
@if (institution.country_code) {
<span class="institution-name">{{ institution.institution_name }}</span>
@if (institution.institution_country_code) {
<img
alt=""
class="flag-img"
[src]="
'https://flagcdn.io/' +
institution.country_code.toLowerCase() +
institution.institution_country_code.toLowerCase() +
'.svg'
"
height="10" />
<span class="country-code">{{
institution.country_code.toUpperCase()
institution.institution_country_code.toUpperCase()
}}</span>
}
</button>
@@ -483,7 +481,7 @@
[subfieldName]="topic.subfield?.display_name"
[fieldName]="topic.field?.display_name"
[domainName]="topic.domain?.display_name"
[color]="getTopicColor(topic)"
[color]="getWorkTopicColor(topic)"
[disabled]="!topic.id"
[active]="isTopicActive(topic)"
(chipClick)="filterByTopic(topic)">
@@ -511,7 +509,7 @@
<a
mat-icon-button
color="primary"
[routerLink]="['/publication', publicationKey(work)]"
[routerLink]="['/publication', extractRawId(work.id)]"
matTooltip="Details anzeigen">
<mat-icon>open_in_new</mat-icon>
</a>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,18 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { Institution, WorksV2Service } from '../api';
export const selectedInstitutionsResolver: ResolveFn<Array<Institution>> = (
route,
state,
) => {
const institutionIds = route.queryParamMap.getAll('publicationInstitutionId');
if (institutionIds.length === 0) {
return [];
}
console.log('Resolving selected institutions for IDs:', institutionIds);
return inject(WorksV2Service).getInstitutionsByIds(
institutionIds.map((id) => id.trim()).filter((id) => id.length > 0),
);
};
@@ -0,0 +1,18 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { WorksV2Service, WorkTopic } from '../api';
export const selectedTopicsResolver: ResolveFn<Array<WorkTopic>> = (
route,
state,
) => {
const topicIds = route.queryParamMap.getAll('publicationTopicId');
if (topicIds.length === 0) {
return [];
}
console.log('Resolving selected topics for IDs:', topicIds);
return inject(WorksV2Service).getWorkTopicsByIds(
topicIds.map((id) => id.trim()).filter((id) => id.length > 0),
);
};
+35 -18
View File
@@ -1,27 +1,44 @@
import { ResolveFn } from '@angular/router';
import { WorkPage, WorksService } from '../api';
import {
AuthorWorkPage,
SortDirection,
WorkSortBy,
WorksV2Service,
} from '../api';
import { inject } from '@angular/core';
export const workPageResolver: ResolveFn<WorkPage> = (route, state) => {
const authorId = route.paramMap.get('authorId');
const page = Number(route.queryParamMap.get('page') || 0);
const pageSize = Number(route.queryParamMap.get('pageSize') || 10);
const publicationYears = route.queryParamMap
.getAll('publicationYears')
.map(Number);
const type = route.queryParamMap.getAll('types');
const languages = route.queryParamMap.getAll('languages');
const institutionIds = route.queryParamMap.getAll('institutionIds');
const topicsIds = route.queryParamMap.getAll('topicsIds');
export const workPageResolver: ResolveFn<AuthorWorkPage> = (route, state) => {
const rawOaAuthorId =
route.parent?.paramMap.get('id') || route.paramMap.get('id');
if (!rawOaAuthorId) {
throw new Error('Author ID is required to resolve author work purposes.');
}
return inject(WorksService).getAuthorWorks(
authorId!,
const page = Number(route.queryParamMap.get('page')) || 0;
const size = Number(route.queryParamMap.get('size')) || 10;
const publicationYears = route.queryParamMap
.getAll('publicationYear')
.map(Number);
const publicationTypes = route.queryParamMap.getAll('publicationType');
const institutionIds = route.queryParamMap.getAll('publicationInstitutionId');
const topicIds = route.queryParamMap.getAll('publicationTopicId');
const sortBy: WorkSortBy = (route.queryParamMap.get('sort_by') ||
'publication_year') as WorkSortBy;
const sortDirection: SortDirection = (route.queryParamMap.get(
'sort_direction',
) || 'desc') as SortDirection;
return inject(WorksV2Service).getAuthorWorkPage(
rawOaAuthorId,
page,
pageSize,
size,
publicationYears,
type,
languages,
publicationTypes,
institutionIds,
topicsIds,
topicIds,
undefined,
sortBy,
sortDirection,
);
};