Compare commits

...
Author SHA1 Message Date
farajollahi 33949bef75 Merge branch 'dev' into publications-filters-overview
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-07 12:10:01 +02:00
farajollahi bc3f6b6a95 implement detail page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 17:09:39 +02:00
khalti 8774a425d8 Merge pull request 'feat(funding): show publication titles and improve UI' (#114) from ts-86-get-funding-by-author-clean into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #114
2026-06-06 16:42:38 +02:00
khalti 653c1745eb feat(funding): show publication titles and improve UI
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-06 16:38:45 +02:00
Kazgatari 0529db02d1 Added simple filter to remove some false entries when searching for a Person
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 14:24:57 +02:00
kuzko d951e60ecb Merge pull request 'merging_persons' (#113) from merging_persons into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #113
2026-06-06 13:18:08 +02:00
Kazgatari a5868a3107 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into merging_persons
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 13:14:30 +02:00
Kazgatari c3865a8660 remove openalex_id, change publication & citation to german
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-06 12:45:31 +02:00
Kazgatari 59a718aeaf fix rective topic search frontend 2026-06-06 12:19:16 +02:00
farajollahi fdb0cb3daa implement topics and institute filters
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 11:45:49 +02:00
Kazgatari ba296ef499 changed backend search filter & frontend topic search component (the topics are for now not in the frontend (fetched everytime to reflect changes))
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 11:20:25 +02:00
tischer 33f767dea3 Merge pull request 'person_interested_in shows top topics of works' (#112) from feature/person_interested_in into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #112
2026-06-06 09:52:59 +02:00
Steven Tischer 81e6d4436d show primary topic counts in interest tags
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-06 09:37:40 +02:00
Steven Tischer 2722c846f7 regenerate OpenAPI client from current service spec 2026-06-06 09:36:11 +02:00
Steven Tischer 3930e94b30 add primary topic counts endpoint for authors 2026-06-06 09:35:16 +02:00
Steven Tischer 39969fbaab add footnote to interest card for publication count 2026-06-06 08:16:18 +02:00
Steven Tischer 2a20e7bc33 update person to display scores in interest tags 2026-06-06 08:11:32 +02:00
genja 765c5c9509 regenerated openApi endpoints
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 21:56:49 +02:00
genja 5cfda2e5d6 fixed backed endpoints 2026-06-05 21:56:30 +02:00
genja eab0077347 little ui adjustment 2026-06-05 21:55:49 +02:00
genja 247d81381f endpoints directories fixed 2026-06-05 21:03:06 +02:00
genja bf0cac3299 fixed merging issues 2026-06-05 21:02:36 +02:00
genja 743353f511 Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into merging_persons 2026-06-05 20:46:23 +02:00
genja 1a1bd0226c regenerated openApi endpoints 2026-06-05 18:49:00 +02:00
Kazgatari c77149dcc3 quick patch to revert previos refactor commit
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 16:28:37 +02:00
Kazgatari 5137601bc9 refactor search & added button to filter newest affiliation of institution
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 14:48:13 +02:00
genja e524d3d96c added first institutions filter
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 14:00:39 +02:00
genja 26940fd92d added personSeachWithFilters and + filter services 2026-06-05 13:59:38 +02:00
taguesokoudjou a769fcf380 Merge pull request 'ts-86-get-funding-by-author-clean' (#107) from ts-86-get-funding-by-author-clean into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #107
2026-06-05 12:53:58 +02:00
taguesokoudjou 941652209c Merge remote-tracking branch 'origin/dev' into ts-86-get-funding-by-author-clean
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 12:41:54 +02:00
erfanian b69608050e Merge PR #111: Add topic IDs to timeline response
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #111
2026-06-05 12:23:50 +02:00
spsaefan fffb362197 Add topic ids to timeline response
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-05 12:04:56 +02:00
genja 4aad221543 added track_total_hits field to elastic wrapper 2026-06-05 11:49:03 +02:00
genja 4c33a3e416 updated openApi config + generated endpoints
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 23:18:09 +02:00
genja b168378b11 fixed merging issues. 2026-06-04 23:17:14 +02:00
genja 3e6f2b80f2 Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-04 23:06:52 +02:00
genja c08745c4b0 adjusted search logic by adding search term to query params 2026-06-04 22:59:02 +02:00
genja ff639ec74e adjusted UI for persons list 2026-06-04 22:57:21 +02:00
genja fce1ad74b3 search by institutions adjusted 2026-06-04 22:54:38 +02:00
genja ee991adf3a added page offset to person search 2026-06-04 22:33:28 +02:00
kuzko 57c7dd6d5f Merge pull request 'feature/person-list' (#110) from feature/person-list into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #110
2026-06-04 21:20:17 +02:00
taguesokoudjou de4b7a9ff1 Fix funders pagination test
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-04 17:32:31 +02:00
taguesokoudjou a4a9c58119 Merge remote-tracking branch 'origin/dev' into ts-89-get-funding-by-author-clean
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-04 16:43:11 +02:00
genja 9a5c833b3a refactored for functionality 2026-06-04 13:44:06 +02:00
genja d4b40f5962 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-04 12:54:44 +02:00
genja 537199742b Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-04 12:53:43 +02:00
Steven Tischer ec2899fad9 refactor(backend/persons): move person logic and endpoints to own package
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 11:07:19 +02:00
taguesokoudjou 2dfaace34b Add funder publication URLs from Elasticsearch
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-04 10:43:25 +02:00
Steven Tischer 75514b7f57 fix(backend/elasticsearch): update get function to use query parameters instead of body
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 10:32:47 +02:00
Steven Tischer 9f5835a5d3 refactor(backend/persons): update person logic references to use persons_logic module 2026-06-04 10:31:21 +02:00
Steven Tischer a9822ca5ff refactor(backend/persons): move person logic from logic.py to seperate folder 2026-06-04 10:29:41 +02:00
genja c24686258c added autocompletion for person search 2026-06-03 17:40:25 +02:00
khalti 8df18efd8f Personensuche in der Navigationsleiste hinzugefügt
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-03 10:46:24 +02:00
khalti d0d5a1b793 merge: Konflikte in person-funding Komponenten gelöst
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-03 10:06:07 +02:00
khalti e898f15583 feat: Personensuche in der Navigationsleiste hinzugefügt 2026-06-03 09:39:25 +02:00
taguesokoudjou fd09c5e08c Improve funding view pagination and UI styling
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-03 09:14:46 +02:00
taguesokoudjou b2996b07c6 Refine funding detail view by showing position stats per active filter
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 13:05:36 +02:00
taguesokoudjou 300a618cfd Open publication links directly as PDF with HTML fallback
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 12:52:50 +02:00
taguesokoudjou 9c49191629 Persist funding tab state after reload via query params
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 12:35:44 +02:00
taguesokoudjou 6fe70c8738 Update person funding frontend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-01 22:49:33 +02:00
taguesokoudjou 5294d26552 Refactor funders logic into separate module and add tests
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-01 22:21:50 +02:00
khalti fac08044a8 Add Person funding View and API integration
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-01 14:02:25 +02:00
khalti ce4ccbf154 Add person funding frontend view
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-31 09:10:50 +02:00
taguesokoudjou 22dd33c0a9 Add funders by author endpoint with position counts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-30 09:10:09 +02:00
99 changed files with 8481 additions and 882 deletions
+4
View File
@@ -34,6 +34,10 @@ class Settings(BaseSettings):
"am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
)
openalex_works_search_timeout_seconds: float = 30.0
# OpenAlex public API config
openalex_api_base_url: str = "https://api.openalex.org"
openalex_api_key: Optional[str] = None
openalex_api_timeout_seconds: float = 30.0
# LLM config
llm_api_url: Optional[str] = None
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Funders domain package.
"""
@@ -0,0 +1,160 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for funded-publication searches in the OpenAlex works index.
"""
from typing import Any
import httpx
from .. import config
class MissingApiKeyError(Exception):
pass
class FundedPublicationsSearchClient:
def __init__(
self,
base_url: str | None = None,
index: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
@staticmethod
def indexed_author_id(author_id: str) -> str:
short_id = author_id.strip().removeprefix("https://openalex.org/")
return f"https://openalex.org/{short_id}"
def publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
*,
funded_only: bool = False,
) -> dict[str, Any]:
indexed_author_id = self.indexed_author_id(author_id)
must: list[dict[str, Any]] = [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": indexed_author_id,
},
},
},
},
]
if funded_only:
must.append(self._has_funding_clause())
return {
"from": (page - 1) * size,
"size": size,
"track_total_hits": True,
"_source": self._publication_source_fields(),
"query": {
"bool": {
"must": must,
},
},
}
@staticmethod
def _publication_source_fields() -> list[str]:
return [
"id",
"doi",
"title",
"display_name",
"publication_year",
"primary_location.landing_page_url",
"primary_location.pdf_url",
"best_oa_location.landing_page_url",
"best_oa_location.pdf_url",
"open_access.oa_url",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"funders.id",
"funders.display_name",
"funders.ror",
"awards.id",
"awards.funder_id",
"awards.funder_display_name",
"awards.funder_award_id",
]
@staticmethod
def _has_funding_clause() -> dict[str, Any]:
return {
"bool": {
"should": [
{
"nested": {
"path": "funders",
"query": {
"bool": {
"should": [
{"exists": {"field": "funders.id"}},
{"exists": {"field": "funders.display_name"}},
],
"minimum_should_match": 1,
},
},
},
},
{
"nested": {
"path": "awards",
"query": {
"bool": {
"should": [
{"exists": {"field": "awards.funder_id"}},
{"exists": {"field": "awards.funder_display_name"}},
],
"minimum_should_match": 1,
},
},
},
},
],
"minimum_should_match": 1,
},
}
def funded_publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
) -> dict[str, Any]:
return self.publications_by_author_query(author_id, page, size, funded_only=True)
async def search(self, payload: dict[str, Any]) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{self.index}/_search",
headers={"Authorization": f"ApiKey {self.api_key}"},
json=payload,
)
response.raise_for_status()
return response.json()
+305
View File
@@ -0,0 +1,305 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for author funding based on publication works.
"""
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from ..persons import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from .elastic_search_client import MissingApiKeyError
logger = logging.getLogger(__name__)
_VALID_AUTHOR_POSITIONS = frozenset({"first", "middle", "last"})
_ES_PAGE_SIZE = 500
_MAX_ES_PAGES = 100
async def get_publications_by_author_id(
author_id: str,
page: int = 1,
page_size: int = 20,
client: FundedPublicationsSearchClient | None = None,
) -> model.PublicationsByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
total_works, all_hits = await _fetch_all_author_work_hits(
search_client,
author_id,
funded_only=True,
)
funded_hits = [
hit for hit in all_hits
if _publication_has_funder_data(hit.get("_source", {}))
]
start = (page - 1) * page_size
end = start + page_size
return model.PublicationsByAuthorResponse(
author_id=FundedPublicationsSearchClient.indexed_author_id(author_id),
page=page,
page_size=page_size,
total_works=total_works,
total=len(funded_hits),
results_count=len(funded_hits[start:end]),
results=funded_hits[start:end],
)
async def get_funders_by_author_id(
author_id: str,
client: FundedPublicationsSearchClient | None = None,
) -> model.FundersByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
funder_counts: dict[str, dict[str, Any]] = {}
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
author_name = _get_author_name(author_id)
try:
_, all_hits = await _fetch_all_author_work_hits(
search_client,
author_id,
funded_only=True,
)
_collect_funders_from_publications(all_hits, author_id, funder_counts)
if not funder_counts:
logger.info(
"No funders aggregated for author %s from Elasticsearch.",
normalized_author_id,
)
funders = sorted(
funder_counts.values(),
key=lambda entry: entry["publication_count"],
reverse=True,
)
return model.FundersByAuthorResponse(
author_id=normalized_author_id,
author_name=author_name,
funder_count=len(funders),
funders=[model.FunderByAuthor.model_validate(entry) for entry in funders],
)
except ValidationError as exc:
logger.exception("Funders response could not be validated for author %s.", author_id)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Funders response could not be parsed.",
) from exc
async def _fetch_all_author_work_hits(
search_client: FundedPublicationsSearchClient,
author_id: str,
*,
funded_only: bool = False,
page_size: int = _ES_PAGE_SIZE,
) -> tuple[int, list[dict]]:
page = 1
total_works = 0
all_hits: list[dict] = []
while page <= _MAX_ES_PAGES:
data = await _search_funded_publications(
search_client,
author_id,
page,
page_size,
funded_only=funded_only,
)
total_works, hits = _parse_publication_search_response(data)
all_hits.extend(hits)
if not hits or page * page_size >= total_works:
break
page += 1
if page > _MAX_ES_PAGES and page * page_size < total_works:
logger.warning(
"Stopped pagination for author %s at %s pages (total works: %s).",
author_id,
_MAX_ES_PAGES,
total_works,
)
return total_works, all_hits
async def _search_funded_publications(
search_client: FundedPublicationsSearchClient,
author_id: str,
page: int,
page_size: int,
*,
funded_only: bool = False,
) -> dict:
try:
payload = search_client.publications_by_author_query(
author_id,
page,
page_size,
funded_only=funded_only,
)
return await search_client.search(payload)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="OpenAlex works search is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex works search request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
hits = data.get("hits", {})
total = hits.get("total", 0)
if isinstance(total, dict):
total = total.get("value", 0)
results = hits.get("hits", [])
for hit in results:
_add_publication_url(hit.get("_source", {}))
return total, results
def _get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
search_result = person_logic.search_persons(author_id=short_author_id)
if not search_result.results:
return None
return search_result.results[0].display_name
def _get_author_position_in_publication(publication: dict, author_id: str) -> str:
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
for authorship in publication.get("authorships", []):
author = authorship.get("author", {})
if author.get("id") == normalized_author_id:
position = authorship.get("author_position", "unknown")
if position in _VALID_AUTHOR_POSITIONS:
return position
return "unknown"
return "unknown"
def _publication_has_funder_data(publication: dict) -> bool:
for funder in publication.get("funders", []):
if funder.get("id") or funder.get("display_name"):
return True
for award in publication.get("awards", []):
if award.get("funder_id") or award.get("funder_display_name"):
return True
return False
def _add_publication_url(publication: dict) -> None:
publication["publication_url"] = _resolve_publication_url(publication)
def _resolve_publication_url(publication: dict) -> str | None:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
open_access = publication.get("open_access") or {}
for url in (
primary_location.get("pdf_url"),
best_oa_location.get("pdf_url"),
primary_location.get("landing_page_url"),
best_oa_location.get("landing_page_url"),
open_access.get("oa_url"),
):
if url:
return url
doi = publication.get("doi")
if doi:
return doi if doi.startswith("http") else f"https://doi.org/{doi}"
return publication.get("id")
def _collect_funders_from_publications(
results: list[dict],
author_id: str,
funder_counts: dict[str, dict[str, Any]],
) -> None:
for hit in results:
publication = hit.get("_source", {})
if not _publication_has_funder_data(publication):
continue
publication_id = publication.get("id")
publication_url = publication.get("publication_url") or _resolve_publication_url(publication)
author_position = _get_author_position_in_publication(publication, author_id)
publication_funders: set[tuple[str, str | None, str | None]] = set()
for funder in publication.get("funders", []):
funder_id = funder.get("id")
funder_name = funder.get("display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for award in publication.get("awards", []):
funder_id = award.get("funder_id")
funder_name = award.get("funder_display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for key, funder_id, funder_name in publication_funders:
if key not in funder_counts:
funder_counts[key] = {
"funder_id": funder_id,
"funder_name": funder_name,
"publication_count": 0,
"author_position_count": {
"first": 0,
"middle": 0,
"last": 0,
"unknown": 0,
},
"publication_ids": {
"first": [],
"middle": [],
"last": [],
"unknown": [],
},
"publication_urls": {},
"publication_titles": {},
}
entry = funder_counts[key]
entry["publication_count"] += 1
entry["author_position_count"][author_position] += 1
entry["publication_ids"][author_position].append(publication_id)
if publication_id and publication_url:
entry["publication_urls"][publication_id] = publication_url
if publication_id:
title = publication.get("display_name") or publication.get("title") or publication_id
entry["publication_titles"][publication_id] = title
+44
View File
@@ -0,0 +1,44 @@
from typing import Any
from pydantic import BaseModel
class PublicationsByAuthorResponse(BaseModel):
author_id: str
page: int
page_size: int
total_works: int
total: int
results_count: int
results: list[dict[str, Any]]
class PublicationIdsByAuthorPosition(BaseModel):
first: list[str] = []
middle: list[str] = []
last: list[str] = []
unknown: list[str] = []
class AuthorPositionCount(BaseModel):
first: int = 0
middle: int = 0
last: int = 0
unknown: int = 0
class FunderByAuthor(BaseModel):
funder_id: str | None = None
funder_name: str | None = None
publication_count: int
author_position_count: AuthorPositionCount
publication_ids: PublicationIdsByAuthorPosition
publication_urls: dict[str, str] = {}
publication_titles: dict[str, str] = {}
class FundersByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
funder_count: int
funders: list[FunderByAuthor]
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for author publications and funding.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from . import logic
from . import model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"])
@router.get(
"/{author_id}/publications",
operation_id="getPublicationsByAuthor",
response_model=model.PublicationsByAuthorResponse,
summary="Get funded publications by author.",
)
async def get_publications_by_author(
author_id: str,
page: Annotated[int, Query(ge=1)] = 1,
page_size: Annotated[int, Query(ge=1, le=1000)] = 200,
):
return await logic.get_publications_by_author_id(author_id, page, page_size)
@router.get(
"/{author_id}/funders",
operation_id="getFundersByAuthor",
response_model=model.FundersByAuthorResponse,
summary="Get funding organizations by author.",
)
async def get_funders_by_author(author_id: str):
return await logic.get_funders_by_author_id(author_id)
+263
View File
@@ -0,0 +1,263 @@
import json
import httpx
import pytest
from fastapi import HTTPException
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def _funded_publication_hit(
work_id: str,
*,
funder_id: str | None = "https://openalex.org/F123",
funder_name: str | None = "Example Funder",
author_position: str = "first",
award_funder_id: str | None = None,
award_funder_name: str | None = None,
pdf_url: str | None = None,
) -> dict:
source: dict = {
"id": work_id,
"primary_location": {
"pdf_url": pdf_url,
},
"authorships": [
{
"author": {
"id": "https://openalex.org/A5023888391",
"display_name": "Example Author",
},
"author_position": author_position,
}
],
"funders": [],
"awards": [],
}
if funder_id or funder_name:
source["funders"].append(
{
"id": funder_id,
"display_name": funder_name,
}
)
if award_funder_id or award_funder_name:
source["awards"].append(
{
"funder_id": award_funder_id,
"funder_display_name": award_funder_name,
}
)
return {"_source": source}
@pytest.mark.anyio
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
assert payload["from"] == 0
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Funder A",
author_position="first",
pdf_url="https://example.org/w1.pdf",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
award_funder_id="https://openalex.org/F123",
award_funder_name="Funder A",
author_position="last",
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type(
"Result",
(),
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
)(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert response.author_id == "https://openalex.org/A5023888391"
assert response.author_name == "Example Author"
assert response.funder_count == 1
assert response.funders[0].funder_id == "https://openalex.org/F123"
assert response.funders[0].funder_name == "Funder A"
assert response.funders[0].publication_count == 2
assert response.funders[0].author_position_count.first == 1
assert response.funders[0].author_position_count.last == 1
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
@pytest.mark.anyio
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
requested_pages: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
size = payload["size"]
offset = payload["from"]
page = offset // size + 1
requested_pages.append(page)
total = size + 1
if page == 1:
hits = [
_funded_publication_hit(
f"https://openalex.org/W{i}",
funder_id=f"https://openalex.org/F{i}",
funder_name=f"Funder {i}",
)
for i in range(1, size + 1)
]
else:
hits = [
_funded_publication_hit(
f"https://openalex.org/W{total}",
funder_id=f"https://openalex.org/F{total}",
funder_name=f"Funder {total}",
)
]
return httpx.Response(
200,
json={
"hits": {
"total": {"value": total},
"hits": hits,
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert requested_pages == [1, 2]
assert response.funder_count > 1
funder_names = {funder.funder_name for funder in response.funders}
assert "Funder 1" in funder_names
@pytest.mark.anyio
async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Bundesministerium",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5093075883", client=client)
assert response.funder_count == 1
assert response.funders[0].funder_name == "Bundesministerium"
assert response.funders[0].publication_count == 1
@pytest.mark.anyio
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={"hits": {"total": {"value": 0}, "hits": []}},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5093075883", client=client)
assert response.funder_count == 0
assert response.funders == []
@pytest.mark.anyio
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(api_key="")
with pytest.raises(HTTPException) as exc:
await logic.get_funders_by_author_id("A5023888391", client=client)
assert exc.value.status_code == 503
@@ -0,0 +1 @@
"""Institution lookup module."""
+309
View File
@@ -0,0 +1,309 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for OpenAlex institutions.
"""
import logging
from copy import deepcopy
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.institutions_list_response import InstitutionsListResponse
from .search_client import OpenAlexInstitutionsClient
logger = logging.getLogger(__name__)
_VALID_INSTITUTION_TYPES = {
"education",
"healthcare",
"company",
"archive",
"nonprofit",
"government",
"facility",
"other",
}
async def list_institutions(
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
client: OpenAlexInstitutionsClient | None = None,
) -> InstitutionsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
openalex_client = client or OpenAlexInstitutionsClient()
try:
data = await openalex_client.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
except httpx.HTTPStatusError as exc:
status_code = exc.response.status_code
detail = "OpenAlex institutions request failed."
try:
error_body = exc.response.json()
detail = error_body.get("message") or error_body.get("error") or detail
except ValueError:
if exc.response.text:
detail = exc.response.text
raise HTTPException(status_code=status_code, detail=detail) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex institutions request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions request failed.",
) from exc
try:
normalized_data = _normalize_institutions_response(data)
return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse()
except ValidationError as exc:
logger.exception("OpenAlex institutions response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions response could not be parsed.",
) from exc
async def autocomplete_institutions(
*,
query: str,
country_code: str | None = None,
institution_type: str | None = None,
limit: int = 10,
client: OpenAlexInstitutionsClient | None = None,
) -> AutocompleteResponse:
filters = []
if country_code:
filters.append(f"country_code:{country_code}")
if institution_type:
filters.append(f"type:{institution_type}")
response = await list_institutions(
search=query,
filter=",".join(filters) if filters else None,
sort="works_count:desc",
per_page=limit,
page=1,
select=(
"id,ror,display_name,country_code,type,works_count,"
"cited_by_count,geo"
),
client=client,
)
results = []
for institution in response.results or []:
if not institution.id or not institution.display_name:
continue
hint_parts = []
if institution.geo:
if institution.geo.city:
hint_parts.append(institution.geo.city)
if institution.geo.country:
hint_parts.append(institution.geo.country)
elif institution.country_code:
hint_parts.append(institution.country_code)
if institution.type:
hint_parts.append(institution.type)
results.append(
AutocompleteResponseResultsInner(
id=institution.id,
display_name=institution.display_name,
hint=" · ".join(hint_parts) if hint_parts else None,
cited_by_count=institution.cited_by_count,
works_count=institution.works_count,
entity_type="institution",
external_id=institution.ror,
)
)
return AutocompleteResponse(
meta=AutocompleteResponseMeta(
count=response.meta.count if response.meta else len(results),
db_response_time_ms=(
response.meta.db_response_time_ms if response.meta else None
),
),
results=results,
)
def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
normalized = deepcopy(data)
meta = normalized.get("meta")
if isinstance(meta, dict):
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
meta[field] = _int_or_none(meta.get(field))
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
for institution in normalized.get("results") or []:
if not isinstance(institution, dict):
continue
for field in [
"id",
"ror",
"display_name",
"country_code",
"homepage_url",
"image_url",
"image_thumbnail_url",
"works_api_url",
]:
institution[field] = _str_or_none(institution.get(field))
institution_type = institution.get("type")
if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES:
institution["type"] = None
else:
institution["type"] = _str_or_none(institution_type)
institution["display_name_acronyms"] = _str_list_or_none(
institution.get("display_name_acronyms")
)
institution["display_name_alternatives"] = _str_list_or_none(
institution.get("display_name_alternatives")
)
institution["lineage"] = _str_list_or_none(institution.get("lineage"))
institution["works_count"] = _int_or_none(institution.get("works_count"))
institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count"))
institution["created_date"] = _date_str_or_none(institution.get("created_date"))
institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date"))
summary_stats = institution.get("summary_stats")
if isinstance(summary_stats, dict):
summary_stats["2yr_mean_citedness"] = _number_or_none(
summary_stats.get("2yr_mean_citedness")
)
summary_stats["h_index"] = _int_or_none(summary_stats.get("h_index"))
summary_stats["i10_index"] = _int_or_none(summary_stats.get("i10_index"))
geo = institution.get("geo")
if isinstance(geo, dict):
for field in [
"city",
"geonames_city_id",
"region",
"country_code",
"country",
]:
geo[field] = _str_or_none(geo.get(field))
geo["latitude"] = _number_or_none(geo.get("latitude"))
geo["longitude"] = _number_or_none(geo.get("longitude"))
ids = institution.get("ids")
if isinstance(ids, dict):
for field in ["openalex", "ror", "grid", "wikipedia", "wikidata"]:
ids[field] = _str_or_none(ids.get(field))
ids["mag"] = _int_or_none(ids.get("mag"))
for counts_by_year in institution.get("counts_by_year") or []:
if not isinstance(counts_by_year, dict):
continue
for field in ["year", "works_count", "cited_by_count"]:
counts_by_year[field] = _int_or_none(counts_by_year.get(field))
for group in normalized.get("group_by") or []:
if not isinstance(group, dict):
continue
group["key"] = _str_or_none(group.get("key"))
group["key_display_name"] = _str_or_none(group.get("key_display_name"))
group["count"] = _int_or_none(group.get("count"))
return normalized
def _str_or_none(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, bool):
return str(value).lower()
return str(value)
def _str_list_or_none(value: Any) -> list[str] | None:
if value is None:
return None
if not isinstance(value, list):
return None
return [_str_or_none(item) for item in value if item is not None]
def _int_or_none(value: Any) -> int | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(float(value))
except ValueError:
return None
return None
def _number_or_none(value: Any) -> int | float | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return value
if isinstance(value, str):
try:
number = float(value)
except ValueError:
return None
return int(number) if number.is_integer() else number
return None
def _date_str_or_none(value: Any) -> str | None:
text = _str_or_none(value)
if not text:
return None
return text[:10]
def _datetime_str_or_none(value: Any) -> str | None:
text = _str_or_none(value)
if not text:
return None
if len(text) == 10:
return f"{text}T00:00:00Z"
return text
@@ -0,0 +1,95 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for OpenAlex institutions.
"""
from typing import Any
import httpx
from .. import config
class OpenAlexInstitutionsClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds
self.transport = transport
def list_institutions_params(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
params: dict[str, Any] = {"per_page": per_page}
if search:
params["search"] = search
if filter:
params["filter"] = filter
if sort:
params["sort"] = sort
if group_by:
params["group_by"] = group_by
if cursor:
params["cursor"] = cursor
elif page is not None:
params["page"] = page
if sample is not None:
params["sample"] = sample
if select:
params["select"] = select
if self.api_key:
params["api_key"] = self.api_key
return params
async def list_institutions(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.get(
"/institutions",
params=self.list_institutions_params(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
),
)
response.raise_for_status()
return response.json()
@@ -0,0 +1,108 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex institutions.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags
from . import logic
router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS])
@router.get(
"/autocomplete",
operation_id="autocompleteInstitutions",
response_model=AutocompleteResponse,
response_model_exclude_none=True,
summary="Returns institution options for autocomplete inputs.",
)
async def autocomplete_institutions(
query: Annotated[
str,
Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1),
],
country_code: Annotated[
str | None,
Query(alias="countryCode", description="Optional ISO country code filter."),
] = None,
institution_type: Annotated[
str | None,
Query(alias="type", description="Optional institution type filter."),
] = None,
limit: Annotated[
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
):
return await logic.autocomplete_institutions(
query=query,
country_code=country_code,
institution_type=institution_type,
limit=limit,
)
@router.get(
"",
operation_id="listInstitutions",
response_model=InstitutionsListResponse,
response_model_exclude_none=True,
summary="Returns a list of OpenAlex institutions.",
)
async def list_institutions(
search: Annotated[
str | None,
Query(description="Full-text search, for example 'Duisburg Essen'."),
] = None,
filter: Annotated[
str | None,
Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."),
] = None,
sort: Annotated[
str | None,
Query(description="Sort field, for example 'works_count:desc'."),
] = "works_count:desc",
group_by: Annotated[
str | None,
Query(description="OpenAlex group_by field, for example 'country_code'."),
] = None,
per_page: Annotated[
int,
Query(description="Results per page.", ge=1, le=100),
] = 25,
page: Annotated[
int | None,
Query(description="Page number. Use cursor for deep pagination.", ge=1),
] = 1,
cursor: Annotated[
str | None,
Query(description="Cursor pagination token. Use '*' to start."),
] = None,
sample: Annotated[
int | None,
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
] = None,
select: Annotated[
str | None,
Query(description="Comma-separated fields to return."),
] = None,
):
return await logic.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
@@ -0,0 +1,236 @@
import httpx
import pytest
from fastapi import HTTPException
from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_list_institutions_maps_openalex_response_to_model():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
"homepage_url": "https://www.uni-due.de",
"image_url": "https://example.org/image.jpg",
"image_thumbnail_url": "https://example.org/thumb.jpg",
"display_name_acronyms": ["UDE"],
"display_name_alternatives": ["Universitaet Duisburg-Essen"],
"works_count": 123,
"cited_by_count": 456,
"summary_stats": {
"2yr_mean_citedness": 1.5,
"h_index": 42,
"i10_index": 99,
},
"geo": {
"city": "Duisburg",
"geonames_city_id": "2934691",
"region": "North Rhine-Westphalia",
"country_code": "DE",
"country": "Germany",
"latitude": 51.4344,
"longitude": 6.7623,
},
"lineage": ["https://openalex.org/I123"],
"ids": {
"openalex": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"mag": 123,
"grid": "grid.12345.6",
"wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen",
"wikidata": "https://www.wikidata.org/wiki/Q317070",
},
"counts_by_year": [
{
"year": 2024,
"works_count": 12,
"cited_by_count": 34,
}
],
"works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123",
"created_date": "2023-12-25",
"updated_date": "2023-11-07T05:31:56Z",
}
],
"group_by": [
{
"key": "DE",
"key_display_name": "Germany",
"count": 1,
}
],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.list_institutions(search="Duisburg Essen", client=client)
assert result.meta.count == 1
institution = result.results[0]
assert institution.display_name == "University of Duisburg-Essen"
assert institution.summary_stats.h_index == 42
assert institution.geo.country == "Germany"
assert institution.ids.mag == 123
assert institution.counts_by_year[0].year == 2024
assert result.group_by[0].key_display_name == "Germany"
@pytest.mark.anyio
async def test_list_institutions_rejects_sample_with_sort():
with pytest.raises(HTTPException) as exc_info:
await logic.list_institutions(sample=10, sort="works_count:desc")
assert exc_info.value.status_code == 400
@pytest.mark.anyio
async def test_list_institutions_accepts_practical_openalex_type_variants():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": 123,
"ror": 456,
"display_name": "Example Institute",
"country_code": 789,
"type": "unknown-openalex-type",
"display_name_acronyms": ["EI", 123],
"display_name_alternatives": "not-a-list",
"works_count": "12",
"cited_by_count": "34.0",
"summary_stats": {
"2yr_mean_citedness": "1.25",
"h_index": "10.0",
"i10_index": True,
},
"geo": {
"city": 123,
"geonames_city_id": 12345,
"latitude": "51.4",
"longitude": "6",
},
"ids": {"openalex": 123, "mag": "123"},
"counts_by_year": [
{
"year": "2024",
"works_count": "12.0",
"cited_by_count": False,
}
],
"created_date": "2023-12-25T10:11:12Z",
"updated_date": "2023-12-25",
}
],
"group_by": [{"key": True, "count": 1}],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.list_institutions(client=client)
assert result.results[0].id == "123"
assert result.results[0].ror == "456"
assert result.results[0].country_code == "789"
assert result.results[0].type is None
assert result.results[0].display_name_acronyms == ["EI", "123"]
assert result.results[0].display_name_alternatives is None
assert result.results[0].works_count == 12
assert result.results[0].cited_by_count == 34
assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25
assert result.results[0].summary_stats.h_index == 10
assert result.results[0].summary_stats.i10_index is None
assert result.results[0].geo.city == "123"
assert result.results[0].geo.geonames_city_id == "12345"
assert result.results[0].geo.latitude == 51.4
assert result.results[0].geo.longitude == 6
assert result.results[0].ids.openalex == "123"
assert result.results[0].ids.mag == 123
assert result.results[0].counts_by_year[0].year == 2024
assert result.results[0].counts_by_year[0].works_count == 12
assert result.results[0].counts_by_year[0].cited_by_count is None
assert result.group_by[0].key == "true"
@pytest.mark.anyio
async def test_autocomplete_institutions_returns_frontend_options():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["search"] == "Duisburg Essen"
assert request.url.params["filter"] == "country_code:DE,type:education"
assert request.url.params["sort"] == "works_count:desc"
assert request.url.params["per_page"] == "5"
assert request.url.params["select"] == (
"id,ror,display_name,country_code,type,works_count,"
"cited_by_count,geo"
)
return httpx.Response(
200,
json={
"meta": {"count": 1, "db_response_time_ms": 12},
"results": [
{
"id": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
"works_count": 123,
"cited_by_count": 456,
"geo": {
"city": "Duisburg",
"country": "Germany",
},
}
],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.autocomplete_institutions(
query="Duisburg Essen",
country_code="DE",
institution_type="education",
limit=5,
client=client,
)
assert result.meta.count == 1
assert result.meta.db_response_time_ms == 12
assert len(result.results) == 1
option = result.results[0]
assert option.id == "https://openalex.org/I123"
assert option.display_name == "University of Duisburg-Essen"
assert option.hint == "Duisburg · Germany · education"
assert option.works_count == 123
assert option.cited_by_count == 456
assert option.entity_type == "institution"
assert option.external_id == "https://ror.org/04mz5ra38"
@@ -0,0 +1,77 @@
import httpx
import pytest
from inse.institutions.search_client import OpenAlexInstitutionsClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def test_list_institutions_params_include_openalex_query_parameters():
client = OpenAlexInstitutionsClient(api_key="test-key")
params = client.list_institutions_params(
search="Duisburg Essen",
filter="country_code:DE,type:education",
sort="works_count:desc",
group_by="country_code",
per_page=10,
page=2,
select="id,display_name",
)
assert params == {
"search": "Duisburg Essen",
"filter": "country_code:DE,type:education",
"sort": "works_count:desc",
"group_by": "country_code",
"per_page": 10,
"page": 2,
"select": "id,display_name",
"api_key": "test-key",
}
def test_list_institutions_params_prefers_cursor_over_page():
client = OpenAlexInstitutionsClient(api_key="test-key")
params = client.list_institutions_params(cursor="*", page=3)
assert params["cursor"] == "*"
assert "page" not in params
@pytest.mark.anyio
async def test_list_institutions_calls_openalex_institutions_endpoint():
def handler(request: httpx.Request) -> httpx.Response:
assert request.method == "GET"
assert request.url.path == "/institutions"
assert request.url.params["search"] == "Duisburg Essen"
assert request.url.params["api_key"] == "test-key"
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": "https://openalex.org/I123",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
}
],
},
)
client = OpenAlexInstitutionsClient(
base_url="https://api.openalex.org",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await client.list_institutions(search="Duisburg Essen")
assert result["meta"]["count"] == 1
assert result["results"][0]["display_name"] == "University of Duisburg-Essen"
@@ -10,8 +10,10 @@ def search(
query: dict = None,
source = None,
size: int = None,
offset:int = None,
sort: list = None,
body: dict = None,
track_total_hits = False
) -> dict[str, Any]:
headers = {
@@ -27,8 +29,12 @@ def search(
payload["_source"] = source
if size is not None:
payload["size"] = size
if offset is not None:
payload["from"] = offset
if sort is not None:
payload["sort"] = sort
if track_total_hits:
payload["track_total_hits"] = True
else:
payload = {
"query": {
@@ -49,22 +55,23 @@ def search(
return response.json()
def get(
index: str,
doc_id:str,
body: dict = None,
doc_id: str,
source: list = None,
) -> dict[str, Any]:
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
payload = body
# get document directly
params = {}
if source is not None:
params["_source_includes"] = ",".join(source)
with httpx.Client() as client:
response = client.get(
f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}",
json=payload,
params=params,
headers=headers
)
response.raise_for_status()
+56 -205
View File
@@ -12,23 +12,14 @@ from typing import Type
from sqlalchemy.orm import Session
from sqlalchemy import select
from sqlalchemy import func
from fastapi import HTTPException
import logging
import httpx
import json
import time
from . import schema
from . import model
from . import config
from .integrations import elasticsearch
from .integrations import llm
from . import util
from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError
from inse.models.author import Author
from inse.models.authors_list_response import AuthorsListResponse
from inse.models.meta import Meta
from inse.models.topic import Topic
from inse.models.topic_subfield import TopicSubfield
from inse.models.topic_field import TopicField
@@ -38,20 +29,6 @@ from inse.models.topic_domain import TopicDomain
logger = logging.getLogger(__name__)
def _init_es_client() -> Optional[Elasticsearch]:
es_url = config.settings.elasticsearch_url
if not es_url:
logger.warning("Elasticsearch URL not configured; skipping client init.")
return None
client = Elasticsearch(
hosts=[str(es_url)],
api_key=config.settings.elasticsearch_api_key,
)
logger.info("Elasticsearch client initialized with URL: %s", es_url)
return client
es_client = _init_es_client()
topic_cache_filename: str = "topic_hierarchy_cache.json"
@@ -113,8 +90,12 @@ def insert_element(db: Session, value: S) -> S:
def _load_topic_cache() -> dict:
"""Loads the topic hierarchy cache from a JSON file."""
import os
try:
cache_path = "/data/" + topic_cache_filename
if not os.path.exists(cache_path):
current_dir = os.path.dirname(__file__)
cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename)
with open(cache_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as exc:
@@ -250,186 +231,56 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
return counts
### persons
def search_persons(
author_id: Optional[str] = None,
query: Optional[str] = None,
include: Optional[set[str]] = None,
) -> AuthorsListResponse:
if author_id:
query_field = "_id"
query_value = author_id
elif query:
query_field = "display_name"
query_value = query
else:
return AuthorsListResponse(results=[], meta=Meta(count=0))
data = elasticsearch.search(
index="openalex-authors", query_field=query_field, query_value=query_value
)
authors = []
for hit in data.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = source_copy.get("id") or hit.get("_id", "")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = dict(ids)
for str_field in ["openalex", "orcid", "scopus"]:
val = ids_copy.get(str_field)
if val is not None and not isinstance(val, str):
ids_copy[str_field] = str(val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
if author:
authors.append(author)
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
start_time = time.time()
search_result = search_persons(author_id=author_id)
if not search_result.results:
return "No person found."
if len(search_result.results) > 1:
return "Multiple persons found, cannot generate bio."
person = search_result.results[0]
person_json = json.dumps(person.model_dump_json())
system_prompt = """\
Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person.
Gehe dabei auf folgende drei Punkte ein:
1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema)
2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung?
3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend?
Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\
def get_topic_hierarchy() -> dict:
"""
user_prompt = f"Daten zur Person:\n{person_json}"
bio = llm.call(system_prompt, user_prompt)
elapsed_time = time.time() - start_time
logger.info(
f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds"
)
return bio
def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse:
body = {
"_source":include.split(",") if include else True,
}
try:
hit = elasticsearch.get(
index="openalex-authors",
body=body,
doc_id=author_id
)
except NotFoundError:
raise HTTPException(
status_code=404, detail=f"Person with id {author_id} not found"
)
except ApiError as e:
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
persons = [util.get_persons_data(hit)]
return AuthorsListResponse(results=persons)
def search_persons_by_name(
author_name: str, limit: Optional[int] = 10, include: Optional[str] = None
) -> AuthorsListResponse:
if not author_name:
raise HTTPException(status_code=400, detail="name must be provided")
search_query = {
"bool": {
"should": [
{"match_phrase": {"display_name": {"query": author_name, "boost": 5}}},
{
"match_phrase_prefix": {
"display_name": {"query": author_name, "boost": 3}
}
},
# {
# "match": {
# "display_name": {
# "query": author_name,
# "fuzziness": 1
# }
# }
# }
],
"minimum_should_match": 1,
}
}
try:
response = elasticsearch.search(
index="openalex-authors",
query=search_query,
source=include.split(",") if include else True,
size=limit,
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
return AuthorsListResponse(results=persons)
def search_persons_by_institution(
institution_name: str, limit: Optional[int] = 10, include: Optional[str] = None
) -> AuthorsListResponse:
if not institution_name:
raise HTTPException(status_code=400, detail="institution_name must be provided")
search_query = {
"nested": {
"path": "affiliations",
"query": {
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
}
}
try:
response = elasticsearch.search(
index="openalex-authors",
query=search_query,
source=include.split(",") if include else True,
size=limit,
sort=[{"works_count": {"order": "desc"}}],
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
return AuthorsListResponse(results=persons)
Builds and returns a hierarchical tree structure of topics:
Domains -> Fields -> Subfields -> Topics
"""
flat_cache = _load_topic_cache()
tree = {}
for topic_name, info in flat_cache.items():
domain = info.get("domain") or "Unbekannter Bereich"
field = info.get("field") or "Unbekanntes Feld"
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
topic_id = info.get("topic_id", "")
# Clean topic ID to just be the trailing ID or keep full URL
# For querying, display name is used in persons search, but ID is useful
if domain not in tree:
tree[domain] = {}
if field not in tree[domain]:
tree[domain][field] = {}
if subfield not in tree[domain][field]:
tree[domain][field][subfield] = []
tree[domain][field][subfield].append({
"id": topic_id,
"name": topic_name
})
formatted_domains = []
for d_name, d_fields in tree.items():
formatted_fields = []
for f_name, f_subfields in d_fields.items():
formatted_subfields = []
for sf_name, sf_topics in f_subfields.items():
sf_topics.sort(key=lambda x: x["name"])
formatted_subfields.append({
"name": sf_name,
"topics": sf_topics
})
formatted_subfields.sort(key=lambda x: x["name"])
formatted_fields.append({
"name": f_name,
"subfields": formatted_subfields
})
formatted_fields.sort(key=lambda x: x["name"])
formatted_domains.append({
"name": d_name,
"fields": formatted_fields
})
formatted_domains.sort(key=lambda x: x["name"])
return {"domains": formatted_domains}
+8 -2
View File
@@ -11,8 +11,11 @@ from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from inse.collaboration_network.router import router as collaboration_network_router
from inse.institutions.service import router as institutions_service_router
from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.search.service import router as search_router
from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
from . import config
from .service import router as service_router
@@ -32,8 +35,11 @@ app = FastAPI(
servers=settings.servers,
)
app.include_router(collaboration_network_router)
app.include_router(institutions_service_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(search_router)
app.include_router(persons_service_router)
app.include_router(funders_service_router)
app.include_router(service_router)
app.include_router(account_router)
-3
View File
@@ -36,8 +36,5 @@ class Page(BaseModel, Generic[T]):
class ItemPage(Page[Item]):
pass
class PersonBio(BaseModel):
bio: str = Field(description="The generated biography.")
@@ -1,6 +1,9 @@
from typing import Optional
from pydantic import BaseModel, Field
class TopicCount(BaseModel):
id: Optional[str] = Field(default=None, description="The topic id.")
name: str = Field(description="The topic display name.")
count: int = Field(default=0, description="The number of occurrences.")
+435
View File
@@ -0,0 +1,435 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for persons / authors.
"""
import json
import logging
import time
from typing import Optional, Callable, Any, List
import hashlib
import httpx
from fastapi import HTTPException
from .. import config
from .. import util
from ..integrations import llm
from inse.models.author import Author
from inse.models.authors_list_response import AuthorsListResponse
from inse import util
from inse.integrations import elasticsearch
from inse.models.meta import Meta
from inse.persons.query_builder import build_authors_search
from inse.persons.model import CustomAuthor, CustomAuthorsListResponse, PersonSearchRequest
logger = logging.getLogger(__name__)
INDEX_NAME="openalex-authors"
def search_persons(
author_id: Optional[str] = None,
query: Optional[str] = None,
include: Optional[set[str]] = None,
) -> AuthorsListResponse:
if author_id:
query_field = "_id"
query_value = author_id
elif query:
query_field = "display_name"
query_value = query
else:
return AuthorsListResponse(results=[], meta=Meta(count=0))
data = elasticsearch.search(
index="openalex-authors", query_field=query_field, query_value=query_value
)
authors = []
for hit in data.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = source_copy.get("id") or hit.get("_id", "")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
if author:
authors.append(author)
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
start_time = time.time()
search_result = search_persons(author_id=author_id)
if not search_result.results:
return "No person found."
if len(search_result.results) > 1:
return "Multiple persons found, cannot generate bio."
person = search_result.results[0]
person_json = json.dumps(person.model_dump_json())
system_prompt = """\
Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person.
Gehe dabei auf folgende drei Punkte ein:
1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema)
2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung?
3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend?
Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\
"""
user_prompt = f"Daten zur Person:\n{person_json}"
bio = llm.call(system_prompt, user_prompt)
elapsed_time = time.time() - start_time
logger.info(
f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds"
)
return bio
def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse:
body = {
"_source":include.split(",") if include else True,
}
try:
hit = elasticsearch.get(
index="openalex-authors",
body=body,
doc_id=author_id
)
except NotFoundError:
raise HTTPException(
status_code=404, detail=f"Person with id {author_id} not found"
)
except ApiError as e:
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
persons = [util.get_persons_data(hit)]
return AuthorsListResponse(results=persons)
def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse:
body = {
"_source":include.split(",") if include else True,
}
try:
hit = elasticsearch.get(
index="openalex-authors",
body=body,
doc_id=author_id
)
except NotFoundError:
raise HTTPException(
status_code=404, detail=f"Person with id {author_id} not found"
)
except ApiError as e:
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
persons = [util.get_persons_data(hit)]
return AuthorsListResponse(results=persons)
def search_persons_by_name(
author_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None
) -> AuthorsListResponse:
if not author_name:
raise HTTPException(status_code=400, detail="name must be provided")
search_query = {
"bool": {
"should": [
{"match_phrase": {"display_name": {"query": author_name, "boost": 5}}},
{
"match_phrase_prefix": {
"display_name": {"query": author_name, "boost": 3}
}
},
# {
# "match": {
# "display_name": {
# "query": author_name,
# "fuzziness": 1
# }
# }
# }
],
"minimum_should_match": 1,
}
}
try:
response = elasticsearch.search(
index="openalex-authors",
query=search_query,
offset=page_offset,
source=include.split(",") if include else True,
size=limit,
track_total_hits=True
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
total_count = response.get("hits",{}).get("total",{}).get("value",0)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
return AuthorsListResponse(results=persons,meta=Meta(count=total_count,page=page_offset))
def search_persons_autocomplete(author_name: str, limit: Optional[int] = 5, include: Optional[str] = None) -> AuthorsListResponse:
if not author_name:
raise HTTPException(
status_code=400,
detail="name must be provided"
)
search_query = {
"function_score": {
"query": {
"wildcard": {
"display_name.keyword": {
"value": author_name + "*",
"case_insensitive": True
}
}
},
"functions": [
{
"script_score": {
"script": {
"lang": "painless",
"source": "String name = doc['display_name.keyword'].value.toLowerCase(); String[] parts = name.splitOnToken(' '); Set unique = new HashSet(); for (String p : parts) { unique.add(p); } return unique.size() > 1 ? 1.0 : 0.3;"
}
}
}
],
"boost_mode": "multiply"
}
}
collapse ={
"field":"display_name.keyword"
}
body = {
"size":limit,
"query":search_query,
"_source":include.split(",") if include else True,
"sort":[{"works_count": {"order": "desc"}}],
"collapse":collapse
}
try:
response = elasticsearch.search(
index="openalex-authors",
body=body
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Elasticsearch search failed: {str(e)}"
)
hits = response.get("hits", {}).get("hits", [])
persons = []
for hit in hits:
fields = hit.get("fields",{})
source = hit.get("_source",{})
source_copy = dict (source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
for key,value in fields.items():
source_copy[key] = value
author = Author.from_dict(source_copy)
persons.append(author)
return AuthorsListResponse(results=persons)
def search_persons_by_institution(
institution_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None
) -> AuthorsListResponse:
if not institution_name:
raise HTTPException(status_code=400, detail="institution_name must be provided")
search_query = {
"nested": {
"path": "last_known_institutions",
"query": {
"bool": {
"must": [
{
"match_phrase": {
"last_known_institutions.display_name": institution_name
}
}
]
}
}
}
}
try:
response = elasticsearch.search(
index="openalex-authors",
query=search_query,
source=include.split(",") if include else True,
size=limit,
offset=page_offset,
sort=[{"works_count": {"order": "desc"}}],
track_total_hits=True
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
total_count = response.get("hits",{}).get("total",{}).get("value",0)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
return AuthorsListResponse(results=persons,meta=Meta(count=total_count,page=page_offset))
def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
if not author_data:
return None
if not isinstance(author_data, dict):
if hasattr(author_data, 'model_dump'):
author_data = author_data.model_dump()
elif hasattr(author_data, 'to_dict'):
author_data = author_data.to_dict()
else:
return None
author_id = author_data.get("id", "") or ""
# Not implemented yet
h = int(hashlib.md5(author_id.encode('utf-8')).hexdigest(), 16)
# Experimental suitability rating
suitability_score = h % 100
if suitability_score < 15:
relevance_rating = "Sehr geeignet"
elif suitability_score < 50:
relevance_rating = "Geeignet"
else:
relevance_rating = "Möglich"
# Resilient sanitization of IDs to protect against model type conflicts (Generated) TODO: multiple code occurrences (e.g. in util.py) => refactor into seperate utility function (if required, after all merges)
ids = author_data.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
author_data["ids"] = ids_copy
base_author = Author.from_dict(author_data)
if not base_author:
return None
author = CustomAuthor(
**base_author.model_dump(),
relevance_rating=relevance_rating,
)
return author
def advanced_search_persons(
query: Optional[str] = None,
institution_name: Optional[str] = None,
topics: Optional[List[str]] = None,
page: int = 1,
page_size: int = 10,
include: Optional[set[str]] = None,
strict: Optional[bool] = False,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None,
) -> CustomAuthorsListResponse:
try:
query_body = build_authors_search(
query=query,
institution_name=institution_name,
topics=topics,
page=page,
page_size=page_size,
include=include,
strict=strict,
track_total_hits = True,
filter_mode=filter_mode,
filter_year=filter_year
)
response_dict = elasticsearch.search(
index=INDEX_NAME,
body=query_body,
)
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
return CustomAuthorsListResponse(
results=[],
meta=Meta(
count=0,
page=page,
per_page=page_size
)
)
elif e.response.status_code == 400:
logger.error(f"Elasticsearch request error: {str(e)}")
raise HTTPException(
status_code=400, detail=f"Elasticsearch request error: {str(e)}"
)
else:
logger.error(f"Elasticsearch API error: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Elasticsearch API error: {str(e)}"
)
except httpx.RequestError as e:
logger.error(f"Elasticsearch connection/request error: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}"
)
except Exception as e:
logger.error(f"Elasticsearch search failed: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
total_count = response_dict.get("hits",{}).get("total",{}).get("value",0)
hits = response_dict.get("hits", {}).get("hits", [])
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
results = []
for hit in hits:
raw_data = util.get_persons_data(hit)
custom_author = _enrich_author_data(raw_data)
if custom_author:
results.append(custom_author)
return CustomAuthorsListResponse(
results=results,
meta=Meta(
count=total_count,
page=page,
per_page=page_size
)
)
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data models for persons / authors.
"""
from pydantic import BaseModel
from pydantic import Field
from typing import List, Optional
from inse.models.author import Author
from inse.models.meta import Meta
from inse.models.authors_list_response import AuthorsListResponse
from inse.models.group_by_result import GroupByResult
class CustomAuthor(Author):
relevance_rating: Optional[str] = Field(default=None, description="The relevance suitability rating.")
class CustomAuthorsListResponse(AuthorsListResponse):
pass
#meta: Optional[Meta] = None
#results: Optional[List[CustomAuthor]] = None
#group_by: Optional[List[GroupByResult]] = None
class PersonBio(BaseModel):
bio: str = Field(description="The generated biography.")
class PersonFilters(BaseModel):
institution: Optional[str] = None
cited_by_count: Optional[int] = None
# more filters
class PersonSearchRequest(BaseModel):
name: Optional[str] = None
filters: PersonFilters = PersonFilters()
include: Optional[str] = None
limit: Optional[int] = 10
page_offset: Optional[int] = 0
@@ -0,0 +1,230 @@
# -*- coding: utf-8 -*-
from typing import List, Optional, Set, Any
def build_authors_search(
using: Any = None,
index: Optional[str] = None,
query: Optional[str] = None,
institution_name: Optional[str] = None,
topics: Optional[List[str]] = None,
page: int = 1,
page_size: int = 10,
include: Optional[Set[str]] = None,
strict: Optional[bool] = False,
track_total_hits: Optional[bool] = False,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None
) -> dict:
"""
Builds an Elasticsearch search request query body for authors as a dictionary.
"""
# 1. Build Query Clauses
query_clause = None
if query:
query_clause = {
"bool": {
"should": [
{
"match_phrase": {
"display_name": {
"query": query,
"boost": 5
}
}
},
{
"match_phrase_prefix": {
"display_name": {
"query": query,
"boost": 3
}
}
},
{
"match": {
"display_name": {
"query": query,
"fuzziness": 1
}
}
}
],
"minimum_should_match": 1
}
}
# 2. Build Filters
filter_clauses = []
# Filter against false entries (nested ((Works > 2 AND Year > 2020) OR has last_known_institution))
filter_clauses.append({
"bool": {
"should": [
{
"bool": {
"filter": [
{
"range": { "works_count": { "gt": 2 } }
},
{
"nested": {
"path": "counts_by_year",
"query": {
"range": { "counts_by_year.year": { "gt": 2020 } } # hardcoded for now
}
}
}
]
}
},
{
"nested": {
"path": "last_known_institutions",
"query": {
"exists": {
"field": "last_known_institutions.id"
}
}
}
}
],
"minimum_should_match": 1
}
})
# Institution filter with optional year-based filtering
if institution_name:
if filter_year is not None:
target_year = filter_year
mode = filter_mode or "from"
else:
from datetime import datetime
current_year = datetime.now().year
target_year = current_year - 1
mode = "from"
range_query = {"gte": target_year}
if mode == "in":
range_query["lte"] = target_year
if strict:
filter_clauses.append({
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
{
"range": {
"affiliations.years": range_query
}
}
]
}
}
}
})
else:
filter_clauses.append({
"bool": {
"filter": [
{
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.display_name": institution_name
}
}
}
},
{
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
{
"range": {
"affiliations.years": range_query
}
}
]
}
}
}
}
]
}
})
if topics:
for t in topics:
if t:
filter_clauses.append({
"nested": {
"path": "topics",
"query": {
"match_phrase": {
"topics.display_name": t
}
}
}
})
# Combine query and filters
body = {}
if query_clause:
if filter_clauses:
body["query"] = {
"bool": {
"must": [query_clause],
"filter": filter_clauses
}
}
else:
body["query"] = query_clause
else:
if filter_clauses:
body["query"] = {
"bool": {
"filter": filter_clauses
}
}
else:
body["query"] = {
"match_all": {}
}
# 3. Source Filtering
if include:
body["_source"] = list(include)
else:
body["_source"] = True
# 4. Pagination
es_size = page_size
es_from = (page - 1) * page_size
body["from"] = es_from
body["size"] = es_size
body["track_total_hits"] = track_total_hits
# 5. Sorting
if not query:
body["sort"] = [
{"cited_by_count": {"order": "desc"}},
{"works_count": {"order": "desc"}}
]
return body
+234
View File
@@ -0,0 +1,234 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for persons / authors.
"""
from typing import Annotated, Optional
from fastapi import APIRouter
from fastapi import Path
from fastapi import Query
from typing import List
from . import logic
from . import model
from inse.models.authors_list_response import AuthorsListResponse
router = APIRouter(
prefix="/api/inse-service",
tags=["Persons"],
responses={404: {"description": "Not found"}},
)
@router.get(
"/persons/search",
operation_id="searchPersons",
response_model=AuthorsListResponse,
summary="Searches for persons by ID or name.",
response_model_exclude_none=True,
)
def search_persons(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
] = None,
query: Annotated[
str, Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
include: Annotated[
Optional[str],
Query(
description=(
"Comma-separated include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, sources, counts_by_year, works_api_url, dates, "
"cited_by_count_boost"
),
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
return logic.search_persons(author_id, query, include_set)
@router.get(
"/persons/bio",
operation_id="generatePersonBio",
response_model=model.PersonBio,
summary="Generates a bio for a person by author ID.",
)
def generate_person_bio(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
],
include: Annotated[
Optional[str],
Query(
description=("Comma-separated list to include tags"),
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
bio = logic.generate_person_bio(author_id, include_set)
return model.PersonBio(bio=bio)
@router.get(
"/person/{id}",
operation_id="getPersonByID",
response_model=AuthorsListResponse,
summary="Searches for person by ID.",
tags=["Persons"],
)
def get_person_by_id(
id: Annotated[
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
):
return logic.get_person_by_id(author_id=id, include=include)
@router.get(
"/persons/searchByName",
operation_id="searchPersonsByName",
response_model=AuthorsListResponse,
summary="Searches for person by name.",
tags=["Persons"],
)
def search_persons_by_name(
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
):
return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
@router.get(
'/persons/autocomplete',
operation_id='searchPersonsAutocomplete',
response_model=AuthorsListResponse,
summary='Searches for person by name.',
tags=[ 'Persons' ])
def search_persons_autocomplete(
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
include : Annotated[Optional[str], Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share"
)]):
return logic.search_persons_autocomplete(author_name=author_name,include=include)
@router.get(
"/persons/searchByInstitution",
operation_id="searchPersonsByInstitution",
response_model=AuthorsListResponse,
summary="Searches for persons by institution name.",
tags=["Persons"],
)
def search_persons_by_institution(
institution_name: Annotated[
str, Query(description="Institution name (e.g., MIT, Oxford University)")
],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
):
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
@router.get(
"/persons/search-list",
operation_id="searchPersonsList",
response_model=model.CustomAuthorsListResponse,
summary="Searches for persons with advanced filters (Topic & Institution) and pagination.",
response_model_exclude_none=True,
tags=["Persons"],
)
def search_persons_list(
query: Annotated[
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
institution_name: Annotated[
Optional[str], Query(alias="institutionName", description="Filter by institution name")
] = None,
topic: Annotated[
Optional[List[str]], Query(description="Filter by topic display names")
] = None,
page: Annotated[
int, Query(description="Page number (1-indexed)", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Results per page", ge=1, le=100)
] = 10,
include: Annotated[
Optional[str],
Query(
description="Comma-separated include tags",
example="topics_full,topic_share",
),
] = None,
strict: Annotated[
Optional[bool], Query(description="Strict institution search by target year")
] = False,
filter_mode: Annotated[
Optional[str], Query(alias="filterMode", description="Filter mode: 'in' or 'from'")
] = "from",
filter_year: Annotated[
Optional[int], Query(alias="filterYear", description="Filter year")
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
return logic.advanced_search_persons(
query=query,
institution_name=institution_name,
topics=topic,
page=page,
page_size=page_size,
include=include_set,
strict=strict,
filter_mode=filter_mode,
filter_year=filter_year,
)
-1
View File
@@ -1 +0,0 @@
# -*- coding: utf-8 -*-
-153
View File
@@ -1,153 +0,0 @@
# -*- coding: utf-8 -*-
import logging
import hashlib
from typing import List, Optional
from fastapi import HTTPException
from inse import util
from inse.logic import es_client
from inse.models.author import Author
from inse.models.meta import Meta
from inse.search.model import CustomAuthor, CustomAuthorsListResponse
logger = logging.getLogger(__name__)
def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
if not author_data:
return None
if not isinstance(author_data, dict):
if hasattr(author_data, 'model_dump'):
author_data = author_data.model_dump()
elif hasattr(author_data, 'to_dict'):
author_data = author_data.to_dict()
else:
return None
author_id = author_data.get("id", "") or ""
h = int(hashlib.md5(author_id.encode('utf-8')).hexdigest(), 16)
# Experimental suitability rating
suitability_score = h % 100
if suitability_score < 15:
relevance_rating = "Sehr geeignet"
elif suitability_score < 50:
relevance_rating = "Geeignet"
else:
relevance_rating = "Möglich"
# Resilient sanitization of IDs to protect against model type conflicts (Generated)
ids = author_data.get("ids")
if isinstance(ids, dict):
ids_copy = dict(ids)
for str_field in ["openalex", "orcid", "scopus"]:
val = ids_copy.get(str_field)
if val is not None and not isinstance(val, str):
ids_copy[str_field] = str(val)
author_data["ids"] = ids_copy
base_author = Author.from_dict(author_data)
if not base_author:
return None
author = CustomAuthor(
**base_author.model_dump(),
relevance_rating=relevance_rating,
)
return author
def advanced_search_persons(
query: Optional[str] = None,
institution_name: Optional[str] = None,
topics: Optional[List[str]] = None,
page: int = 1,
page_size: int = 10,
include: Optional[set[str]] = None,
) -> CustomAuthorsListResponse:
must_clauses = []
filter_clauses = []
if query:
must_clauses.append({
"bool": {
"should": [
{"match_phrase": {"display_name": {"query": query, "boost": 5}}},
{"match_phrase_prefix": {"display_name": {"query": query, "boost": 3}}},
{"match": {"display_name": {"query": query, "fuzziness": 1}}},
],
"minimum_should_match": 1
}
})
if institution_name:
filter_clauses.append({
"nested": {
"path": "affiliations",
"query": {
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
}
}
})
if topics:
for t in topics:
if t:
filter_clauses.append({
"nested": {
"path": "topics",
"query": {
"match_phrase": {
"topics.display_name": t
}
}
}
})
query_body = {"bool": {}}
if must_clauses:
query_body["bool"]["must"] = must_clauses
if filter_clauses:
query_body["bool"]["filter"] = filter_clauses
if not must_clauses and not filter_clauses:
query_body["bool"]["must"] = [{"match_all": {}}]
es_size = page_size
es_from = (page - 1) * page_size
sort_option = [{"cited_by_count": {"order": "desc"}}, {"works_count": {"order": "desc"}}]
try:
response = es_client.search(
index="openalex-authors",
query=query_body,
source=list(include) if include else True,
from_=es_from,
size=es_size,
sort=sort_option if not query else None,
)
except Exception as e:
logger.error(f"Elasticsearch search failed: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
hits = response.get("hits", {}).get("hits", [])
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
results = []
for hit in hits:
raw_data = util.get_persons_data(hit)
custom_author = _enrich_author_data(raw_data)
if custom_author:
results.append(custom_author)
return CustomAuthorsListResponse(
results=results,
meta=Meta(
count=total_count,
page=page,
per_page=page_size
)
)
-14
View File
@@ -1,14 +0,0 @@
# -*- coding: utf-8 -*-
from pydantic import BaseModel, Field
from typing import List, Optional
from inse.models.author import Author
from inse.models.meta import Meta
from inse.models.group_by_result import GroupByResult
class CustomAuthor(Author):
relevance_rating: Optional[str] = Field(default=None, description="The relevance suitability rating.")
class CustomAuthorsListResponse(BaseModel):
meta: Optional[Meta] = None
results: Optional[List[CustomAuthor]] = None
group_by: Optional[List[GroupByResult]] = None
-62
View File
@@ -1,62 +0,0 @@
# -*- coding: utf-8 -*-
import logging
from typing import Annotated, List, Optional
from fastapi import APIRouter, Query, Depends
from inse import database
from inse.search import model as search_model
from inse.search import logic
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="/api/inse-service",
tags=["Persons Search"],
responses={404: {"description": "Not found"}},
)
@router.get(
"/persons/search-list",
operation_id="searchPersonsList",
response_model=search_model.CustomAuthorsListResponse,
summary="Searches for persons with advanced filters (Topic & Institution) and pagination.",
response_model_exclude_none=True,
tags=["Persons"],
)
def search_persons_list(
query: Annotated[
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
institution_name: Annotated[
Optional[str], Query(alias="institutionName", description="Filter by institution name")
] = None,
topic: Annotated[
Optional[List[str]], Query(description="Filter by topic display names")
] = None,
page: Annotated[
int, Query(description="Page number (1-indexed)", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Results per page", ge=1, le=100)
] = 10,
include: Annotated[
Optional[str],
Query(
description="Comma-separated include tags",
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
return logic.advanced_search_persons(
query=query,
institution_name=institution_name,
topics=topic,
page=page,
page_size=page_size,
include=include_set,
)
+7 -139
View File
@@ -27,9 +27,7 @@ from . import schema
from . import database
from . import security
from . import util
from .works import service as works_service
from inse.models.authors_list_response import AuthorsListResponse
logger = logging.getLogger(__name__)
@@ -44,7 +42,6 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
)
# @app.get("/", include_in_schema=False)
# async def show_api():
# return RedirectResponse("api")
@@ -212,141 +209,12 @@ def count_topic_hierarchy(
):
return logic.count_topic_hierarchy(topic_names)
### persons
@router.get(
"/persons/search",
operation_id="searchPersons",
response_model=AuthorsListResponse,
summary="Searches for persons by ID or name.",
response_model_exclude_none=True,
tags=["Persons"],
"/topics/hierarchy",
operation_id="getTopicHierarchy",
response_model=dict,
summary="Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).",
tags=["Topics"],
)
def search_persons(
author_id: Annotated[
Optional[str], Query(description="OpenAlex author ID (e.g., A5093075883)")
] = None,
query: Annotated[
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
include: Annotated[
Optional[str],
Query(
description=(
"Comma-separated include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, sources, counts_by_year, works_api_url, dates, "
"cited_by_count_boost"
),
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
return logic.search_persons(author_id, query, include_set)
@router.get(
"/persons/bio",
operation_id="generatePersonBio",
response_model=model.PersonBio,
summary="Generates a bio for a person by author ID.",
tags=["Persons"],
)
def generate_person_bio(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
],
include: Annotated[
Optional[str],
Query(
description=("Comma-separated list to include tags"),
example="topics_full,topic_share",
),
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
if include
else None
)
bio = logic.generate_person_bio(author_id, include_set)
return model.PersonBio(bio=bio)
@router.get(
"/person/{id}",
operation_id="getPersonByID",
response_model=AuthorsListResponse,
summary="Searches for person by ID.",
tags=["Persons"],
)
def get_person_by_id(
id: Annotated[
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
):
return logic.get_person_by_id(author_id=id, include=include)
@router.get(
"/persons/searchByName",
operation_id="searchPersonsByName",
response_model=AuthorsListResponse,
summary="Searches for person by name.",
tags=["Persons"],
)
def search_persons_by_name(
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
):
return logic.search_persons_by_name(author_name=author_name, include=include)
@router.get(
"/persons/searchByInstitution",
operation_id="searchPersonsByInstitution",
response_model=AuthorsListResponse,
summary="Searches for persons by institution name.",
tags=["Persons"],
)
def search_persons_by_institution(
institution_name: Annotated[
str, Query(description="Institution name (e.g., MIT, Oxford University)")
],
include: Annotated[
Optional[str],
Query(
description=(
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
"last_known_institutions, ..."
),
example="topics_full,topic_share",
),
],
):
return logic.search_persons_by_institution(institution_name, include=include)
def get_topic_hierarchy():
return logic.get_topic_hierarchy()
+3 -1
View File
@@ -4,4 +4,6 @@ from enum import Enum
class Tags(Enum):
PERSON = "Person"
PERSON_NETWORK = "Person Network"
WORKS = "Works"
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
OpenAlex topics module.
"""
+257
View File
@@ -0,0 +1,257 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for OpenAlex topics.
"""
import logging
from copy import deepcopy
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import (
AutocompleteResponseResultsInner,
)
from inse.models.topics_list_response import TopicsListResponse
from .search_client import OpenAlexTopicsClient
logger = logging.getLogger(__name__)
async def list_topics(
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
client: OpenAlexTopicsClient | None = None,
) -> TopicsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
openalex_client = client or OpenAlexTopicsClient()
try:
data = await openalex_client.list_topics(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
except httpx.HTTPStatusError as exc:
status_code = exc.response.status_code
detail = "OpenAlex topics request failed."
try:
error_body = exc.response.json()
detail = error_body.get("message") or error_body.get("error") or detail
except ValueError:
if exc.response.text:
detail = exc.response.text
raise HTTPException(status_code=status_code, detail=detail) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex topics request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex topics request failed.",
) from exc
try:
normalized_data = _normalize_topics_response(data)
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("OpenAlex topics response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex topics response could not be parsed.",
) from exc
async def autocomplete_topics(
*,
query: str,
domain_id: str | None = None,
field_id: str | None = None,
subfield_id: str | None = None,
limit: int = 10,
client: OpenAlexTopicsClient | None = None,
) -> AutocompleteResponse:
filters = []
if domain_id:
filters.append(f"domain.id:{domain_id}")
if field_id:
filters.append(f"field.id:{field_id}")
if subfield_id:
filters.append(f"subfield.id:{subfield_id}")
response = await list_topics(
search=query,
filter=",".join(filters) if filters else None,
sort="works_count:desc",
per_page=limit,
page=1,
select=(
"id,display_name,description,keywords,subfield,field,domain,"
"works_count,cited_by_count,ids"
),
client=client,
)
results = []
for topic in response.results or []:
if not topic.id or not topic.display_name:
continue
hint_parts = []
if topic.var_field and topic.var_field.display_name:
hint_parts.append(topic.var_field.display_name)
if topic.subfield and topic.subfield.display_name:
hint_parts.append(topic.subfield.display_name)
if topic.domain and topic.domain.display_name:
hint_parts.append(topic.domain.display_name)
results.append(
AutocompleteResponseResultsInner(
id=topic.id,
display_name=topic.display_name,
hint=" · ".join(hint_parts) if hint_parts else topic.description,
cited_by_count=topic.cited_by_count,
works_count=topic.works_count,
entity_type="topic",
external_id=topic.ids.openalex if topic.ids else None,
)
)
return AutocompleteResponse(
meta=AutocompleteResponseMeta(
count=response.meta.count if response.meta else len(results),
db_response_time_ms=(
response.meta.db_response_time_ms if response.meta else None
),
),
results=results,
)
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
normalized = deepcopy(data)
meta = normalized.get("meta")
if isinstance(meta, dict):
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
meta[field] = _int_or_none(meta.get(field))
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
for topic in normalized.get("results") or []:
if not isinstance(topic, dict):
continue
for field in ["id", "display_name", "description", "works_api_url"]:
topic[field] = _str_or_none(topic.get(field))
topic["keywords"] = _str_list_or_none(topic.get("keywords"))
topic["works_count"] = _int_or_none(topic.get("works_count"))
topic["cited_by_count"] = _int_or_none(topic.get("cited_by_count"))
topic["created_date"] = _date_str_or_none(topic.get("created_date"))
topic["updated_date"] = _datetime_str_or_none(topic.get("updated_date"))
for relation_field in ["subfield", "field", "domain"]:
relation = topic.get(relation_field)
if not isinstance(relation, dict):
continue
relation["id"] = _str_or_none(relation.get("id"))
relation["display_name"] = _str_or_none(relation.get("display_name"))
ids = topic.get("ids")
if isinstance(ids, dict):
for field in ["openalex", "wikipedia"]:
ids[field] = _str_or_none(ids.get(field))
for group in normalized.get("group_by") or []:
if not isinstance(group, dict):
continue
group["key"] = _str_or_none(group.get("key"))
group["key_display_name"] = _str_or_none(group.get("key_display_name"))
group["count"] = _int_or_none(group.get("count"))
return normalized
def _str_or_none(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, bool):
return str(value).lower()
return str(value)
def _str_list_or_none(value: Any) -> list[str] | None:
if value is None:
return None
if not isinstance(value, list):
return None
return [_str_or_none(item) for item in value if item is not None]
def _int_or_none(value: Any) -> int | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(float(value))
except ValueError:
return None
return None
def _number_or_none(value: Any) -> int | float | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return value
if isinstance(value, str):
try:
number = float(value)
except ValueError:
return None
return int(number) if number.is_integer() else number
return None
def _date_str_or_none(value: Any) -> str | None:
text = _str_or_none(value)
if not text:
return None
return text[:10]
def _datetime_str_or_none(value: Any) -> str | None:
text = _str_or_none(value)
if not text:
return None
if len(text) == 10:
return f"{text}T00:00:00Z"
return text
@@ -0,0 +1,99 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for OpenAlex topics.
"""
from typing import Any
import httpx
from .. import config
class OpenAlexTopicsClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
self.timeout = (
timeout
if timeout is not None
else config.settings.openalex_api_timeout_seconds
)
self.transport = transport
def list_topics_params(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
params: dict[str, Any] = {"per_page": per_page}
if search:
params["search"] = search
if filter:
params["filter"] = filter
if sort:
params["sort"] = sort
if group_by:
params["group_by"] = group_by
if cursor:
params["cursor"] = cursor
elif page is not None:
params["page"] = page
if sample is not None:
params["sample"] = sample
if select:
params["select"] = select
if self.api_key:
params["api_key"] = self.api_key
return params
async def list_topics(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.get(
"/topics",
params=self.list_topics_params(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
),
)
response.raise_for_status()
return response.json()
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex topics.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.topics_list_response import TopicsListResponse
from inse.tags import Tags
from . import logic
router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS])
@router.get(
"/autocomplete",
operation_id="autocompleteTopics",
response_model=AutocompleteResponse,
response_model_exclude_none=True,
summary="Returns topic options for autocomplete inputs.",
)
async def autocomplete_topics(
query: Annotated[
str,
Query(description="Topic search text, for example 'machine learning'.", min_length=1),
],
domain_id: Annotated[
str | None,
Query(alias="domainId", description="Optional OpenAlex domain id filter."),
] = None,
field_id: Annotated[
str | None,
Query(alias="fieldId", description="Optional OpenAlex field id filter."),
] = None,
subfield_id: Annotated[
str | None,
Query(alias="subfieldId", description="Optional OpenAlex subfield id filter."),
] = None,
limit: Annotated[
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
):
return await logic.autocomplete_topics(
query=query,
domain_id=domain_id,
field_id=field_id,
subfield_id=subfield_id,
limit=limit,
)
@router.get(
"",
operation_id="listTopics",
response_model=TopicsListResponse,
response_model_exclude_none=True,
summary="Returns a list of OpenAlex topics.",
)
async def list_topics(
search: Annotated[
str | None,
Query(description="Full-text search, for example 'machine learning'."),
] = None,
filter: Annotated[
str | None,
Query(description="OpenAlex filter, for example 'domain.id:1,works_count:>1000'."),
] = None,
sort: Annotated[
str | None,
Query(description="Sort field, for example 'works_count:desc'."),
] = "works_count:desc",
group_by: Annotated[
str | None,
Query(description="OpenAlex group_by field, for example 'domain.id'."),
] = None,
per_page: Annotated[
int,
Query(description="Results per page.", ge=1, le=100),
] = 25,
page: Annotated[
int | None,
Query(description="Page number. Use cursor for deep pagination.", ge=1),
] = 1,
cursor: Annotated[
str | None,
Query(description="Cursor pagination token. Use '*' to start."),
] = None,
sample: Annotated[
int | None,
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
] = None,
select: Annotated[
str | None,
Query(description="Comma-separated fields to return."),
] = None,
):
return await logic.list_topics(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
+195
View File
@@ -0,0 +1,195 @@
import httpx
import pytest
from fastapi import HTTPException
from inse.topics import logic
from inse.topics.search_client import OpenAlexTopicsClient
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_list_topics_maps_openalex_response_to_model():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"description": "Methods that learn from data.",
"keywords": ["machine learning", "classification"],
"subfield": {
"id": "https://openalex.org/subfields/1702",
"display_name": "Artificial Intelligence",
},
"field": {
"id": "https://openalex.org/fields/17",
"display_name": "Computer Science",
},
"domain": {
"id": "https://openalex.org/domains/4",
"display_name": "Physical Sciences",
},
"works_count": 123,
"cited_by_count": 456,
"ids": {
"openalex": "https://openalex.org/T12419",
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
},
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
"created_date": "2023-12-25",
"updated_date": "2023-11-07T05:31:56Z",
}
],
"group_by": [
{
"key": "https://openalex.org/domains/4",
"key_display_name": "Physical Sciences",
"count": 1,
}
],
},
)
client = OpenAlexTopicsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.list_topics(search="machine learning", client=client)
assert result.meta.count == 1
topic = result.results[0]
assert topic.display_name == "Machine learning"
assert topic.var_field.display_name == "Computer Science"
assert topic.subfield.display_name == "Artificial Intelligence"
assert topic.domain.display_name == "Physical Sciences"
assert topic.ids.openalex == "https://openalex.org/T12419"
assert result.group_by[0].key_display_name == "Physical Sciences"
@pytest.mark.anyio
async def test_list_topics_rejects_sample_with_sort():
with pytest.raises(HTTPException) as exc_info:
await logic.list_topics(sample=10, sort="works_count:desc")
assert exc_info.value.status_code == 400
@pytest.mark.anyio
async def test_list_topics_accepts_practical_openalex_type_variants():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": "1", "page": "1", "per_page": "25"},
"results": [
{
"id": 123,
"display_name": 456,
"description": True,
"keywords": ["topic", 123],
"subfield": {"id": 1, "display_name": 2},
"field": {"id": 3, "display_name": 4},
"domain": {"id": 5, "display_name": 6},
"works_count": "12.0",
"cited_by_count": False,
"ids": {"openalex": 123, "wikipedia": 456},
"created_date": "2023-12-25T10:11:12Z",
"updated_date": "2023-12-25",
}
],
"group_by": [{"key": True, "count": "1"}],
},
)
client = OpenAlexTopicsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.list_topics(client=client)
topic = result.results[0]
assert topic.id == "123"
assert topic.display_name == "456"
assert topic.description == "true"
assert topic.keywords == ["topic", "123"]
assert topic.works_count == 12
assert topic.cited_by_count is None
assert topic.var_field.id == "3"
assert topic.domain.display_name == "6"
assert topic.ids.wikipedia == "456"
assert topic.created_date.isoformat() == "2023-12-25"
assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00"
assert result.group_by[0].key == "true"
@pytest.mark.anyio
async def test_autocomplete_topics_returns_frontend_options():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["search"] == "machine learning"
assert request.url.params["filter"] == (
"domain.id:https://openalex.org/domains/4,"
"field.id:https://openalex.org/fields/17,"
"subfield.id:https://openalex.org/subfields/1702"
)
assert request.url.params["sort"] == "works_count:desc"
assert request.url.params["per_page"] == "5"
assert request.url.params["select"] == (
"id,display_name,description,keywords,subfield,field,domain,"
"works_count,cited_by_count,ids"
)
return httpx.Response(
200,
json={
"meta": {"count": 1, "db_response_time_ms": 12},
"results": [
{
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
"description": "Methods that learn from data.",
"field": {"display_name": "Computer Science"},
"subfield": {"display_name": "Artificial Intelligence"},
"domain": {"display_name": "Physical Sciences"},
"works_count": 123,
"cited_by_count": 456,
"ids": {"openalex": "https://openalex.org/T12419"},
}
],
},
)
client = OpenAlexTopicsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.autocomplete_topics(
query="machine learning",
domain_id="https://openalex.org/domains/4",
field_id="https://openalex.org/fields/17",
subfield_id="https://openalex.org/subfields/1702",
limit=5,
client=client,
)
assert result.meta.count == 1
assert result.meta.db_response_time_ms == 12
assert len(result.results) == 1
option = result.results[0]
assert option.id == "https://openalex.org/T12419"
assert option.display_name == "Machine learning"
assert option.hint == (
"Computer Science · Artificial Intelligence · Physical Sciences"
)
assert option.works_count == 123
assert option.cited_by_count == 456
assert option.entity_type == "topic"
assert option.external_id == "https://openalex.org/T12419"
@@ -0,0 +1,75 @@
import httpx
import pytest
from inse.topics.search_client import OpenAlexTopicsClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def test_list_topics_params_include_openalex_query_parameters():
client = OpenAlexTopicsClient(api_key="test-key")
params = client.list_topics_params(
search="machine learning",
filter="domain.id:4,works_count:>1000",
sort="works_count:desc",
group_by="domain.id",
per_page=10,
page=2,
select="id,display_name",
)
assert params == {
"search": "machine learning",
"filter": "domain.id:4,works_count:>1000",
"sort": "works_count:desc",
"group_by": "domain.id",
"per_page": 10,
"page": 2,
"select": "id,display_name",
"api_key": "test-key",
}
def test_list_topics_params_prefers_cursor_over_page():
client = OpenAlexTopicsClient(api_key="test-key")
params = client.list_topics_params(cursor="*", page=3)
assert params["cursor"] == "*"
assert "page" not in params
@pytest.mark.anyio
async def test_list_topics_calls_openalex_topics_endpoint():
def handler(request: httpx.Request) -> httpx.Response:
assert request.method == "GET"
assert request.url.path == "/topics"
assert request.url.params["search"] == "machine learning"
assert request.url.params["api_key"] == "test-key"
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": "https://openalex.org/T12419",
"display_name": "Machine learning",
}
],
},
)
client = OpenAlexTopicsClient(
base_url="https://api.openalex.org",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await client.list_topics(search="machine learning")
assert result["meta"]["count"] == 1
assert result["results"][0]["display_name"] == "Machine learning"
+4 -5
View File
@@ -28,11 +28,10 @@ def get_persons_data(hit:dict):
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = dict(ids)
for str_field in ["openalex", "orcid", "scopus"]:
val = ids_copy.get(str_field)
if val is not None and not isinstance(val, str):
ids_copy[str_field] = str(val)
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
+88 -15
View File
@@ -11,6 +11,7 @@ import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_404_NOT_FOUND
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.models.work import Work
@@ -33,6 +34,8 @@ async def get_author_works(
publication_year: list[int] | None = None,
work_type: list[str] | None = None,
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
client: OpenAlexWorksSearchClient | None = None,
) -> WorkPage:
search_client = client or OpenAlexWorksSearchClient()
@@ -44,6 +47,8 @@ async def get_author_works(
publication_year=publication_year,
work_type=work_type,
language=language,
institution_id=institution_id,
topic_id=topic_id,
)
elements, total = _parse_full_work_search_response(data)
@@ -90,6 +95,58 @@ async def get_all_author_works(
)
async def get_primary_topic_counts(
author_id: str,
client: OpenAlexWorksSearchClient | None = None,
) -> List[TopicCount]:
works = await get_all_author_works(author_id, client=client)
counts = {}
for work in works.results or []:
primary_topic = work.primary_topic
if not primary_topic or not primary_topic.display_name:
continue
name = primary_topic.display_name
if name not in counts:
counts[name] = {"id": primary_topic.id, "name": name, "count": 0}
counts[name]["count"] += 1
items = sorted(counts.values(), key=lambda item: item["count"], reverse=True)
return [
TopicCount(id=item["id"], name=item["name"], count=item["count"])
for item in items
]
async def get_work(
work_id: str,
client: OpenAlexWorksSearchClient | None = None,
) -> Work:
search_client = client or OpenAlexWorksSearchClient()
try:
data = await search_client.search_work(work_id)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="OpenAlex works search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
elements, _ = _parse_full_work_search_response(data)
if not elements:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail="Publication not found.",
)
return elements[0]
async def get_topics_by_time_by_author(
author_id: str,
max_topics_per_year: int = 3,
@@ -117,45 +174,57 @@ async def get_topics_by_time_by_author(
for topic in work.topics or []:
if topic.display_name:
topic_name = topic.display_name
topic_id = topic.id
if topic_name not in years[year]["topics"]:
years[year]["topics"][topic_name] = 0
years[year]["topics"][topic_name] = {
"id": topic_id,
"name": topic_name,
"count": 0,
}
years[year]["topics"][topic_name] += 1
years[year]["topics"][topic_name]["count"] += 1
primary_topic = work.primary_topic
if primary_topic and primary_topic.display_name:
primary_topic_name = primary_topic.display_name
primary_topic_id = primary_topic.id
if primary_topic_name not in years[year]["primary_topics"]:
years[year]["primary_topics"][primary_topic_name] = 0
years[year]["primary_topics"][primary_topic_name] += 1
years[year]["primary_topics"][primary_topic_name] = {
"id": primary_topic_id,
"name": primary_topic_name,
"count": 0,
}
years[year]["primary_topics"][primary_topic_name]["count"] += 1
elements = []
for year in sorted(years.keys()):
topic_items = list(years[year]["topics"].items())
topic_items.sort(key=lambda item: item[1], reverse=True)
topic_items = list(years[year]["topics"].values())
topic_items.sort(key=lambda item: item["count"], reverse=True)
topics = []
for topic_name, count in topic_items[:max_topics_per_year]:
for topic in topic_items[:max_topics_per_year]:
topics.append(TopicCount(
name=topic_name,
count=count,
id=topic["id"],
name=topic["name"],
count=topic["count"],
))
primary_topic_items = list(years[year]["primary_topics"].items())
primary_topic_items.sort(key=lambda item: item[1], reverse=True)
primary_topic_items = list(years[year]["primary_topics"].values())
primary_topic_items.sort(key=lambda item: item["count"], reverse=True)
primary_topics = []
for topic_name, count in primary_topic_items[:max_topics_per_year]:
for topic in primary_topic_items[:max_topics_per_year]:
primary_topics.append(TopicCount(
name=topic_name,
count=count,
id=topic["id"],
name=topic["name"],
count=topic["count"],
))
elements.append(TopicsByYear(
@@ -179,6 +248,8 @@ async def _search_author_works_data(
publication_year: list[int] | None = None,
work_type: list[str] | None = None,
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
) -> dict:
try:
return await search_client.search_author_works(
@@ -188,6 +259,8 @@ async def _search_author_works_data(
publication_year=publication_year,
work_type=work_type,
language=language,
institution_id=institution_id,
topic_id=topic_id,
)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
+80 -13
View File
@@ -40,26 +40,52 @@ class OpenAlexWorksSearchClient:
publication_year: list[int] | None = None,
work_type: list[str] | None = None,
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
) -> dict[str, Any]:
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
filters = self._work_filters(publication_year, work_type, language)
filters = self._work_filters(
publication_year,
work_type,
language,
topic_id,
)
author_filters: list[dict[str, Any]] = [
{
"term": {
"authorships.author.id": indexed_author_id,
},
},
]
must_clauses: list[dict[str, Any]] = [
{
"nested": {
"path": "authorships",
"query": {
"bool": {
"filter": author_filters,
},
},
},
},
]
if institution_id:
must_clauses.append({
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": institution_id,
},
},
},
})
return {
"from": (page - 1) * size,
"size": size,
"query": {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": indexed_author_id,
},
},
},
},
],
"must": must_clauses,
"filter": filters,
},
},
@@ -74,6 +100,7 @@ class OpenAlexWorksSearchClient:
publication_year: list[int] | None = None,
work_type: list[str] | None = None,
language: list[str] | None = None,
topic_id: list[str] | None = None,
) -> list[dict[str, Any]]:
filters: list[dict[str, Any]] = []
if publication_year:
@@ -82,6 +109,21 @@ class OpenAlexWorksSearchClient:
filters.append({"terms": {"type": work_type}})
if language:
filters.append({"terms": {"language": language}})
if topic_id:
filters.append({
"bool": {
"should": [
{
"nested": {
"path": "topics",
"query": {"terms": {"topics.id": topic_id}},
},
},
{"terms": {"primary_topic.id": topic_id}},
],
"minimum_should_match": 1,
},
})
return filters
async def search_author_works(
@@ -92,6 +134,8 @@ class OpenAlexWorksSearchClient:
publication_year: list[int] | None = None,
work_type: list[str] | None = None,
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
@@ -111,8 +155,31 @@ class OpenAlexWorksSearchClient:
publication_year=publication_year,
work_type=work_type,
language=language,
institution_id=institution_id,
topic_id=topic_id,
),
)
# logging.debug(f"Response: {response.text}")
response.raise_for_status()
return response.json()
async def search_work(self, work_id: str) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}"
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{self.index}/_search",
headers={"Authorization": f"ApiKey {self.api_key}"},
json={
"size": 1,
"query": {"term": {"id": indexed_work_id}},
},
)
response.raise_for_status()
return response.json()
+40
View File
@@ -16,7 +16,9 @@ from inse.tags import Tags
from .. import security
from . import logic
from inse.models.work_page import WorkPage
from inse.models.work import Work
from inse.models.works_list_response import WorksListResponse
from inse.models.topic_count import TopicCount
from inse.models.topics_by_time import TopicsByTime
@@ -46,6 +48,14 @@ async def get_author_works(
language: Annotated[
list[str] | None, Query(description="Filter by language code. Can be repeated.")
] = None,
institution_id: Annotated[
list[str] | None,
Query(description="Filter by OpenAlex institution id. Can be repeated."),
] = None,
topic_id: Annotated[
list[str] | None,
Query(description="Filter by OpenAlex topic id. Can be repeated."),
] = None,
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
@@ -57,6 +67,8 @@ async def get_author_works(
publication_year=publication_year,
work_type=work_type,
language=language,
institution_id=institution_id,
topic_id=topic_id,
)
@@ -71,6 +83,17 @@ async def get_all_author_works(
return await logic.get_all_author_works(author_id)
@router.get("/{author_id}/primary-topic-counts",
operation_id="getPrimaryTopicCountsByAuthor",
response_model=list[TopicCount],
summary="Returns work counts per primary topic for an author.")
async def get_primary_topic_counts(
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
):
return await logic.get_primary_topic_counts(author_id)
@router.get("/{author_id}/topics-by-time",
operation_id="getTopicsByTimeByAuthor",
response_model=TopicsByTime,
@@ -84,3 +107,20 @@ async def get_topics_by_time_by_author(
author_id,
max_topics_per_year=max_topics_per_year,
)
@router.get(
"/detail/{work_id}",
operation_id="getWork",
response_model=Work,
summary="Returns one publication.",
)
async def get_work(
work_id: Annotated[
str, Path(description="The OpenAlex work id, for example W2741809807.")
],
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
return await logic.get_work(work_id)
@@ -1,3 +1,5 @@
import json
import httpx
import pytest
@@ -19,7 +21,9 @@ def test_author_works_query_searches_authorship_author_id():
assert query["size"] == 25
author_query = query["query"]["bool"]["must"][0]["nested"]
assert author_query["path"] == "authorships"
assert author_query["query"]["term"]["authorships.author.id"] == "https://openalex.org/A5023888391"
assert author_query["query"]["bool"]["filter"] == [
{"term": {"authorships.author.id": "https://openalex.org/A5023888391"}},
]
assert query["query"]["bool"]["filter"] == []
@@ -33,13 +37,191 @@ def test_author_works_query_adds_publication_filters():
publication_year=[2023, 2024],
work_type=["article", "book-chapter"],
language=["en", "de"],
institution_id=["https://openalex.org/I123"],
topic_id=["https://openalex.org/T12419"],
)
assert query["query"]["bool"]["filter"] == [
{"terms": {"publication_year": [2023, 2024]}},
{"terms": {"type": ["article", "book-chapter"]}},
{"terms": {"language": ["en", "de"]}},
{
"bool": {
"should": [
{
"nested": {
"path": "topics",
"query": {
"terms": {
"topics.id": ["https://openalex.org/T12419"],
},
},
},
},
{"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}},
],
"minimum_should_match": 1,
},
},
]
assert query["query"]["bool"]["must"] == [
{
"nested": {
"path": "authorships",
"query": {
"bool": {
"filter": [
{
"term": {
"authorships.author.id": "https://openalex.org/A5023888391"
}
},
],
},
},
},
},
{
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [
"https://openalex.org/I123",
],
},
},
},
},
]
def test_author_works_query_uses_nested_institution_path():
client = OpenAlexWorksSearchClient(api_key="test-key")
query = client.author_works_query(
"A5023888391",
page=1,
size=20,
institution_id=["https://openalex.org/I205640436"],
)
assert query["query"]["bool"]["must"][1] == {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [
"https://openalex.org/I205640436",
],
},
},
},
}
def test_author_works_query_adds_topic_filter():
client = OpenAlexWorksSearchClient(api_key="test-key")
query = client.author_works_query(
"A5023888391",
page=1,
size=20,
topic_id=["https://openalex.org/T12419"],
)
assert query["query"]["bool"]["filter"] == [
{
"bool": {
"should": [
{
"nested": {
"path": "topics",
"query": {
"terms": {
"topics.id": ["https://openalex.org/T12419"],
},
},
},
},
{"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}},
],
"minimum_should_match": 1,
},
},
]
@pytest.mark.anyio
async def test_search_author_works_passes_institution_filter_to_query():
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
"authorships.institutions"
)
assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == {
"authorships.institutions.id": ["https://openalex.org/I205640436"],
}
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
client = OpenAlexWorksSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
index="openalex-works",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
await client.search_author_works(
"A5023888391",
page=1,
size=20,
institution_id=["https://openalex.org/I205640436"],
)
@pytest.mark.anyio
async def test_search_author_works_passes_topic_filter_to_query():
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body["query"]["bool"]["filter"] == [
{
"bool": {
"should": [
{
"nested": {
"path": "topics",
"query": {
"terms": {
"topics.id": ["https://openalex.org/T12419"],
},
},
},
},
{
"terms": {
"primary_topic.id": ["https://openalex.org/T12419"],
},
},
],
"minimum_should_match": 1,
},
},
]
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
client = OpenAlexWorksSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
index="openalex-works",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
await client.search_author_works(
"A5023888391",
page=1,
size=20,
topic_id=["https://openalex.org/T12419"],
)
@pytest.mark.anyio
@@ -62,6 +244,26 @@ async def test_search_author_works_calls_elasticsearch_index_with_api_key():
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
@pytest.mark.anyio
async def test_search_work_filters_by_work_id():
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body == {
"size": 1,
"query": {"term": {"id": "https://openalex.org/W2741809807"}},
}
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
client = OpenAlexWorksSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
index="openalex-works",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
await client.search_work("W2741809807")
@pytest.mark.anyio
async def test_search_author_works_requires_api_key():
client = OpenAlexWorksSearchClient(api_key="")
+10 -8
View File
@@ -1,9 +1,10 @@
.gitignore
.openapi-generator-ignore
README.md
api.base.service.ts
api.module.ts
api/api.ts
api/funding.service.ts
api/funding.serviceInterface.ts
api/inse-account-service.service.ts
api/inse-account-service.serviceInterface.ts
api/inse-service.service.ts
@@ -12,8 +13,6 @@ api/items.service.ts
api/items.serviceInterface.ts
api/person-network.service.ts
api/person-network.serviceInterface.ts
api/persons-search.service.ts
api/persons-search.serviceInterface.ts
api/persons.service.ts
api/persons.serviceInterface.ts
api/topics.service.ts
@@ -31,6 +30,7 @@ model/author-affiliations-inner.ts
model/author-counts-by-year-inner.ts
model/author-ids.ts
model/author-parsed-longest-name.ts
model/author-position-count.ts
model/author-summary-stats.ts
model/author.ts
model/authors-list-response.ts
@@ -49,6 +49,8 @@ model/dehydrated-institution.ts
model/dehydrated-source.ts
model/filter-information.ts
model/filter-properties.ts
model/funder-by-author.ts
model/funders-by-author-response.ts
model/fwci.ts
model/group-by-result.ts
model/http-validation-error.ts
@@ -63,14 +65,14 @@ model/model2-yr-mean-citedness.ts
model/models.ts
model/open-access.ts
model/person-bio.ts
model/publication-ids-by-author-position.ts
model/publications-by-author-response.ts
model/score.ts
model/topic-count.ts
model/topics-by-time.ts
model/topics-by-year.ts
model/validation-error-loc-inner.ts
model/validation-error.ts
model/topicCount.ts
model/topicsByTime.ts
model/topicsByYear.ts
model/validationError.ts
model/validationErrorLocInner.ts
model/value.ts
model/work-biblio.ts
model/work-citation-normalized-percentile.ts
+4 -4
View File
@@ -1,3 +1,6 @@
export * from './funding.service';
import { FundingService } from './funding.service';
export * from './funding.serviceInterface';
export * from './inse-account-service.service';
import { INSEAccountServiceService } from './inse-account-service.service';
export * from './inse-account-service.serviceInterface';
@@ -13,13 +16,10 @@ export * from './person-network.serviceInterface';
export * from './persons.service';
import { PersonsService } from './persons.service';
export * from './persons.serviceInterface';
export * from './persons-search.service';
import { PersonsSearchService } from './persons-search.service';
export * from './persons-search.serviceInterface';
export * from './topics.service';
import { TopicsService } from './topics.service';
export * from './topics.serviceInterface';
export * from './works.service';
import { WorksService } from './works.service';
export * from './works.serviceInterface';
export const APIS = [INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, PersonsSearchService, TopicsService, WorksService];
export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService];
+164
View File
@@ -0,0 +1,164 @@
/**
* 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 { FundersByAuthorResponse } from '../model/funders-by-author-response';
// @ts-ignore
import { HTTPValidationError } from '../model/http-validation-error';
// @ts-ignore
import { PublicationsByAuthorResponse } from '../model/publications-by-author-response';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
import {
FundingServiceInterface
} from './funding.serviceInterface';
@Injectable({
providedIn: 'root'
})
export class FundingService extends BaseService implements FundingServiceInterface {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Get funding organizations by author.
* @endpoint get /api/inse-service/authors/{author_id}/funders
* @param authorId
* @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 getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<FundersByAuthorResponse>;
public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<FundersByAuthorResponse>>;
public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<FundersByAuthorResponse>>;
public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.');
}
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/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<FundersByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get funded publications by author.
* @endpoint get /api/inse-service/authors/{author_id}/publications
* @param authorId
* @param page
* @param pageSize
* @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 getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PublicationsByAuthorResponse>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
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/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PublicationsByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -0,0 +1,45 @@
/**
* 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 { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { FundersByAuthorResponse } from '../model/models';
import { HTTPValidationError } from '../model/models';
import { PublicationsByAuthorResponse } from '../model/models';
import { Configuration } from '../configuration';
export interface FundingServiceInterface {
defaultHeaders: HttpHeaders;
configuration: Configuration;
/**
* Get funding organizations by author.
*
* @endpoint get /api/inse-service/authors/{author_id}/funders
* @param authorId
*/
getFundersByAuthor(authorId: string, extraHttpRequestParams?: any): Observable<FundersByAuthorResponse>;
/**
* Get funded publications by author.
*
* @endpoint get /api/inse-service/authors/{author_id}/publications
* @param authorId
* @param page
* @param pageSize
*/
getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, extraHttpRequestParams?: any): Observable<PublicationsByAuthorResponse>;
}
@@ -19,6 +19,8 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorsListResponse } from '../model/authors-list-response';
// @ts-ignore
import { FundersByAuthorResponse } from '../model/funders-by-author-response';
// @ts-ignore
import { HTTPValidationError } from '../model/http-validation-error';
// @ts-ignore
import { Item } from '../model/item';
@@ -28,6 +30,8 @@ import { ItemCreate } from '../model/item-create';
import { ItemPage } from '../model/item-page';
// @ts-ignore
import { PersonBio } from '../model/person-bio';
// @ts-ignore
import { PublicationsByAuthorResponse } from '../model/publications-by-author-response';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -299,6 +303,8 @@ export class INSEServiceService extends BaseService implements INSEServiceServic
}
/**
<<<<<<< HEAD
=======
* Generates a bio for a person by author ID.
* @endpoint get /api/inse-service/persons/bio
* @param authorId OpenAlex author ID (e.g., A5093075883)
@@ -362,6 +368,62 @@ export class INSEServiceService extends BaseService implements INSEServiceServic
}
/**
* Get funding organizations by author.
* @endpoint get /api/inse-service/authors/{author_id}/funders
* @param authorId
* @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 getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<FundersByAuthorResponse>;
public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<FundersByAuthorResponse>>;
public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<FundersByAuthorResponse>>;
public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.');
}
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/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<FundersByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d
* Returns the item with the id.
* @endpoint get /api/inse-service/items/{id}
* @param id The item id.
@@ -483,6 +545,8 @@ export class INSEServiceService extends BaseService implements INSEServiceServic
}
/**
<<<<<<< HEAD
=======
* Searches for person by ID.
* @endpoint get /api/inse-service/person/{id}
* @param id OpenAlex author ID
@@ -546,6 +610,70 @@ export class INSEServiceService extends BaseService implements INSEServiceServic
);
}
/**
* Get funded publications by author.
* @endpoint get /api/inse-service/authors/{author_id}/publications
* @param authorId
* @param page
* @param pageSize
* @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 getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PublicationsByAuthorResponse>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
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/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PublicationsByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for persons by ID or name.
* @endpoint get /api/inse-service/persons/search
@@ -742,6 +870,7 @@ export class INSEServiceService extends BaseService implements INSEServiceServic
}
/**
>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d
* Updates the item with the id.
* @endpoint put /api/inse-service/items/{id}
* @param id The item id.
@@ -11,12 +11,14 @@ import { HttpHeaders } from '@angular/comm
import { Observable } from 'rxjs';
import { AuthorsListResponse } from '../model/models';
import { AuthorsListResponse } from '../model/models'; //
import { FundersByAuthorResponse } from '../model/models'; //
import { HTTPValidationError } from '../model/models';
import { Item } from '../model/models';
import { ItemCreate } from '../model/models';
import { ItemPage } from '../model/models';
import { PersonBio } from '../model/models';
import { PersonBio } from '../model/models'; //
import { PublicationsByAuthorResponse } from '../model/models'; //
import { Configuration } from '../configuration';
@@ -61,6 +63,8 @@ export interface INSEServiceServiceInterface {
deleteItem(id: number, extraHttpRequestParams?: any): Observable<any>;
/**
<<<<<<< HEAD
=======
* Generates a bio for a person by author ID.
*
* @endpoint get /api/inse-service/persons/bio
@@ -70,6 +74,15 @@ export interface INSEServiceServiceInterface {
generatePersonBio(authorId: string, include?: string, extraHttpRequestParams?: any): Observable<PersonBio>;
/**
* Get funding organizations by author.
*
* @endpoint get /api/inse-service/authors/{author_id}/funders
* @param authorId
*/
getFundersByAuthor(authorId: string, extraHttpRequestParams?: any): Observable<FundersByAuthorResponse>;
/**
>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d
* Returns the item with the id.
*
* @endpoint get /api/inse-service/items/{id}
@@ -87,6 +100,8 @@ export interface INSEServiceServiceInterface {
getItems(pageOffset?: number, pageSize?: number, extraHttpRequestParams?: any): Observable<ItemPage>;
/**
<<<<<<< HEAD
=======
* Searches for person by ID.
*
* @endpoint get /api/inse-service/person/{id}
@@ -95,6 +110,16 @@ export interface INSEServiceServiceInterface {
*/
getPersonByID(id: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Get funded publications by author.
*
* @endpoint get /api/inse-service/authors/{author_id}/publications
* @param authorId
* @param page
* @param pageSize
*/
getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, extraHttpRequestParams?: any): Observable<PublicationsByAuthorResponse>;
/**
* Searches for persons by ID or name.
*
@@ -124,6 +149,7 @@ export interface INSEServiceServiceInterface {
searchPersonsByName(authorName: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d
* Updates the item with the id.
*
* @endpoint put /api/inse-service/items/{id}
@@ -49,13 +49,14 @@ export class PersonsSearchService extends BaseService implements PersonsSearchSe
* @param page Page number (1-indexed)
* @param pageSize Results per page
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
* @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 searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, 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,
@@ -74,6 +75,8 @@ export class PersonsSearchService extends BaseService implements PersonsSearchSe
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>strict, 'strict');
let localVarHeaders = this.defaultHeaders;
@@ -11,7 +11,7 @@ import { HttpHeaders } from '@angular/comm
import { Observable } from 'rxjs';
import { CustomAuthorsListResponse } from '../model/models';
import { CustomAuthorsListResponse } from '../model/custom-authors-list-response';
import { HTTPValidationError } from '../model/models';
@@ -33,7 +33,8 @@ export interface PersonsSearchServiceInterface {
* @param page Page number (1-indexed)
* @param pageSize Results per page
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
*/
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
}
+457 -15
View File
@@ -171,6 +171,70 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
);
}
/**
* Searches for person by ID.
* @endpoint get /api/inse-service/person/{id}
* @param id OpenAlex author ID
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @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 getPersonByID_1(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public getPersonByID_1(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public getPersonByID_1(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public getPersonByID_1(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getPersonByID_1.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling getPersonByID_1.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
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/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for persons by ID or name.
* @endpoint get /api/inse-service/persons/search
@@ -235,17 +299,151 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
}
/**
* Searches for persons by institution name.
* @endpoint get /api/inse-service/persons/searchByInstitution
* @param institutionName Institution name (e.g., MIT, Oxford University)
* Searches for person by name.
* @endpoint get /api/inse-service/persons/autocomplete
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @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 searchPersonsByInstitution(institutionName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorName === null || authorName === undefined) {
throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorName, 'author_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
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/inse-service/persons/autocomplete`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for person by name.
* @endpoint get /api/inse-service/persons/autocomplete
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @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 searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsAutocomplete_2(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorName === null || authorName === undefined) {
throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorName, 'author_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
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/inse-service/persons/autocomplete`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for persons by institution name.
* @endpoint get /api/inse-service/persons/searchByInstitution
* @param institutionName Institution name (e.g., MIT, Oxford University)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
* @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 searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (institutionName === null || institutionName === undefined) {
throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.');
}
@@ -258,6 +456,82 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
<any>institutionName, 'institution_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>limit, 'limit');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageOffset, 'page_offset');
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/inse-service/persons/searchByInstitution`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for persons by institution name.
* @endpoint get /api/inse-service/persons/searchByInstitution
* @param institutionName Institution name (e.g., MIT, Oxford University)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
* @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 searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (institutionName === null || institutionName === undefined) {
throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution_3.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution_3.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>institutionName, 'institution_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>limit, 'limit');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageOffset, 'page_offset');
let localVarHeaders = this.defaultHeaders;
@@ -305,13 +579,15 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
* @endpoint get /api/inse-service/persons/searchByName
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
* @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 searchPersonsByName(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorName === null || authorName === undefined) {
throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.');
}
@@ -324,6 +600,82 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
<any>authorName, 'author_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>limit, 'limit');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageOffset, 'page_offset');
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/inse-service/persons/searchByName`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for person by name.
* @endpoint get /api/inse-service/persons/searchByName
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
* @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 searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorName === null || authorName === undefined) {
throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName_4.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling searchPersonsByName_4.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>authorName, 'author_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>limit, 'limit');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageOffset, 'page_offset');
let localVarHeaders = this.defaultHeaders;
@@ -375,13 +727,14 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
* @param page Page number (1-indexed)
* @param pageSize Results per page
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
* @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 searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, 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,
@@ -400,6 +753,95 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>strict, 'strict');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterMode, 'filterMode');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterYear, 'filterYear');
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/inse-service/persons/search-list`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CustomAuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Searches for persons with advanced filters (Topic &amp; Institution) and pagination.
* @endpoint get /api/inse-service/persons/search-list
* @param query Search query (e.g., Arman AND Arzani)
* @param institutionName Filter by institution name
* @param topic Filter by topic display names
* @param page Page number (1-indexed)
* @param pageSize Results per page
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
* @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 searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, 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>query, 'query');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>institutionName, 'institutionName');
if (topic) {
topic.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>strict, 'strict');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterMode, 'filterMode');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterYear, 'filterYear');
let localVarHeaders = this.defaultHeaders;
@@ -43,6 +43,15 @@ export interface PersonsServiceInterface {
*/
getPersonByID(id: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for person by ID.
*
* @endpoint get /api/inse-service/person/{id}
* @param id OpenAlex author ID
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
*/
getPersonByID_1(id: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for persons by ID or name.
*
@@ -53,14 +62,45 @@ export interface PersonsServiceInterface {
*/
searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for person by name.
*
* @endpoint get /api/inse-service/persons/autocomplete
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
*/
searchPersonsAutocomplete(authorName: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for person by name.
*
* @endpoint get /api/inse-service/persons/autocomplete
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
*/
searchPersonsAutocomplete_2(authorName: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for persons by institution name.
*
* @endpoint get /api/inse-service/persons/searchByInstitution
* @param institutionName Institution name (e.g., MIT, Oxford University)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
*/
searchPersonsByInstitution(institutionName: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for persons by institution name.
*
* @endpoint get /api/inse-service/persons/searchByInstitution
* @param institutionName Institution name (e.g., MIT, Oxford University)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
*/
searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for person by name.
@@ -68,8 +108,23 @@ export interface PersonsServiceInterface {
* @endpoint get /api/inse-service/persons/searchByName
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
*/
searchPersonsByName(authorName: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for person by name.
*
* @endpoint get /api/inse-service/persons/searchByName
* @param authorName Authors name (e.g., Arman Arzani)
* @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ...
* @param limit Limit of search page results
* @param pageOffset Offset of the result page
*/
searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
/**
* Searches for persons with advanced filters (Topic &amp; Institution) and pagination.
@@ -81,7 +136,8 @@ export interface PersonsServiceInterface {
* @param page Page number (1-indexed)
* @param pageSize Results per page
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
*/
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
}
+51
View File
@@ -162,4 +162,55 @@ export class TopicsService extends BaseService implements TopicsServiceInterface
);
}
/**
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
* @endpoint get /api/inse-service/topics/hierarchy
* @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
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/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -39,4 +39,11 @@ export interface TopicsServiceInterface {
*/
countTopicHierarchy(topic: Array<string>, extraHttpRequestParams?: any): Observable<object>;
/**
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
*
* @endpoint get /api/inse-service/topics/hierarchy
*/
getTopicHierarchy(extraHttpRequestParams?: any): Observable<object>;
}
+109 -36
View File
@@ -9,26 +9,27 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/http-validation-error';
// @ts-ignore
import { TopicsByTime } from '../model/topicsByTime';
import { TopicCount } from '../model/topic-count'; //
// @ts-ignore
import { WorkPage } from '../model/workPage';
import { TopicsByTime } from '../model/topics-by-time';
// @ts-ignore
import { WorkPage } from '../model/work-page';
// @ts-ignore
import { WorksListResponse } from '../model/works-list-response';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
import {
WorksServiceInterface
@@ -37,11 +38,11 @@ import {
@Injectable({
providedIn: 'root'
providedIn: 'root'
})
export class WorksService extends BaseService implements WorksServiceInterface {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string | string[], @Optional() configuration?: Configuration) {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
@@ -52,10 +53,10 @@ export class WorksService extends BaseService implements WorksServiceInterface {
* @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 getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<WorksListResponse>;
public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<HttpResponse<WorksListResponse>>;
public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<HttpEvent<WorksListResponse>>;
public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<any> {
public getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorksListResponse>;
public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorksListResponse>>;
public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorksListResponse>>;
public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getAllAuthorWorks.');
}
@@ -88,7 +89,7 @@ export class WorksService extends BaseService implements WorksServiceInterface {
}
}
let localVarPath = `/api/works/${this.configuration.encodeParam({ name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined })}/all`;
let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/all`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<WorksListResponse>('get', `${basePath}${localVarPath}`,
{
@@ -112,38 +113,52 @@ export class WorksService extends BaseService implements WorksServiceInterface {
* @param publicationYear Filter by publication year. Can be repeated.
* @param type Filter by publication type. Can be repeated.
* @param language Filter by language code. Can be repeated.
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
* @param topicId Filter by OpenAlex topic id. Can be repeated.
* @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<WorkPage>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<HttpResponse<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<HttpEvent<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<any> {
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
<any>size, 'size');
if (publicationYear) {
publicationYear.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_year');
<any>element, 'publication_year');
})
}
if (type) {
type.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'type');
<any>element, 'type');
})
}
if (language) {
language.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language');
<any>element, 'language');
})
}
if (institutionId) {
institutionId.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_id');
})
}
if (topicId) {
topicId.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_id');
})
}
@@ -175,7 +190,7 @@ export class WorksService extends BaseService implements WorksServiceInterface {
}
}
let localVarPath = `/api/works/${this.configuration.encodeParam({ name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined })}`;
let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<WorkPage>('get', `${basePath}${localVarPath}`,
{
@@ -191,6 +206,64 @@ export class WorksService extends BaseService implements WorksServiceInterface {
);
}
/**
* Returns work counts per primary topic for an author.
* @endpoint get /api/works/{author_id}/primary-topic-counts
* @param authorId The author id, for example A5023888391.
* @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 getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<TopicCount>>;
public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<TopicCount>>>;
public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<TopicCount>>>;
public getPrimaryTopicCountsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', '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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-topic-counts`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<TopicCount>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns topics grouped by publication year for an author.
* @endpoint get /api/works/{author_id}/topics-by-time
@@ -199,17 +272,17 @@ export class WorksService extends BaseService implements WorksServiceInterface {
* @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 getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<TopicsByTime>;
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<HttpResponse<TopicsByTime>>;
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<HttpEvent<TopicsByTime>>;
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable<any> {
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicsByTime>;
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicsByTime>>;
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicsByTime>>;
public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.');
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>maxTopicsPerYear, 'max_topics_per_year');
<any>maxTopicsPerYear, 'max_topics_per_year');
let localVarHeaders = this.defaultHeaders;
@@ -239,7 +312,7 @@ export class WorksService extends BaseService implements WorksServiceInterface {
}
}
let localVarPath = `/api/works/${this.configuration.encodeParam({ name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined })}/topics-by-time`;
let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/topics-by-time`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopicsByTime>('get', `${basePath}${localVarPath}`,
{
@@ -12,6 +12,8 @@ import { HttpHeaders } from '@angular/comm
import { Observable } from 'rxjs';
import { HTTPValidationError } from '../model/models';
import { TopicCount } from '../model/models'; //
import { TopicsByTime } from '../model/models';
import { WorkPage } from '../model/models';
import { WorksListResponse } from '../model/models';
@@ -42,7 +44,18 @@ export interface WorksServiceInterface {
* @param publicationYear Filter by publication year. Can be repeated.
* @param type Filter by publication type. Can be repeated.
* @param language Filter by language code. Can be repeated.
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
* @param topicId Filter by OpenAlex topic id. Can be repeated.
*/
getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, extraHttpRequestParams?: any): Observable<WorkPage>;
getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, extraHttpRequestParams?: any): Observable<WorkPage>;
/**
* Returns topics grouped by publication year for an author.
*
* @endpoint get /api/works/{author_id}/topics-by-time
* @param authorId The author id, for example A5023888391.
* @param maxTopicsPerYear The maximum number of topics per year.
*/
getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, extraHttpRequestParams?: any): Observable<TopicsByTime>;
}
@@ -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.
*/
export interface AuthorPositionCount {
first?: number;
middle?: number;
last?: number;
unknown?: number;
}
@@ -0,0 +1,22 @@
/**
* 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 { PublicationIdsByAuthorPosition } from './publication-ids-by-author-position';
import { AuthorPositionCount } from './author-position-count';
export interface FunderByAuthor {
funder_id?: string | null;
funder_name?: string | null;
publication_count: number;
author_position_count: AuthorPositionCount;
publication_ids: PublicationIdsByAuthorPosition;
publication_urls?: { [key: string]: string; };
}
@@ -0,0 +1,19 @@
/**
* 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 { FunderByAuthor } from './funder-by-author';
export interface FundersByAuthorResponse {
author_id: string;
author_name?: string | null;
funder_count: number;
funders: Array<FunderByAuthor>;
}
+8 -3
View File
@@ -6,6 +6,7 @@ export * from './author-affiliations-inner';
export * from './author-counts-by-year-inner';
export * from './author-ids';
export * from './author-parsed-longest-name';
export * from './author-position-count';
export * from './author-summary-stats';
export * from './authors-list-response';
export * from './authorship';
@@ -23,6 +24,8 @@ export * from './dehydrated-institution';
export * from './dehydrated-source';
export * from './filter-information';
export * from './filter-properties';
export * from './funder-by-author';
export * from './funders-by-author-response';
export * from './fwci';
export * from './group-by-result';
export * from './http-validation-error';
@@ -36,12 +39,14 @@ export * from './meta';
export * from './model2-yr-mean-citedness';
export * from './open-access';
export * from './person-bio';
export * from './publication-ids-by-author-position';
export * from './publications-by-author-response';
export * from './score';
export * from './topic-count';
export * from './topics-by-time';
export * from './topics-by-year';
export * from './validation-error';
export * from './validation-error-loc-inner';
export * from './topicCount';
export * from './topicsByTime';
export * from './topicsByYear';
export * from './value';
export * from './work';
export * from './work-biblio';
@@ -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 PersonFilters {
institution?: string | null;
cited_by_count?: number | null;
}
@@ -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.
*/
import { PersonFilters } from './person-filters';
export interface PersonSearchRequest {
name?: string | null;
filters?: PersonFilters;
include?: string | null;
limit?: number | null;
page_offset?: number | 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.
*/
export interface PublicationIdsByAuthorPosition {
first?: Array<string>;
middle?: Array<string>;
last?: Array<string>;
unknown?: Array<string>;
}
@@ -0,0 +1,21 @@
/**
* 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 PublicationsByAuthorResponse {
author_id: string;
page: number;
page_size: number;
total_works: number;
total: number;
results_count: number;
results: Array<object>;
}
@@ -10,6 +10,7 @@
export interface TopicCount {
id?: string | null;
/**
* The topic display name.
*/
@@ -7,7 +7,7 @@
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { TopicsByYear } from './topicsByYear';
import { TopicsByYear } from './topics-by-year';
export interface TopicsByTime {
@@ -7,7 +7,7 @@
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { TopicCount } from './topicCount';
import { TopicCount } from './topic-count';
export interface TopicsByYear {
+15
View File
@@ -26,6 +26,14 @@ export const routes: Routes = [
(mod) => mod.PersonListComponent,
),
},
{
path: 'publication/:publicationId',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/publication-detail/publication-detail.component').then(
(mod) => mod.PublicationDetailComponent,
),
},
{
path: 'person/:id',
canActivate: [userGuard],
@@ -80,6 +88,13 @@ export const routes: Routes = [
(mod) => mod.PersonPublicationsComponent,
),
},
{
path: 'funding',
loadComponent: () =>
import('./modules/person-funding/person-funding.component').then(
(mod) => mod.PersonFundingComponent,
),
},
],
},
{
@@ -0,0 +1,180 @@
@if (loading) {
<p class="message">Lade Förderungen...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Förderungen.</p>
} @else if (funders.length === 0) {
<p class="message">Keine Förderungen gefunden.</p>
} @else {
<div class="funding-container">
<div class="funding-summary">
<p class="summary-line">
<span class="summary-value">{{ getUniquePublicationCount() }}</span>
<span class="summary-label"> Einzigartige Publikationen</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ filteredFunders.length }}</span>
<span class="summary-label"> Förderer</span>
</p>
</div>
<!-- Filter Buttons -->
<div class="filter-bar">
<span>Filter nach Position:</span>
<button
[class.active]="activeFilter === 'all'"
(click)="setFilter('all')"
>
Alle
</button>
<button
[class.active]="activeFilter === 'first'"
(click)="setFilter('first')"
>
Erstautor
</button>
<button
[class.active]="activeFilter === 'middle'"
(click)="setFilter('middle')"
>
Mitautor
</button>
<button
[class.active]="activeFilter === 'last'"
(click)="setFilter('last')"
>
Letztautor
</button>
</div>
<div class="funding-content">
<!-- Linke Seite: Tabelle -->
<div class="funding-list">
<table>
<thead>
<tr>
<th>Förderer</th>
<th>Publikationen</th>
</tr>
</thead>
<tbody>
@for (funder of getPagedFunders(); track funder.funder_id) {
<tr
[class.selected]="selectedFunder === funder"
(click)="selectFunder(funder)"
>
<td class="funder-name">{{ funder.funder_name }}</td>
<td>{{ getPublicationCount(funder) }}</td>
</tr>
}
</tbody>
</table>
@if (hasFunderListPagination()) {
<div class="publication-pagination">
<button
[disabled]="selectedFunderListPage === 1"
(click)="setFunderListPage(selectedFunderListPage - 1)"
>
Zurück
</button>
<span
>Seite {{ selectedFunderListPage }} von
{{ getFunderListPageCount() }}</span
>
<button
[disabled]="selectedFunderListPage === getFunderListPageCount()"
(click)="setFunderListPage(selectedFunderListPage + 1)"
>
Weiter
</button>
</div>
}
</div>
<!-- Rechte Seite: Details -->
@if (selectedFunder) {
<div class="funding-detail">
<h3>{{ selectedFunder.funder_name }}</h3>
<div class="position-stats">
@if (shouldShowPosition("first")) {
<div class="stat stat-first">
<span class="stat-label">Erstautor</span>
<span class="stat-value">{{
selectedFunder.author_position_count.first
}}</span>
</div>
}
@if (shouldShowPosition("middle")) {
<div class="stat stat-middle">
<span class="stat-label">Mitautor</span>
<span class="stat-value">{{
selectedFunder.author_position_count.middle
}}</span>
</div>
}
@if (shouldShowPosition("last")) {
<div class="stat stat-last">
<span class="stat-label">Letztautor</span>
<span class="stat-value">{{
selectedFunder.author_position_count.last
}}</span>
</div>
}
</div>
<h4>Publikationen</h4>
<ul class="publication-list">
@for (id of getSelectedPublicationIdsPage(); track id) {
<li class="publication-item" (click)="togglePublication(id)">
<span class="publication-title">{{
getPublicationTitle(id)
}}</span>
@if (expandedPublicationId === id) {
<div class="publication-more-info">
<span class="mehr-infos-label">Mehr Infos</span>
<a
[href]="getPublicationUrl(id)"
target="_blank"
rel="noopener"
(click)="openPublication($event, id)"
class="publication-link-icon"
title="Publikation öffnen"
>
<span class="material-icons">open_in_new</span>
</a>
</div>
}
</li>
}
</ul>
@if (hasPublicationPagination()) {
<div class="publication-pagination">
<button
[disabled]="selectedPublicationPage === 1"
(click)="setPublicationPage(selectedPublicationPage - 1)"
>
Zurück
</button>
<span
>Seite {{ selectedPublicationPage }} von
{{ getSelectedPublicationPageCount() }}</span
>
<button
[disabled]="
selectedPublicationPage === getSelectedPublicationPageCount()
"
(click)="setPublicationPage(selectedPublicationPage + 1)"
>
Weiter
</button>
</div>
}
</div>
} @else {
<div class="funding-detail empty">
<p>Klicke auf einen Förderer für Details.</p>
</div>
}
</div>
</div>
}
@@ -0,0 +1,298 @@
.message {
padding: 16px;
color: #666;
}
.funding-container {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
.filter-bar {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
span {
font-weight: 500;
color: #555;
}
button {
padding: 6px 14px;
border: 1px solid #ccc;
border-radius: 20px;
background: white;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
&:hover {
background: #f0f0f0;
}
}
button:nth-child(2) {
background: #f0f6ff;
color: #0b63ce;
border-color: #bdd4ff;
}
button:nth-child(3) {
background: #effaf3;
color: #24834f;
border-color: #bdebcf;
}
button:nth-child(4) {
background: #f6f0ff;
color: #7255d9;
border-color: #d8cafe;
}
button:nth-child(5) {
background: #fff7e8;
color: #c67500;
border-color: #ffd796;
}
}
.funding-content {
display: flex;
gap: 24px;
align-items: flex-start;
}
.funding-list {
flex: 1;
table {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #333;
}
tr {
cursor: pointer;
transition: background 0.15s;
&:hover {
background: #f5f5f5;
}
&.selected {
background: #f0f0f0;
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
}
.funder-name {
color: #333;
font-weight: 500;
}
}
}
.funding-detail {
width: 440px;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
&.empty {
display: flex;
align-items: center;
justify-content: center;
color: #999;
min-height: 200px;
}
h3 {
margin: 0 0 16px 0;
font-size: 16px;
color: #333;
}
h4 {
margin: 16px 0 8px 0;
font-size: 14px;
color: #555;
}
}
.position-stats {
display: flex;
gap: 12px;
margin-bottom: 16px;
width: fit-content;
margin-left: auto;
margin-right: auto;
.stat {
flex: 0.0 auto;
min-width: 100px;
text-align: center;
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 10px;
.stat-label {
display: block;
font-size: 12px;
color: #666;
margin-bottom: 4px;
}
.stat-value {
display: block;
font-size: 22px;
font-weight: bold;
color: #333;
}
}
.stat-first {
background: #effaf3;
border-color: #bdebcf;
}
.stat-middle {
background: #f6f0ff;
border-color: #d8cafe;
}
.stat-last {
background: #fff7e8;
border-color: #ffd796;
}
}
.publication-list {
list-style: none;
padding: 0;
margin: 0;
max-height: 300px;
overflow-y: auto;
li {
padding: 6px 0;
border-bottom: 1px solid #5b5555;
font-size: 13px;
a {
color: #2563eb;
text-decoration: none;
word-break: break-all;
&:hover {
color: #1d4ed8;
text-decoration: underline;
}
}
}
}
.publication-pagination {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
button {
padding: 4px 10px;
border: 1px solid #d0d0d0;
border-radius: 6px;
background: white;
cursor: pointer;
font-size: 12px;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
span {
font-size: 12px;
color: #666;
}
}
.funding-summary {
margin-bottom: 16px;
.summary-line {
margin: 0 0 4px 0;
font-size: 14px;
color: #333;
}
.summary-label {
color: #333;
}
.summary-value {
font-weight: 600;
color: #333;
}
}
.publication-item {
padding: 8px 0;
border-bottom: 2px solid #5b5555;
cursor: pointer;
&:hover {
background: #f9f9f9;
}
}
.publication-title {
font-size: 0.875rem;
color: #333;
white-space: normal;
word-break: break-word;
display: block;
}
.publication-more-info {
display: flex;
align-items: center;
flex-direction: row;
gap: 4px;
margin-top: 6px;
}
.mehr-infos-label {
font-size: 0.8rem;
color: #1976d2;
font-weight: 500;
}
.publication-link-icon {
display: flex;
align-items: center;
color: #1976d2;
text-decoration: none;
flex-shrink: 0;
.material-icons {
font-size: 16px;
}
&:hover {
color: #0d47a1;
}
}
@@ -0,0 +1,270 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { PersonsService } from '../../api';
import { FundingService } from '../../api';
@Component({
selector: 'app-person-funding',
imports: [CommonModule],
templateUrl: './person-funding.component.html',
styleUrl: './person-funding.component.scss',
})
export class PersonFundingComponent implements OnInit {
private route = inject(ActivatedRoute);
private router = inject(Router);
private fundingApi = inject(FundingService);
private initialSelectedFunderKey: string | null = null;
private initialPublicationPage = 1;
private initialFunderListPage = 1;
funders: any[] = [];
filteredFunders: any[] = [];
selectedFunder: any = null;
selectedFunderListPage = 1;
selectedPublicationPage = 1;
readonly funderListPageSize = 10;
readonly publicationPageSize = 10;
activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all';
loading = true;
error = false;
expandedPublicationId: string | null = null;
ngOnInit(): void {
this.route.parent?.paramMap.subscribe(params => {
const authorId = params.get('id') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder');
this.initialPublicationPage = this.parsePageParam(
this.route.snapshot.queryParamMap.get('publicationPage') ?? this.route.snapshot.queryParamMap.get('page')
);
this.initialFunderListPage = this.parsePageParam(this.route.snapshot.queryParamMap.get('funderPage'));
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (authorId) {
this.fundingApi.getFundersByAuthor(authorId).subscribe({
next: (result: any) => {
this.funders = result.funders ?? [];
this.applyFilter();
this.selectedFunderListPage = this.clampPage(this.initialFunderListPage, this.getFunderListPageCount());
this.restoreSelectedFunderFromUrl();
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
}
});
}
});
}
selectFunder(funder: any): void {
this.selectedFunder = funder;
this.selectedPublicationPage = 1;
this.updateQueryParams();
}
setFilter(filter: 'all' | 'first' | 'middle' | 'last'): void {
this.activeFilter = filter;
this.applyFilter();
this.updateQueryParams();
}
private applyFilter(): void {
this.selectedFunder = null;
this.selectedFunderListPage = 1;
this.selectedPublicationPage = 1;
if (this.activeFilter === 'all') {
this.filteredFunders = this.funders;
} else {
this.filteredFunders = this.funders.filter(
f => f.author_position_count[this.activeFilter] > 0
);
}
}
private restoreSelectedFunderFromUrl(): void {
if (!this.initialSelectedFunderKey) {
return;
}
const matchedFunder = this.filteredFunders.find(
(funder: any) => this.getFunderKey(funder) === this.initialSelectedFunderKey
);
if (matchedFunder) {
this.selectedFunder = matchedFunder;
const matchedIndex = this.filteredFunders.findIndex(
(funder: any) => this.getFunderKey(funder) === this.getFunderKey(matchedFunder)
);
if (matchedIndex >= 0) {
this.selectedFunderListPage = Math.floor(matchedIndex / this.funderListPageSize) + 1;
}
this.selectedPublicationPage = this.clampPublicationPage(
this.initialPublicationPage,
this.getPublicationPageCountForFunder(matchedFunder),
);
this.updateQueryParams();
} else {
this.updateQueryParams();
}
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null,
publicationPage: this.selectedFunder ? this.selectedPublicationPage : null,
funderPage: this.selectedFunderListPage
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
private getFunderKey(funder: any): string {
return funder.funder_id ?? funder.funder_name ?? '';
}
private isValidFilter(value: string | null): value is 'all' | 'first' | 'middle' | 'last' {
return value === 'all' || value === 'first' || value === 'middle' || value === 'last';
}
getPublicationCount(funder: any): number {
if (this.activeFilter === 'all') {
return funder.publication_count ?? 0;
}
return funder.author_position_count?.[this.activeFilter] ?? 0;
}
getPublicationIds(funder: any): string[] {
if (this.activeFilter === 'all') {
return [
...funder.publication_ids.first,
...funder.publication_ids.middle,
...funder.publication_ids.last,
...funder.publication_ids.unknown
];
}
return funder.publication_ids[this.activeFilter] ?? [];
}
getPagedFunders(): any[] {
const startIndex = (this.selectedFunderListPage - 1) * this.funderListPageSize;
return this.filteredFunders.slice(startIndex, startIndex + this.funderListPageSize);
}
hasFunderListPagination(): boolean {
return this.getFunderListPageCount() > 1;
}
getFunderListPageCount(): number {
return Math.max(1, Math.ceil(this.filteredFunders.length / this.funderListPageSize));
}
setFunderListPage(page: number): void {
this.selectedFunderListPage = this.clampPage(page, this.getFunderListPageCount());
this.updateQueryParams();
}
getSelectedPublicationIdsPage(): string[] {
if (!this.selectedFunder) {
return [];
}
const allPublicationIds = this.getPublicationIds(this.selectedFunder);
const startIndex = (this.selectedPublicationPage - 1) * this.publicationPageSize;
return allPublicationIds.slice(startIndex, startIndex + this.publicationPageSize);
}
hasPublicationPagination(): boolean {
return this.getSelectedPublicationPageCount() > 1;
}
getSelectedPublicationPageCount(): number {
if (!this.selectedFunder) {
return 1;
}
return this.getPublicationPageCountForFunder(this.selectedFunder);
}
setPublicationPage(page: number): void {
const totalPages = this.getSelectedPublicationPageCount();
this.selectedPublicationPage = this.clampPublicationPage(page, totalPages);
this.updateQueryParams();
}
openPublication(event: MouseEvent, publicationId: string): void {
event.preventDefault();
const url = this.getPublicationUrl(publicationId);
window.open(url, '_blank', 'noopener');
}
getPositionLabel(position: string): string {
const labels: Record<string, string> = {
first: 'Erstautor',
middle: 'Mitautor',
last: 'Letztautor',
unknown: 'Unbekannt'
};
return labels[position] ?? position;
}
shouldShowPosition(position: 'first' | 'middle' | 'last'): boolean {
return this.activeFilter === 'all' || this.activeFilter === position;
}
getUniquePublicationCount(): number {
const allIds = new Set<string>();
for (const funder of this.funders) {
if (this.activeFilter === 'all') {
for (const ids of Object.values(funder.publication_ids) as string[][]) {
ids.forEach((id: string) => allIds.add(id));
}
} else {
(funder.publication_ids[this.activeFilter] ?? []).forEach((id: string) =>
allIds.add(id),
);
}
}
return allIds.size;
}
getPublicationUrl(publicationId: string): string {
return this.selectedFunder?.publication_urls?.[publicationId] ?? publicationId;
}
private getPublicationPageCountForFunder(funder: any): number {
const publicationCount = this.getPublicationIds(funder).length;
return Math.max(1, Math.ceil(publicationCount / this.publicationPageSize));
}
private clampPublicationPage(page: number, totalPages: number): number {
return this.clampPage(page, totalPages);
}
private clampPage(page: number, totalPages: number): number {
return Math.min(Math.max(page, 1), totalPages);
}
private parsePageParam(value: string | null): number {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1) {
return 1;
}
return parsed;
}
getPublicationTitle(publicationId: string): string {
const title = this.selectedFunder?.publication_titles?.[publicationId];
if (title) return title;
const parts = publicationId.split('/');
return parts[parts.length - 1] ?? publicationId;
}
togglePublication(id: string): void {
this.expandedPublicationId = this.expandedPublicationId === id ? null : id;
}
}
@@ -1,9 +1,14 @@
<aside class="interest-card">
<h3>Interessant für</h3>
<div class="interest-header">
<h3>Interessant für</h3>
@if (tags().length > 0) {
<span class="interest-footnote">* Anzahl Publikationen zum Thema</span>
}
</div>
<div class="interest-tags">
@if (tags().length > 0) {
@for (tag of tags(); track tag.label) {
<button type="button" class="interest-tag-button">{{ tag.label }}</button>
<button type="button" class="interest-tag-button">{{ tag.label }} ({{ tag.count }}*)</button>
}
} @else {
<span class="interest-empty">Keine Themen gefunden</span>
@@ -10,8 +10,15 @@
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
}
.interest-card h3 {
.interest-header {
display: flex;
align-items: baseline;
gap: 10px;
margin: 0 0 18px;
}
.interest-card h3 {
margin: 0;
font-size: 14px;
font-weight: 700;
}
@@ -48,6 +55,11 @@
}
}
.interest-footnote {
color: var(--sg-text-muted);
font-size: 11px;
}
.interest-tags .interest-empty {
padding: 9px 16px;
border: 1px solid #e2e8f0;
@@ -1,12 +1,14 @@
import { Component, input, computed } from '@angular/core';
import { WorkTopic } from '../../api';
import { TopicCount } from '../../api';
interface InterestTag {
label: string;
score: number;
count: number;
}
const MAX_TAGS = 5;
@Component({
selector: 'app-person-interesting',
imports: [],
@@ -14,23 +16,19 @@ interface InterestTag {
styleUrl: './person-interesting.component.scss',
})
export class PersonInterestingComponent {
readonly topics = input<WorkTopic[] | null>(null);
readonly topics = input<TopicCount[] | null>(null);
readonly tags = computed<InterestTag[]>(() => {
const topicsList = this.topics() ?? [];
const grouped = new Map<string, number>();
const tags: InterestTag[] = [];
for (const topic of topicsList) {
const label = (topic.subfield?.display_name ?? '').trim();
const label = (topic.name ?? '').trim();
if (!label) continue;
const score = typeof topic.score === 'number' ? (topic.score as number) : 0;
grouped.set(label, (grouped.get(label) ?? 0) + score);
tags.push({ label, count: topic.count ?? 0 });
}
return Array.from(grouped.entries())
.map(([label, score]) => ({ label, score }))
.sort((a, b) => b.score - a.score)
.slice(0, 8);
return tags.sort((a, b) => b.count - a.count).slice(0, MAX_TAGS);
});
}
@@ -92,11 +92,13 @@
</button>
</div>
<h2 class="person-name">{{ person.display_name }}</h2>
<p class="institution">{{ institution(person) }}</p>
<p class="institution"><span>{{ institution(person)?.display_name }}</span><img alt="" class="flag-img"
[src]="`https://flagcdn.io/${institution(person)?.country_code?.toLowerCase()}.svg`" height="15">
</p>
<p class="person-id">{{ getDistinguishingId(person) }}</p>
<p class="stats">
Works: {{ person.works_count }} ·
Citations: {{ person.cited_by_count }}
Publikationen: {{ person.works_count }} ·
Zitationen: {{ person.cited_by_count }}
</p>
</div>
</div>
@@ -182,21 +184,9 @@
}
</div>
<div class="checkbox-list">
@for (topic of filteredTopicsList; track topic) {
<label class="checkbox-label">
<input type="checkbox" [checked]="isTopicSelected(topic)" (change)="toggleTopic(topic)" />
<span class="checkbox-text">{{ topic }}</span>
</label>
}
@if (topicsList.length > 5 && !topicSearchControl.value) {
<button class="show-more-btn" (click)="toggleShowAllTopics()">
<span>{{ showAllTopics ? 'Weniger anzeigen' : 'Mehr anzeigen' }}</span>
<mat-icon>{{ showAllTopics ? 'expand_less' : 'expand_more' }}</mat-icon>
</button>
}
</div>
<app-topic-hierarchy [selectedTopics]="selectedTopics" [searchQuery]="topicSearchControl.value"
(selectionChange)="onTopicSelectionChange($event)">
</app-topic-hierarchy>
</div>
<!-- Section 2: Institution Filter -->
@@ -212,6 +202,36 @@
</button>
}
</div>
<div class="year-filter-wrapper" style="margin-top: 12px; display: flex; flex-direction: column; gap: 8px;">
<mat-checkbox [formControl]="yearFilterEnabledControl" (change)="applySidebarFilters()">
<span style="font-size: 12px; font-weight: 500; color: var(--sg-text);">Zusammenarbeit nach Jahr
filtern</span>
</mat-checkbox>
@if (yearFilterEnabledControl.value) {
<div class="year-filter-options" style="display: flex; flex-direction: column; gap: 8px; padding-left: 28px;">
<mat-radio-group [formControl]="filterModeControl" (change)="applySidebarFilters()"
style="display: flex; gap: 16px;">
<mat-radio-button value="in"><span style="font-size: 12px; color: var(--sg-text);">Genau
in</span></mat-radio-button>
<mat-radio-button value="from"><span
style="font-size: 12px; color: var(--sg-text);">Seit</span></mat-radio-button>
</mat-radio-group>
<mat-form-field appearance="outline" style="width: 100%; font-size: 13px; margin-top: 4px;">
<mat-label>Jahr</mat-label>
<input matInput type="number" [formControl]="filterYearControl" (change)="applySidebarFilters()"
(keyup.enter)="applySidebarFilters()" placeholder="Z. B. 2025" />
@if (filterYearControl.hasError('min')) {
<mat-error>Jahr muss ≥ 1900 sein</mat-error>
}
@if (filterYearControl.hasError('max')) {
<mat-error>Zukünftige Jahre sind nicht erlaubt</mat-error>
}
</mat-form-field>
</div>
}
</div>
</div>
<!-- Sidebar Footer Action showing matches count -->
@@ -15,6 +15,7 @@
.results-column {
display: flex;
min-width: 0;
flex-direction: column;
gap: 20px;
min-width: 0;
@@ -268,6 +269,9 @@
}
.institution {
display: flex;
align-items: center;
gap: 15px;
margin: 0;
font-size: 12px;
color: var(--sg-text-muted);
@@ -276,6 +280,11 @@
white-space: nowrap;
}
.flag-img {
border: 1px solid;
vertical-align: -10px;
}
.person-id {
margin: 2px 0 0;
font-size: 10px;
@@ -287,7 +296,7 @@
.stats {
margin: 4px 0 0;
font-size: 12px;
font-size: 10px;
color: var(--sg-text-muted);
}
@@ -2,7 +2,7 @@ import { Component, inject, signal, DestroyRef } from '@angular/core';
import { Router, RouterLink, ActivatedRoute } from '@angular/router';
import { CommonModule } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon';
import { MatPaginatorModule } from '@angular/material/paginator';
@@ -10,11 +10,17 @@ import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { CustomAuthor, PersonsSearchService } from '../../api';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio';
import { CustomAuthor } from '../../api/model/custom-author';
// import { PersonsSearchService } from '../../api/api/persons-search.service';
import { DehydratedInstitution, PersonsService } from '../../api';
import { TopicsService } from '../../api/api/topics.service';
import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component';
import { SharedStateService } from '../../shared/services/shared-state.service';
import { PaginationService } from '../../shared/services/pagination.service';
import { finalize } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-person-list',
@@ -28,20 +34,26 @@ import { finalize } from 'rxjs';
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatCheckboxModule,
MatRadioModule,
TopicHierarchyComponent,
],
templateUrl: './person-list.component.html',
styleUrl: './person-list.component.scss',
standalone: true,
})
export class PersonListComponent {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly personsSearchService = inject(PersonsSearchService);
private readonly personsService = inject(PersonsService);
private readonly topicsService = inject(TopicsService);
private readonly destroyRef = inject(DestroyRef);
private readonly snackBar = inject(MatSnackBar);
public readonly state = inject(SharedStateService);
public readonly paginationService = inject(PaginationService);
private readonly defaultIncludes =
'display_name,works_count,cited_by_count,topics,orcid,relevance_rating,affiliations';
'display_name,works_count,cited_by_count,topics,orcid,relevance_rating,last_known_institutions,affiliations';
readonly loadingState = signal<boolean>(false);
persons: CustomAuthor[] = [];
@@ -69,6 +81,12 @@ export class PersonListComponent {
sortControl = new FormControl('relevance', { nonNullable: true });
topicSearchControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl('', { nonNullable: true });
yearFilterEnabledControl = new FormControl(false, { nonNullable: true });
filterModeControl = new FormControl<'in' | 'from'>('from', { nonNullable: true });
filterYearControl = new FormControl<number>(new Date().getFullYear() - 1, {
nonNullable: true,
validators: [Validators.min(1900), Validators.max(new Date().getFullYear())]
});
showAllTopics = false;
// Bookmarking
@@ -83,6 +101,9 @@ export class PersonListComponent {
const page = params['page'] ? Number.parseInt(params['page'], 10) : 1;
const pageSize = params['pageSize'] ? Number.parseInt(params['pageSize'], 10) : 10;
const institutionName = params['institutionName'] || '';
const yearFilterEnabled = params['yearFilterEnabled'] === 'true';
const filterMode = (params['filterMode'] === 'in' || params['filterMode'] === 'from') ? params['filterMode'] : 'from';
const filterYear = params['filterYear'] ? Number.parseInt(params['filterYear'], 10) : (new Date().getFullYear() - 1);
const topics = this.parseQueryParamArray(params['topic']);
@@ -97,8 +118,17 @@ export class PersonListComponent {
if (this.institutionControl.value !== institutionName) {
this.institutionControl.setValue(institutionName);
}
if (this.yearFilterEnabledControl.value !== yearFilterEnabled) {
this.yearFilterEnabledControl.setValue(yearFilterEnabled);
}
if (this.filterModeControl.value !== filterMode) {
this.filterModeControl.setValue(filterMode);
}
if (this.filterYearControl.value !== filterYear) {
this.filterYearControl.setValue(filterYear);
}
this.load(query, page, pageSize, topics, institutionName);
this.load(query, page, pageSize, topics, institutionName, yearFilterEnabled, filterMode, filterYear);
});
}
@@ -107,17 +137,23 @@ export class PersonListComponent {
page: number = 1,
pageSize: number = 10,
topics?: string[],
institutionName?: string
institutionName?: string,
yearFilterEnabled: boolean = false,
filterMode: 'in' | 'from' = 'from',
filterYear?: number
): void {
this.loadingState.set(true);
this.personsSearchService.searchPersonsList(
this.personsService.searchPersonsList(
query || undefined,
institutionName || undefined,
topics?.length ? topics : undefined,
page,
pageSize,
this.defaultIncludes
this.defaultIncludes,
yearFilterEnabled ? true : undefined,
yearFilterEnabled ? filterMode : undefined,
yearFilterEnabled ? filterYear : undefined
)
.pipe(
finalize(() => this.loadingState.set(false)),
@@ -195,10 +231,15 @@ export class PersonListComponent {
list.push({ category: 'topic', value: t, label: t });
});
if (this.institutionControl.value) {
let label = `Institution: ${this.institutionControl.value}`;
if (this.yearFilterEnabledControl.value) {
const modeLabel = this.filterModeControl.value === 'in' ? 'in' : 'from';
label += ` (${modeLabel} ${this.filterYearControl.value})`;
}
list.push({
category: 'institutionName',
value: this.institutionControl.value,
label: `Institution: ${this.institutionControl.value}`
label: label
});
}
return list;
@@ -209,6 +250,9 @@ export class PersonListComponent {
this.selectedTopics.delete(filter.value);
} else if (filter.category === 'institutionName') {
this.institutionControl.setValue('');
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
}
this.applySidebarFilters();
}
@@ -216,14 +260,24 @@ export class PersonListComponent {
clearAllFilters(): void {
this.selectedTopics.clear();
this.institutionControl.setValue('');
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
this.applySidebarFilters();
}
applySidebarFilters(): void {
if (this.yearFilterEnabledControl.value && this.filterYearControl.invalid) {
return;
}
this.router.navigate([], {
queryParams: {
topic: this.selectedTopics.size ? Array.from(this.selectedTopics) : null,
institutionName: this.institutionControl.value || null,
yearFilterEnabled: this.institutionControl.value && this.yearFilterEnabledControl.value ? 'true' : null,
filterMode: this.institutionControl.value && this.yearFilterEnabledControl.value ? this.filterModeControl.value : null,
filterYear: this.institutionControl.value && this.yearFilterEnabledControl.value ? this.filterYearControl.value : null,
strict: null,
page: 1,
},
queryParamsHandling: 'merge',
@@ -285,12 +339,11 @@ export class PersonListComponent {
return `${start}-${end} von ${this.total} Personen`;
}
// Model parsing / UI Helpers
institution(person: CustomAuthor): string {
institution(person: CustomAuthor): DehydratedInstitution | undefined {
return (
person.affiliations?.[0]?.institution?.display_name ||
person.last_known_institutions?.[0]?.display_name ||
'Unbekannte Institution'
person.last_known_institutions?.[0] ||
person.affiliations?.[person.affiliations.length - 1]?.institution ||
undefined
);
}
@@ -327,6 +380,11 @@ export class PersonListComponent {
}
}
onTopicSelectionChange(newSelection: Set<string>): void {
this.selectedTopics = newSelection;
this.applySidebarFilters();
}
isBookmarked(person: CustomAuthor): boolean {
return !!person.id && this.bookmarkedIds.has(person.id);
}
@@ -344,9 +402,6 @@ export class PersonListComponent {
if (person.orcid) {
return person.orcid.replace('https://orcid.org/', '');
}
if (person.id) {
return person.id.replace('https://openalex.org/', '');
}
return '';
}
@@ -112,7 +112,16 @@
*ngFor="let item of timelineItems; let index = index; trackBy: trackByYear"
class="timeline-item"
>
<h3>{{ getMainTopic(item) }}</h3>
<h3>
<button
type="button"
class="main-topic-button"
[disabled]="!getMainTopicItem(item)?.id"
(click)="selectTopic(getMainTopicItem(item)!)"
>
{{ getMainTopic(item) }}
</button>
</h3>
<span class="publication-count">
{{ item.publication_count }}
@@ -121,14 +130,17 @@
<div class="topic-list">
<ng-container *ngIf="getDisplayedTopics(item).length > 0; else noTopicsForYear">
<span
<button
type="button"
*ngFor="let topic of getDisplayedTopics(item); trackBy: trackByTopic"
class="topic-chip"
[ngClass]="getColorClass(index)"
[disabled]="!topic.id"
(click)="selectTopic(topic)"
>
<span class="topic-name">{{ topic.name }}</span>
<span class="topic-count">{{ topic.count }}</span>
</span>
</button>
</ng-container>
<ng-template #noTopicsForYear>
@@ -155,7 +167,16 @@
<div class="phase-title-block">
<span class="phase-years">{{ getPhaseYearLabel(phase) }}</span>
<h3>{{ phase.primaryTopicName }}</h3>
<h3>
<button
type="button"
class="main-topic-button"
[disabled]="!phase.primaryTopic.id"
(click)="selectTopic(phase.primaryTopic)"
>
{{ phase.primaryTopicName }}
</button>
</h3>
<span class="phase-publications">
{{ phase.publication_count }}
{{ phase.publication_count === 1 ? 'Publikation' : 'Publikationen' }}
@@ -165,14 +186,17 @@
<div class="phase-topics">
<ng-container *ngIf="phase.topics.length > 0; else noPhaseTopics">
<span
<button
type="button"
*ngFor="let topic of phase.topics; trackBy: trackByTopic"
class="topic-chip"
[ngClass]="getColorClass(index)"
[disabled]="!topic.id"
(click)="selectTopic(topic)"
>
<span class="topic-name">{{ topic.name }}</span>
<span class="topic-count">{{ topic.count }}</span>
</span>
</button>
</ng-container>
<ng-template #noPhaseTopics>
@@ -208,16 +232,19 @@
else noPhaseYearTopics
"
>
<span
<button
type="button"
*ngFor="
let topic of getDisplayedTopicsForPrimaryTopic(year, phase.primaryTopicName);
trackBy: trackByTopic
"
class="mini-topic-chip"
[disabled]="!topic.id"
(click)="selectTopic(topic)"
>
<span>{{ topic.name }}</span>
<strong>{{ topic.count }}</strong>
</span>
</button>
</ng-container>
<ng-template #noPhaseYearTopics>
@@ -246,4 +273,4 @@
Keine Timeline-Daten vorhanden.
</div>
</ng-template>
</section>
</section>
@@ -315,6 +315,32 @@
font-size: 12px;
}
.main-topic-button {
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
font-weight: inherit;
line-height: inherit;
cursor: pointer;
&:hover:not(:disabled) {
color: #0057ff;
text-decoration: underline;
}
&:focus-visible {
outline: 2px solid #0057ff;
outline-offset: 3px;
border-radius: 3px;
}
&:disabled {
cursor: default;
}
}
.topic-list {
display: flex;
flex-direction: column;
@@ -335,6 +361,24 @@
font-size: 12px;
font-weight: 500;
line-height: 1.25;
border: 0;
font-family: inherit;
cursor: pointer;
transition: transform 0.15s ease, box-shadow 0.15s ease;
&:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
}
&:focus-visible {
outline: 2px solid #0057ff;
outline-offset: 2px;
}
&:disabled {
cursor: default;
}
}
.topic-name {
@@ -515,6 +559,22 @@
color: #40506f;
font-size: 11px;
line-height: 1.25;
border: 0;
font-family: inherit;
cursor: pointer;
&:hover:not(:disabled) {
color: #0057ff;
}
&:focus-visible {
outline: 2px solid #0057ff;
outline-offset: 2px;
}
&:disabled {
cursor: default;
}
span {
overflow-wrap: anywhere;
@@ -686,4 +746,4 @@
.phase-year-row {
grid-template-columns: 1fr;
}
}
}
@@ -9,6 +9,7 @@ import {
} from '@angular/core';
export interface TopicTimelineTopic {
id?: string;
name: string;
count: number;
}
@@ -27,11 +28,17 @@ export interface TimelineYearRange {
endYear: number;
}
export interface TimelineTopicSelection {
topic: TopicTimelineTopic;
years: number[];
}
interface ResearchTimelinePhase {
id: string;
startYear: number;
endYear: number;
publication_count: number;
primaryTopic: TopicTimelineTopic;
primaryTopicName: string;
years: TopicTimelineElement[];
topics: TopicTimelineTopic[];
@@ -41,6 +48,7 @@ interface WorkingResearchTimelinePhase {
startYear: number;
endYear: number;
publication_count: number;
primaryTopic: TopicTimelineTopic;
primaryTopicName: string;
years: TopicTimelineElement[];
}
@@ -62,6 +70,7 @@ export class ResearchTimelineComponent implements OnChanges {
@Output() viewModeChange = new EventEmitter<TimelineViewMode>();
@Output() yearRangeChange = new EventEmitter<TimelineYearRange>();
@Output() topicSelect = new EventEmitter<TimelineTopicSelection>();
timelineViewMode: TimelineViewMode = 'years';
@@ -167,12 +176,27 @@ export class ResearchTimelineComponent implements OnChanges {
this.emitYearRangeChange();
}
selectTopic(topic: TopicTimelineTopic): void {
if (!topic.id) {
return;
}
this.topicSelect.emit({
topic,
years: this.createSelectedYears(),
});
}
getPrimaryTopic(item: TopicTimelineElement): TopicTimelineTopic | undefined {
return (item.primary_topics ?? [])[0];
}
getMainTopic(item: TopicTimelineElement): string {
return this.getPrimaryTopic(item)?.name ?? this.getFirstTopic(item)?.name ?? 'Keine Topics';
return this.getMainTopicItem(item)?.name ?? 'Keine Topics';
}
getMainTopicItem(item: TopicTimelineElement): TopicTimelineTopic | undefined {
return this.getPrimaryTopic(item) ?? this.getFirstTopic(item);
}
getDisplayedTopics(item: TopicTimelineElement): TopicTimelineTopic[] {
@@ -276,7 +300,10 @@ export class ResearchTimelineComponent implements OnChanges {
if (candidates.length === 0) {
this.pushWorkingPhase(phases, currentPhase);
currentPhase = this.createWorkingPhase(item, this.getMainTopic(item));
currentPhase = this.createWorkingPhase(
item,
this.getMainTopicItem(item) ?? { name: 'Keine Topics', count: 0 },
);
continue;
}
@@ -299,7 +326,7 @@ export class ResearchTimelineComponent implements OnChanges {
}
this.pushWorkingPhase(phases, currentPhase);
currentPhase = this.createWorkingPhase(item, candidates[0].name);
currentPhase = this.createWorkingPhase(item, candidates[0]);
}
this.pushWorkingPhase(phases, currentPhase);
@@ -309,13 +336,14 @@ export class ResearchTimelineComponent implements OnChanges {
private createWorkingPhase(
item: TopicTimelineElement,
primaryTopicName: string,
primaryTopic: TopicTimelineTopic,
): WorkingResearchTimelinePhase {
return {
startYear: item.year,
endYear: item.year,
publication_count: item.publication_count,
primaryTopicName,
primaryTopic,
primaryTopicName: primaryTopic.name,
years: [item],
};
}
@@ -343,6 +371,7 @@ export class ResearchTimelineComponent implements OnChanges {
): TopicTimelineTopic[] {
const counts = new Map<string, number>();
const originalNames = new Map<string, string>();
const ids = new Map<string, string>();
for (const year of years) {
for (const topic of year.topics ?? []) {
@@ -353,12 +382,16 @@ export class ResearchTimelineComponent implements OnChanges {
const normalizedName = this.normalizeTopicName(topic.name);
originalNames.set(normalizedName, topic.name);
if (topic.id) {
ids.set(normalizedName, topic.id);
}
counts.set(normalizedName, (counts.get(normalizedName) ?? 0) + topic.count);
}
}
return Array.from(counts.entries())
.map(([normalizedName, count]) => ({
id: ids.get(normalizedName),
name: originalNames.get(normalizedName) ?? normalizedName,
count,
}))
@@ -372,6 +405,13 @@ export class ResearchTimelineComponent implements OnChanges {
.slice(0, this.displayedPhaseTopicLimit);
}
private createSelectedYears(): number[] {
return Array.from(
{ length: this.selectedEndYear - this.selectedStartYear + 1 },
(_, index) => this.selectedStartYear + index,
);
}
private getDominantPrimaryTopicCandidates(item: TopicTimelineElement): TopicTimelineTopic[] {
const primaryTopics = item.primary_topics ?? [];
@@ -443,4 +483,4 @@ export class ResearchTimelineComponent implements OnChanges {
endYear: this.selectedEndYear,
});
}
}
}
@@ -8,5 +8,6 @@
[endYear]="timelineEndYear"
(viewModeChange)="onTimelineViewModeChange($event)"
(yearRangeChange)="onTimelineYearRangeChange($event)"
(topicSelect)="onTimelineTopicSelect($event)"
></app-research-timeline>
</section>
</section>
@@ -4,11 +4,13 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { combineLatest, distinctUntilChanged, map } from 'rxjs';
import { TopicCount, TopicsByYear, WorksService } from '../../api';
import { TopicCount,TopicsByYear } from '../../api';
import { WorksService } from '../../api';
import {
ResearchTimelineComponent,
TimelineViewMode,
TimelineYearRange,
TimelineTopicSelection,
TopicTimelineElement,
TopicTimelineTopic,
} from './components/research-timeline/research-timeline.component';
@@ -88,6 +90,22 @@ export class PersonOverviewComponent implements OnInit {
);
}
onTimelineTopicSelect(selection: TimelineTopicSelection): void {
if (!selection.topic.id) {
return;
}
void this.router.navigate(['../publications'], {
relativeTo: this.route,
queryParams: {
publicationPage: 1,
publicationYear: selection.years,
publicationTopicId: selection.topic.id,
publicationTopicName: selection.topic.name,
},
});
}
private findAuthorId(paramMaps: readonly ParamMap[]): string {
return (
paramMaps
@@ -139,7 +157,8 @@ export class PersonOverviewComponent implements OnInit {
}
private mapTopicCounts(topics: TopicCount[] | undefined): TopicTimelineTopic[] {
return (topics ?? []).map((topic) => ({
return (topics ?? []).map((topic: TopicCount & { id?: string | null }) => ({
id: topic.id ?? undefined,
name: topic.name,
count: topic.count ?? 0,
}));
@@ -174,4 +193,4 @@ export class PersonOverviewComponent implements OnInit {
replaceUrl,
});
}
}
}
@@ -1,16 +1,16 @@
<div class="page">
<div class="section-heading">
<div>
<h6>Publikationen</h6>
<p>Übersicht der wissenschaftlichen Veröffentlichungen.</p>
</div>
<div>
<h6>Publikationen</h6>
<p>Übersicht der wissenschaftlichen Veröffentlichungen.</p>
</div>
<div class="publication-filter-stack">
<form class="publication-filters" [formGroup]="filterForm">
<mat-form-field>
<mat-label>Jahr</mat-label>
<mat-select
placeholder="Jahr"
formControlName="publicationYears"
multiple
(selectionChange)="resetAndLoad()"
(selectionChange)="applyFilters()"
>
@for (year of publicationYearOptions; track year) {
<mat-option [value]="year">{{ year }}</mat-option>
@@ -19,11 +19,11 @@
</mat-form-field>
<mat-form-field>
<mat-label>Typ</mat-label>
<mat-select
placeholder="Typ"
formControlName="types"
multiple
(selectionChange)="resetAndLoad()"
(selectionChange)="applyFilters()"
>
@for (type of typeOptions; track type.value) {
<mat-option [value]="type.value">{{ type.label }}</mat-option>
@@ -32,11 +32,11 @@
</mat-form-field>
<mat-form-field>
<mat-label>Sprache</mat-label>
<mat-select
placeholder="Sprache"
formControlName="languages"
multiple
(selectionChange)="resetAndLoad()"
(selectionChange)="applyFilters()"
>
@for (language of languageOptions; track language.value) {
<mat-option [value]="language.value">{{
@@ -46,11 +46,108 @@
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" (click)="clearFilters()">
<mat-form-field class="institution-filter">
<input
type="text"
matInput
[formControl]="institutionSearchControl"
[matAutocomplete]="institutionAutocomplete"
placeholder="Institution suchen"
/>
<mat-autocomplete
#institutionAutocomplete="matAutocomplete"
[displayWith]="displayInstitution"
(optionSelected)="selectInstitution($event)"
>
@for (institution of institutionOptions; track institution.id) {
<mat-option [value]="institution">
<span>{{ institution.display_name }}</span>
@if (institution.hint) {
<small>{{ institution.hint }}</small>
}
</mat-option>
}
@if (
!institutionLookupLoading &&
institutionOptions.length === 0 &&
institutionSearchControl.value
) {
<mat-option disabled>Keine Institution gefunden</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<mat-form-field class="topic-filter">
<input
type="text"
matInput
[formControl]="topicSearchControl"
[matAutocomplete]="topicAutocomplete"
placeholder="Topic suchen"
/>
<mat-autocomplete
#topicAutocomplete="matAutocomplete"
[displayWith]="displayTopic"
(optionSelected)="selectTopic($event)"
>
@for (topic of topicOptions; track topic.id) {
<mat-option [value]="topic">
<span>{{ topic.display_name }}</span>
@if (topic.hint) {
<small>{{ topic.hint }}</small>
}
</mat-option>
}
@if (
!topicLookupLoading &&
topicOptions.length === 0 &&
topicSearchControl.value
) {
<mat-option disabled>Kein Topic gefunden</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<button
class="reset-filter-btn"
mat-stroked-button
type="button"
(click)="clearFilters()"
aria-label="Filter zurücksetzen"
>
<mat-icon>filter_alt_off</mat-icon>
Zurücksetzen
<span>Zurücksetzen</span>
</button>
</form>
@if (selectedInstitutions.length || selectedTopics.length) {
<div class="selected-filter-chips" aria-label="Ausgewählte Filter">
@for (institution of selectedInstitutions; track institution.id) {
<span class="selected-filter-chip">
{{ institution.display_name }}
<button
type="button"
(click)="removeInstitution(institution)"
aria-label="Institution entfernen"
>
<mat-icon>close</mat-icon>
</button>
</span>
}
@for (topic of selectedTopics; track topic.id) {
<span class="selected-filter-chip">
{{ topic.display_name }}
<button
type="button"
(click)="removeTopic(topic)"
aria-label="Topic entfernen"
>
<mat-icon>close</mat-icon>
</button>
</span>
}
</div>
}
</div>
<div class="table-wrap">
@@ -64,14 +161,12 @@
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef>Titel</th>
<td mat-cell *matCellDef="let publication">
@if (doiUrl(publication.doi); as url) {
<a class="title" [href]="url" target="_blank" rel="noopener">
{{ publication.title || "Ohne Titel" }}
</a>
} @else {
<div class="title">{{ publication.title || "Ohne Titel" }}</div>
}
<div class="authors">Becker, A.; Müller, T.; Zhang, L.</div>
<a
class="title"
[routerLink]="['/publication', publicationKey(publication)]"
>
{{ publication.title || "Ohne Titel" }}
</a>
</td>
</ng-container>
@@ -102,6 +197,33 @@
</td>
</ng-container>
<ng-container matColumnDef="institutions">
<th mat-header-cell *matHeaderCellDef>Institutionen</th>
<td mat-cell *matCellDef="let publication">
@let publicationInstitutions = institutions(publication);
<div class="institution-tags" aria-label="Institutionen">
@for (
institution of publicationInstitutions.slice(0, 3);
track institution.id
) {
<span
class="publication-institution-tag"
[title]="institution.name"
>
{{ institution.name }}
</span>
} @empty {
<span class="empty-text">-</span>
}
@if (publicationInstitutions.length > 3) {
<span class="publication-institution-more">
+{{ publicationInstitutions.length - 3 }}
</span>
}
</div>
</td>
</ng-container>
<ng-container matColumnDef="citations">
<th mat-header-cell *matHeaderCellDef>Zitationen</th>
<td mat-cell *matCellDef="let publication">
@@ -112,14 +234,20 @@
<ng-container matColumnDef="topics">
<th mat-header-cell *matHeaderCellDef>Themen</th>
<td mat-cell *matCellDef="let publication">
@let publicationTopics = publication.topics ?? [];
<div class="topic-chips" aria-label="Themen">
@for (topic of (publication.topics ?? []).slice(0, 3); track topic.id) {
<app-chip variant="outlined" color="primary">
@for (topic of publicationTopics.slice(0, 3); track topic.id) {
<span class="publication-topic-tag" [title]="topic.display_name">
{{ topic.display_name }}
</app-chip>
</span>
} @empty {
<span class="empty-text">-</span>
}
@if (publicationTopics.length > 3) {
<span class="publication-topic-more">
+{{ publicationTopics.length - 3 }}
</span>
}
</div>
</td>
</ng-container>
@@ -6,10 +6,10 @@
.section-heading {
display: flex;
align-items: flex-start;
align-items: center;
justify-content: space-between;
gap: 24px;
margin-bottom: 22px;
gap: 18px;
margin-bottom: 18px;
}
h2 {
@@ -25,11 +25,20 @@ h2 {
font-size: 14px;
}
.publication-filter-stack {
display: flex;
align-items: flex-start;
flex-direction: column;
gap: 8px;
padding-top: 10px;
padding-bottom: 25px;
}
.publication-filters {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
align-items: flex-start;
align-items: center;
gap: 10px;
}
@@ -37,17 +46,117 @@ h2 {
width: 150px;
}
.publication-filters button {
.publication-filters .institution-filter,
.publication-filters .topic-filter {
width: 320px;
}
.publication-filters .reset-filter-btn {
min-width: 132px;
height: 42px;
border-color: var(--sg-border);
padding: 0 14px;
border-color: #d9e2f0;
border-radius: var(--sg-radius-sm);
color: var(--sg-text);
background: #fff;
}
.publication-filters .reset-filter-btn mat-icon {
margin-right: 6px;
width: 20px;
height: 20px;
font-size: 20px;
}
::ng-deep .publication-filters .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .publication-filters .mat-mdc-text-field-wrapper {
height: 42px;
background: #fff;
border-radius: var(--sg-radius-sm);
}
::ng-deep .publication-filters .mat-mdc-form-field-infix {
min-height: 42px;
padding-top: 11px;
padding-bottom: 9px;
}
::ng-deep .publication-filters .mdc-notched-outline__leading,
::ng-deep .publication-filters .mdc-notched-outline__notch,
::ng-deep .publication-filters .mdc-notched-outline__trailing {
border-color: #d9e2f0;
}
::ng-deep .publication-filters .mat-mdc-select-value,
::ng-deep .publication-filters input.mat-mdc-input-element {
color: var(--sg-text);
font-size: 14px;
}
::ng-deep .publication-filters .mat-mdc-select-placeholder,
::ng-deep .publication-filters input.mat-mdc-input-element::placeholder {
color: var(--sg-text-muted);
opacity: 1;
font-size: 14px;
}
::ng-deep .publication-filters .mat-mdc-form-field-icon-suffix,
::ng-deep .publication-filters .mat-mdc-select-arrow-wrapper {
transform: none;
}
::ng-deep .mat-mdc-option small {
display: block;
color: var(--sg-text-muted);
font-size: 11px;
line-height: 1.2;
}
.selected-filter-chips {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 6px;
max-width: 900px;
margin: 0;
}
.selected-filter-chip {
display: inline-flex;
align-items: center;
max-width: 320px;
min-height: 26px;
padding: 3px 4px 3px 9px;
border: 1px solid #d9e2f0;
border-radius: var(--sg-radius-sm);
background: #fff;
color: var(--sg-text);
font-size: 11px;
line-height: 1.2;
}
.selected-filter-chip button {
display: inline-grid;
place-items: center;
width: 20px;
height: 20px;
margin-left: 3px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
cursor: pointer;
}
.selected-filter-chip mat-icon {
width: 14px;
height: 14px;
font-size: 14px;
}
.table-wrap {
position: relative;
overflow-x: auto;
@@ -55,7 +164,7 @@ h2 {
table {
width: 100%;
min-width: 980px;
min-width: 1120px;
border-collapse: separate;
border-spacing: 0 10px;
overflow: hidden;
@@ -111,6 +220,63 @@ a.title:hover {
max-width: 320px;
}
.publication-topic-tag,
.publication-topic-more {
display: inline-flex;
align-items: center;
max-width: 180px;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: #fff;
color: var(--sg-text);
font-size: 11px;
line-height: 1.2;
}
.publication-topic-tag {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.publication-topic-more {
color: var(--sg-text-muted);
}
.institution-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
max-width: 280px;
}
.publication-institution-tag,
.publication-institution-more {
display: inline-flex;
align-items: center;
max-width: 180px;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: #fff;
color: var(--sg-text);
font-size: 11px;
line-height: 1.2;
}
.publication-institution-tag {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.publication-institution-more {
color: var(--sg-text-muted);
}
::ng-deep .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
@@ -155,12 +321,27 @@ mat-paginator {
flex-direction: column;
}
.publication-filter-stack {
align-items: stretch;
}
.publication-filters {
justify-content: stretch;
max-width: none;
}
.publication-filters mat-form-field,
.publication-filters button {
width: 100%;
}
.publication-filters .institution-filter,
.publication-filters .topic-filter {
width: 100%;
}
.selected-filter-chips {
justify-content: flex-start;
max-width: none;
}
}
@@ -1,6 +1,11 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { Component, DestroyRef, OnInit, ViewChild, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router';
import {
MatAutocompleteModule,
MatAutocompleteSelectedEvent,
} from '@angular/material/autocomplete';
import { MatIconModule } from '@angular/material/icon';
import {
MatPaginator,
@@ -12,46 +17,113 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
catchError,
combineLatest,
debounceTime,
distinctUntilChanged,
finalize,
map,
of,
switchMap,
} from 'rxjs';
import { Work, WorksService } from '../../api';
import { PaginationService } from '../../shared/services/pagination.service';
import { createLoadError } from '../../shared/utils/errorHandler';
import { ChipComponent } from '../../shared/ui/chip/chip.component';
interface InstitutionAutocompleteOption {
id?: string | null;
display_name?: string | null;
hint?: string | null;
cited_by_count?: number | null;
works_count?: number | null;
entity_type?: string | null;
external_id?: string | null;
}
interface InstitutionAutocompleteResponse {
results?: InstitutionAutocompleteOption[] | null;
}
interface TopicAutocompleteOption {
id?: string | null;
display_name?: string | null;
hint?: string | null;
cited_by_count?: number | null;
works_count?: number | null;
entity_type?: string | null;
external_id?: string | null;
}
interface TopicAutocompleteResponse {
results?: TopicAutocompleteOption[] | null;
}
interface PublicationFilterQueryState {
pageIndex: number;
pageSize: number;
publicationYears: number[];
types: string[];
languages: string[];
institutions: InstitutionAutocompleteOption[];
topics: TopicAutocompleteOption[];
}
@Component({
selector: 'app-person-publications',
imports: [
MatButtonModule,
MatAutocompleteModule,
ChipComponent,
MatIconModule,
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSnackBarModule,
MatTableModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './person-publications.component.html',
styleUrl: './person-publications.component.scss',
})
export class PersonPublicationsComponent implements OnInit {
@ViewChild(MatPaginator) paginator?: MatPaginator;
private readonly destroyRef = inject(DestroyRef);
displayedColumns: string[] = [
'title',
'type',
'year',
'language',
'institutions',
'topics',
'citations',
];
publications: Work[] = [];
total = 0;
loading = false;
institutionLookupLoading = false;
topicLookupLoading = false;
authorId = '';
currentPageIndex = 0;
institutionOptions: InstitutionAutocompleteOption[] = [];
selectedInstitutions: InstitutionAutocompleteOption[] = [];
topicOptions: TopicAutocompleteOption[] = [];
selectedTopics: TopicAutocompleteOption[] = [];
readonly institutionSearchControl = new FormControl<
string | InstitutionAutocompleteOption
>('', { nonNullable: true });
readonly topicSearchControl = new FormControl<string | TopicAutocompleteOption>('', {
nonNullable: true,
});
readonly filterForm = new FormGroup({
publicationYears: new FormControl<number[]>([], { nonNullable: true }),
@@ -61,6 +133,18 @@ export class PersonPublicationsComponent implements OnInit {
readonly publicationYearOptions = this.createPublicationYearOptions();
private readonly queryParamKeys = {
page: 'publicationPage',
pageSize: 'publicationPageSize',
years: 'publicationYear',
types: 'publicationType',
languages: 'publicationLanguage',
institutionIds: 'publicationInstitutionId',
institutionNames: 'publicationInstitutionName',
topicIds: 'publicationTopicId',
topicNames: 'publicationTopicName',
} as const;
readonly typeOptions = [
{ value: 'article', label: 'article' },
{ value: 'book', label: 'book' },
@@ -90,16 +174,28 @@ export class PersonPublicationsComponent implements OnInit {
constructor(
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly workService: WorksService,
private readonly httpClient: HttpClient,
public readonly paginationService: PaginationService,
private readonly snackBar: MatSnackBar,
) {}
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
this.authorId = params.get('id') ?? '';
this.resetAndLoad();
});
this.setupInstitutionAutocomplete();
this.setupTopicAutocomplete();
const parentParamMap = this.route.parent?.paramMap;
if (!parentParamMap) return;
combineLatest([parentParamMap, this.route.queryParamMap])
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(([params, queryParams]) => {
this.authorId = params.get('id') ?? '';
const queryState = this.parsePublicationFilterQueryParams(queryParams);
this.applyPublicationFilterQueryState(queryState);
this.load(queryState.pageIndex, queryState.pageSize);
});
}
load(pageIndex = 0, pageSize = this.paginationService.selection): void {
@@ -116,6 +212,8 @@ export class PersonPublicationsComponent implements OnInit {
this.filters().publicationYears,
this.filters().types,
this.filters().languages,
this.selectedInstitutionIds(),
this.selectedTopicIds(),
)
.subscribe({
next: (page) => {
@@ -137,13 +235,19 @@ export class PersonPublicationsComponent implements OnInit {
onPage(event: PageEvent): void {
this.paginationService.selection = event.pageSize;
this.currentPageIndex = event.pageIndex;
this.load(event.pageIndex, event.pageSize);
this.updatePublicationFilterQueryParams({
[this.queryParamKeys.page]: event.pageIndex + 1,
[this.queryParamKeys.pageSize]: event.pageSize,
});
}
resetAndLoad(): void {
applyFilters(): void {
this.currentPageIndex = 0;
this.paginator?.firstPage();
this.load(0, this.paginationService.selection);
this.updatePublicationFilterQueryParams({
[this.queryParamKeys.page]: 1,
[this.queryParamKeys.pageSize]: this.paginationService.selection,
});
}
clearFilters(): void {
@@ -152,7 +256,65 @@ export class PersonPublicationsComponent implements OnInit {
types: [],
languages: [],
});
this.resetAndLoad();
this.selectedInstitutions = [];
this.selectedTopics = [];
this.institutionOptions = [];
this.topicOptions = [];
this.institutionSearchControl.setValue('', { emitEvent: false });
this.topicSearchControl.setValue('', { emitEvent: false });
this.updatePublicationFilterQueryParams({
[this.queryParamKeys.page]: 1,
[this.queryParamKeys.pageSize]: this.paginationService.selection,
[this.queryParamKeys.years]: null,
[this.queryParamKeys.types]: null,
[this.queryParamKeys.languages]: null,
[this.queryParamKeys.institutionIds]: null,
[this.queryParamKeys.institutionNames]: null,
[this.queryParamKeys.topicIds]: null,
[this.queryParamKeys.topicNames]: null,
});
}
displayInstitution(option: string | InstitutionAutocompleteOption): string {
return typeof option === 'string' ? option : (option.display_name ?? '');
}
selectInstitution(event: MatAutocompleteSelectedEvent): void {
const institution = event.option.value as InstitutionAutocompleteOption;
if (!institution.id) return;
if (!this.selectedInstitutions.some((item) => item.id === institution.id)) {
this.selectedInstitutions = [...this.selectedInstitutions, institution];
this.applyFilters();
}
this.institutionSearchControl.setValue('', { emitEvent: false });
this.institutionOptions = [];
}
removeInstitution(institution: InstitutionAutocompleteOption): void {
this.selectedInstitutions = this.selectedInstitutions.filter(
(item) => item.id !== institution.id,
);
this.applyFilters();
}
displayTopic(option: string | TopicAutocompleteOption): string {
return typeof option === 'string' ? option : (option.display_name ?? '');
}
selectTopic(event: MatAutocompleteSelectedEvent): void {
const topic = event.option.value as TopicAutocompleteOption;
if (!topic.id) return;
if (!this.selectedTopics.some((item) => item.id === topic.id)) {
this.selectedTopics = [...this.selectedTopics, topic];
this.applyFilters();
}
this.topicSearchControl.setValue('', { emitEvent: false });
this.topicOptions = [];
}
removeTopic(topic: TopicAutocompleteOption): void {
this.selectedTopics = this.selectedTopics.filter((item) => item.id !== topic.id);
this.applyFilters();
}
doiUrl(doi: string | null | undefined): string | null {
@@ -160,6 +322,11 @@ export class PersonPublicationsComponent implements OnInit {
return doi.startsWith('http') ? doi : `https://doi.org/${doi}`;
}
publicationKey(publication: Work): string {
const id = publication.id ?? publication.ids?.openalex ?? publication.doi ?? '';
return id.split('/').filter(Boolean).pop() ?? id;
}
publicationRange(): string {
if (this.total === 0 || this.publications.length === 0) {
return 'Keine Publikationen';
@@ -175,6 +342,24 @@ export class PersonPublicationsComponent implements OnInit {
return 'info';
}
institutions(publication: Work): Array<{ id: string; name: string }> {
const institutionsById = new Map<string, { id: string; name: string }>();
for (const authorship of publication.authorships ?? []) {
for (const institution of authorship.institutions ?? []) {
if (!institution.id || !institution.display_name) continue;
if (!institutionsById.has(institution.id)) {
institutionsById.set(institution.id, {
id: institution.id,
name: institution.display_name,
});
}
}
}
return Array.from(institutionsById.values());
}
private filters() {
return {
publicationYears: this.filterForm.controls.publicationYears.value,
@@ -183,6 +368,210 @@ export class PersonPublicationsComponent implements OnInit {
};
}
private setupInstitutionAutocomplete(): void {
this.institutionSearchControl.valueChanges
.pipe(
debounceTime(250),
map((value) => (typeof value === 'string' ? value.trim() : '')),
distinctUntilChanged(),
switchMap((query) => {
if (query.length < 2) {
this.institutionOptions = [];
return of([]);
}
this.institutionLookupLoading = true;
return this.searchInstitutions(query).pipe(
catchError(() => of([])),
finalize(() => {
this.institutionLookupLoading = false;
}),
);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((options) => {
const selectedIds = new Set(this.selectedInstitutionIds());
this.institutionOptions = options.filter(
(option) => !!option.id && !selectedIds.has(option.id),
);
});
}
private setupTopicAutocomplete(): void {
this.topicSearchControl.valueChanges
.pipe(
debounceTime(250),
map((value) => (typeof value === 'string' ? value.trim() : '')),
distinctUntilChanged(),
switchMap((query) => {
if (query.length < 2) {
this.topicOptions = [];
return of([]);
}
this.topicLookupLoading = true;
return this.searchTopics(query).pipe(
catchError(() => of([])),
finalize(() => {
this.topicLookupLoading = false;
}),
);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((options) => {
const selectedIds = new Set(this.selectedTopicIds());
this.topicOptions = options.filter(
(option) => !!option.id && !selectedIds.has(option.id),
);
});
}
private searchInstitutions(query: string) {
const params = new HttpParams()
.set('query', query)
.set('limit', '10');
const basePath = this.workService.configuration.basePath ?? '';
return this.httpClient
.get<InstitutionAutocompleteResponse>(`${basePath}/api/institutions/autocomplete`, {
params,
})
.pipe(map((response) => response.results ?? []));
}
private searchTopics(query: string) {
const params = new HttpParams().set('query', query).set('limit', '10');
const basePath = this.workService.configuration.basePath ?? '';
return this.httpClient
.get<TopicAutocompleteResponse>(`${basePath}/api/topics/autocomplete`, {
params,
})
.pipe(map((response) => response.results ?? []));
}
private selectedInstitutionIds(): string[] {
return this.selectedInstitutions
.map((institution) => institution.id)
.filter((id): id is string => !!id);
}
private selectedTopicIds(): string[] {
return this.selectedTopics
.map((topic) => topic.id)
.filter((id): id is string => !!id);
}
private updatePublicationFilterQueryParams(
overrides: Record<string, string | number | Array<string | number> | null>,
): void {
const filters = this.filters();
const institutionIds = this.selectedInstitutionIds();
const institutionNames = this.selectedInstitutions
.map((institution) => institution.display_name)
.filter((name): name is string => !!name);
const topicIds = this.selectedTopicIds();
const topicNames = this.selectedTopics
.map((topic) => topic.display_name)
.filter((name): name is string => !!name);
void this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[this.queryParamKeys.years]: filters.publicationYears.length
? filters.publicationYears
: null,
[this.queryParamKeys.types]: filters.types.length ? filters.types : null,
[this.queryParamKeys.languages]: filters.languages.length
? filters.languages
: null,
[this.queryParamKeys.institutionIds]: institutionIds.length
? institutionIds
: null,
[this.queryParamKeys.institutionNames]: institutionNames.length
? institutionNames
: null,
[this.queryParamKeys.topicIds]: topicIds.length ? topicIds : null,
[this.queryParamKeys.topicNames]: topicNames.length ? topicNames : null,
...overrides,
},
queryParamsHandling: 'merge',
});
}
private parsePublicationFilterQueryParams(
queryParams: ParamMap,
): PublicationFilterQueryState {
const institutionIds = queryParams.getAll(this.queryParamKeys.institutionIds);
const institutionNames = queryParams.getAll(this.queryParamKeys.institutionNames);
const topicIds = queryParams.getAll(this.queryParamKeys.topicIds);
const topicNames = queryParams.getAll(this.queryParamKeys.topicNames);
return {
pageIndex:
this.parsePositiveInteger(queryParams.get(this.queryParamKeys.page), 1) - 1,
pageSize: this.parsePositiveInteger(
queryParams.get(this.queryParamKeys.pageSize),
this.paginationService.selection,
),
publicationYears: this.parseNumberParams(
queryParams.getAll(this.queryParamKeys.years),
),
types: this.parseStringParams(queryParams.getAll(this.queryParamKeys.types)),
languages: this.parseStringParams(
queryParams.getAll(this.queryParamKeys.languages),
),
institutions: institutionIds
.filter(Boolean)
.map((id, index) => ({
id,
display_name: institutionNames[index] || id,
})),
topics: topicIds
.filter(Boolean)
.map((id, index) => ({
id,
display_name: topicNames[index] || id,
})),
};
}
private applyPublicationFilterQueryState(
queryState: PublicationFilterQueryState,
): void {
this.currentPageIndex = queryState.pageIndex;
this.paginationService.selection = queryState.pageSize;
this.selectedInstitutions = queryState.institutions;
this.selectedTopics = queryState.topics;
this.filterForm.setValue(
{
publicationYears: queryState.publicationYears,
types: queryState.types,
languages: queryState.languages,
},
{ emitEvent: false },
);
}
private parseStringParams(values: string[]): string[] {
return values.map((value) => value.trim()).filter(Boolean);
}
private parseNumberParams(values: string[]): number[] {
return values
.map((value) => Number(value))
.filter((value) => Number.isInteger(value));
}
private parsePositiveInteger(value: string | null, fallback: number): number {
const parsedValue = Number(value);
if (!Number.isInteger(parsedValue) || parsedValue < 1) {
return fallback;
}
return parsedValue;
}
private createPublicationYearOptions(): number[] {
const currentYear = new Date().getFullYear();
return Array.from({ length: 90 }, (_, index) => currentYear - index);
@@ -32,14 +32,6 @@
<mat-icon>mail</mat-icon>
<span>uni-email@uni-due.de</span>
</div>
<!-->
@if (openAlexId()) {
<div>
<mat-icon>person</mat-icon>
<span>{{ openAlexId() }}</span>
</div>
}
<!-->
@if (orcid()) {
<div>
<mat-icon class="orcid">verified</mat-icon>
@@ -64,7 +56,7 @@
}
</div>
</aside>
<app-person-interesting [topics]="topicsFull()"></app-person-interesting>
<app-person-interesting [topics]="primaryTopicCounts()"></app-person-interesting>
</section>
<nav class="person-tabs" mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link.path) {
@@ -8,7 +8,7 @@ import { ActivatedRoute, RouterModule, RouterOutlet } from '@angular/router';
import { of, switchMap, finalize, map, catchError } from 'rxjs';
import { PersonInterestingComponent } from '../person-interesting/person-interesting.component';
import { PersonsService } from '../../api';
import { PersonsService, WorksService } from '../../api';
const PERSON_INCLUDE_TAGS =
'topics_full,topic_share,summary_stats,ids,last_known_institutions,' +
@@ -30,6 +30,7 @@ const PERSON_INCLUDE_TAGS =
export class PersonComponent {
private route = inject(ActivatedRoute);
private readonly personsApi = inject(PersonsService);
private readonly worksApi = inject(WorksService);
private readonly destroyRef = inject(DestroyRef);
@@ -50,7 +51,7 @@ export class PersonComponent {
switchMap((id) => {
if (!id) return of(null);
this.isPersonLoading.set(true);
return this.personsApi.searchPersons(id, PERSON_INCLUDE_TAGS).pipe(
return this.personsApi.searchPersons(id, undefined, PERSON_INCLUDE_TAGS).pipe(
map((result) => result.results?.[0] ?? null),
catchError((err) => {
console.error('Failed to load person:', err);
@@ -93,11 +94,20 @@ readonly personBio = toSignal(
readonly primaryAffiliation = computed(
() => this.person()?.affiliations?.[0] ?? null,
);
readonly lastAffiliation = computed(
()=> {
let lastAffiliation: number | undefined = 0
if (this.person()?.affiliations?.length != undefined){
lastAffiliation = this.person()?.affiliations?.length
}
return (lastAffiliation ? this.person()?.affiliations?.[lastAffiliation - 1] : this.person()?.affiliations?.[0]) ?? null
}
)
readonly institution = computed(
() => this.primaryAffiliation()?.institution?.display_name ?? 'Unbekannte Institution',
() => this.lastAffiliation()?.institution?.display_name ?? 'Unbekannte Institution',
);
readonly countryCode = computed(
() => this.primaryAffiliation()?.institution?.country_code ?? null,
() => this.lastAffiliation()?.institution?.country_code ?? null,
);
readonly worksCount = computed(() => this.person()?.works_count ?? null);
readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null);
@@ -112,10 +122,20 @@ readonly personBio = toSignal(
this.orcid() ? `https://orcid.org/${this.orcid()}` : null,
);
readonly worksApiUrl = computed(() => this.person()?.works_api_url ?? null);
readonly openAlexId = computed(() => this.person()?.id ?? null);
readonly topicsFull = computed(
() => this.person()?.topics ?? [],
readonly primaryTopicCounts = toSignal(
toObservable(this.authorId).pipe(
switchMap((id) => {
if (!id) return of([]);
return this.worksApi.getPrimaryTopicCountsByAuthor(id).pipe(
catchError((err) => {
console.error('Failed to load primary topic counts:', err);
return of([]);
})
);
})
),
{ initialValue: [] }
);
links = [
{ label: 'Übersicht', path: 'overview', disabled: false },
@@ -123,6 +143,7 @@ readonly personBio = toSignal(
{ label: 'Publikationen', path: 'publications', disabled: false },
{ label: 'Netzwerk', path: 'network', disabled: false },
{ label: 'Gründungen', path: 'foundings', disabled: true },
{ label: 'Förderungen', path: 'funding', disabled: false },
];
private getId(key: string): string | null {
@@ -0,0 +1,256 @@
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Publikationen"
>
<mat-icon>arrow_back</mat-icon>
Alle Publikationen
</button>
@if (loading) {
<div class="state">
<mat-spinner diameter="42"></mat-spinner>
<p>Publikation wird geladen...</p>
</div>
} @else if (notFound || !publication) {
<div class="state error-state">
<mat-icon>search_off</mat-icon>
<h2>Publikation nicht gefunden</h2>
<p>Die Publikation konnte nicht geladen werden.</p>
<a mat-stroked-button routerLink="/persons">
Zur Personensuche
</a>
</div>
} @else {
<header class="hero">
<div class="hero-copy">
<div class="eyebrow">
@if (publication.type) {
<span>{{ publication.type }}</span>
}
@if (publication.publication_year) {
<span>{{ publication.publication_year }}</span>
}
@if (publication.language) {
<span>{{ publication.language | uppercase }}</span>
}
</div>
<h1>{{ publication.title || publication.display_name || "Ohne Titel" }}</h1>
<p class="author-line">
@for (authorship of authors(); track authorship.author?.id; let last = $last) {
<span>{{ authorship.author?.display_name || authorship.raw_author_name || "Unbekannt" }}</span>@if (!last) {<span>, </span>}
} @empty {
Autorinnen und Autoren nicht angegeben
}
</p>
<div class="hero-actions">
@for (link of externalLinks().slice(0, 3); track link.url; let first = $first) {
<a
[class.primary-action]="first"
[attr.mat-flat-button]="first ? '' : null"
[attr.mat-stroked-button]="first ? null : ''"
[href]="link.url"
target="_blank"
rel="noopener"
>
{{ link.label }}
<mat-icon>open_in_new</mat-icon>
</a>
}
</div>
</div>
<div class="metrics" aria-label="Publikationskennzahlen">
<div>
<mat-icon>format_quote</mat-icon>
<strong>{{ publication.cited_by_count ?? 0 | number }}</strong>
<span>Zitationen</span>
</div>
<div>
<mat-icon>menu_book</mat-icon>
<strong>{{ publication.referenced_works_count ?? 0 | number }}</strong>
<span>Referenzen</span>
</div>
<div [class.positive]="publication.open_access?.is_oa">
<mat-icon>{{ publication.open_access?.is_oa ? "lock_open" : "lock" }}</mat-icon>
<strong>{{ publication.open_access?.is_oa ? "Ja" : "Nein" }}</strong>
<span>Open Access</span>
</div>
</div>
</header>
@if (publication.is_retracted) {
<div class="warning">
<mat-icon>warning</mat-icon>
Diese Publikation wurde zurückgezogen.
</div>
}
<div class="content-grid">
<main>
@if (abstractText(); as abstract) {
<section class="card abstract-card">
<div class="section-title">
<mat-icon>subject</mat-icon>
<h2>Abstract</h2>
</div>
<p>{{ abstract }}</p>
</section>
}
<section class="card">
<div class="section-title">
<mat-icon>group</mat-icon>
<h2>Autorinnen und Autoren</h2>
<span>{{ authors().length }}</span>
</div>
<div class="author-list">
@for (authorship of authors(); track authorship.author?.id) {
<article>
<div class="avatar">{{ (authorship.author?.display_name || authorship.raw_author_name || "?").charAt(0) }}</div>
<div>
@if (authorship.author?.id; as authorId) {
<a [routerLink]="['/person', authorId.split('/').pop(), 'overview']">
{{ authorship.author?.display_name || authorship.raw_author_name || "Unbekannt" }}
</a>
} @else {
<strong>{{ authorship.raw_author_name || "Unbekannt" }}</strong>
}
<p>
{{ authorship.author_position || "Mitautor/in" }}
@if (authorship.is_corresponding) { · Korrespondenz }
</p>
</div>
</article>
} @empty {
<p class="empty">Keine Angaben vorhanden.</p>
}
</div>
</section>
@if (publication.topics?.length || publication.keywords?.length) {
<section class="card">
<div class="section-title">
<mat-icon>interests</mat-icon>
<h2>Themen und Keywords</h2>
</div>
<div class="tags">
@for (topic of publication.topics ?? []; track topic.id) {
<span class="topic-tag" [title]="topic.field?.display_name || ''">
{{ topic.display_name }}
</span>
}
@for (keyword of publication.keywords ?? []; track keyword.id) {
<span>{{ keyword.display_name }}</span>
}
</div>
</section>
}
@if (sources().length) {
<section class="card">
<div class="section-title">
<mat-icon>library_books</mat-icon>
<h2>Quellen und Versionen</h2>
</div>
<div class="source-list">
@for (location of sources(); track location.source?.id || location.landing_page_url) {
<article>
<div>
<strong>{{ location.source?.display_name || "Externe Quelle" }}</strong>
<p>
{{ location.version || location.source?.type || "Veröffentlichte Version" }}
@if (location.license) { · {{ location.license }} }
</p>
</div>
<div class="source-actions">
@if (location.is_oa) {
<span class="oa-badge">Open Access</span>
}
@if (location.pdf_url || location.landing_page_url; as sourceUrl) {
<a [href]="sourceUrl" target="_blank" rel="noopener" aria-label="Quelle öffnen">
<mat-icon>open_in_new</mat-icon>
</a>
}
</div>
</article>
}
</div>
</section>
}
</main>
<aside>
<section class="card facts-card">
<div class="section-title">
<mat-icon>info</mat-icon>
<h2>Publikationsdaten</h2>
</div>
<dl>
<div><dt>Datum</dt><dd>{{ (publication.publication_date | date: "dd.MM.yyyy") || "-" }}</dd></div>
<div><dt>Typ</dt><dd>{{ publication.type || "-" }}</dd></div>
<div><dt>Sprache</dt><dd>{{ publication.language || "-" }}</dd></div>
<div><dt>Open Access</dt><dd>{{ openAccessLabel() }}</dd></div>
<div><dt>Volume</dt><dd>{{ publication.biblio?.volume || "-" }}</dd></div>
<div><dt>Ausgabe</dt><dd>{{ publication.biblio?.issue || "-" }}</dd></div>
<div><dt>Seiten</dt><dd>{{ pages() || "-" }}</dd></div>
<div><dt>Indexiert in</dt><dd>{{ publication.indexed_in?.join(", ") || "-" }}</dd></div>
</dl>
</section>
@if (institutions().length) {
<section class="card">
<div class="section-title">
<mat-icon>account_balance</mat-icon>
<h2>Institutionen</h2>
</div>
<div class="compact-list">
@for (institution of institutions(); track institution.id) {
<div>
<strong>{{ institution.name }}</strong>
<span>{{ institution.country || institution.type || "" }}</span>
</div>
}
</div>
</section>
}
@if (publication.funders?.length || publication.awards?.length) {
<section class="card">
<div class="section-title">
<mat-icon>paid</mat-icon>
<h2>Förderungen</h2>
</div>
<div class="compact-list">
@for (funder of publication.funders ?? []; track funder.id) {
<div><strong>{{ funder.display_name }}</strong><span>Förderorganisation</span></div>
}
@for (award of publication.awards ?? []; track award.id) {
<div><strong>{{ award.display_name || award.funder_award_id }}</strong><span>{{ award.funder_display_name || "Förderung" }}</span></div>
}
</div>
</section>
}
@if (externalLinks().length) {
<section class="card">
<div class="section-title">
<mat-icon>link</mat-icon>
<h2>Externe Links</h2>
</div>
<div class="link-list">
@for (link of externalLinks(); track link.url) {
<a [href]="link.url" target="_blank" rel="noopener">
<span>{{ link.label }}</span>
<mat-icon>north_east</mat-icon>
</a>
}
</div>
</section>
}
</aside>
</div>
}
</div>
@@ -0,0 +1,436 @@
:host {
display: block;
background: var(--sg-background);
}
.detail-page {
max-width: 1500px;
margin: 0 auto;
padding: 26px 32px 56px;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
gap: 42px;
padding: 38px 42px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-lg);
background:
radial-gradient(circle at 90% 10%, rgba(200, 217, 255, 0.75), transparent 35%),
linear-gradient(140deg, #fff 0%, #f8faff 100%);
box-shadow: var(--sg-shadow-sm);
}
.eyebrow,
.tags,
.hero-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.eyebrow span {
padding: 5px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.85);
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
}
h1 {
max-width: 920px;
margin: 20px 0 13px;
font-size: clamp(27px, 3vw, 42px);
line-height: 1.13;
}
.author-line {
max-width: 900px;
margin: 0;
color: var(--sg-text-muted);
font-size: 14px;
line-height: 1.7;
}
.hero-actions {
margin-top: 26px;
}
.hero-actions a {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 42px;
padding: 9px 16px;
border: 1px solid var(--sg-border-strong);
border-radius: var(--sg-radius-sm);
background: #fff;
color: var(--sg-text);
font-weight: 700;
text-decoration: none;
}
.hero-actions a.primary-action {
border-color: var(--sg-primary);
background: var(--sg-primary);
color: #fff;
}
.hero-actions mat-icon {
width: 17px;
height: 17px;
font-size: 17px;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
align-self: center;
overflow: hidden;
border: 1px solid rgba(199, 211, 232, 0.8);
border-radius: var(--sg-radius-md);
background: rgba(255, 255, 255, 0.8);
}
.metrics div {
display: flex;
align-items: center;
flex-direction: column;
gap: 5px;
padding: 22px 10px;
text-align: center;
}
.metrics div + div {
border-left: 1px solid var(--sg-border);
}
.metrics mat-icon {
color: var(--sg-text-soft);
}
.metrics .positive mat-icon {
color: var(--sg-success);
}
.metrics strong {
color: var(--sg-text);
font-family: "Montserrat", "Open Sans", sans-serif;
font-size: 22px;
}
.metrics span {
color: var(--sg-text-muted);
font-size: 11px;
}
.warning {
display: flex;
align-items: center;
gap: 10px;
margin-top: 20px;
padding: 14px 18px;
border: 1px solid #f1c6cc;
border-radius: var(--sg-radius-sm);
background: #fff4f5;
color: #9c2637;
font-weight: 700;
}
.content-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) 380px;
gap: 24px;
margin-top: 24px;
}
main,
aside {
display: flex;
flex-direction: column;
gap: 24px;
}
.card {
padding: 26px 28px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-md);
background: var(--sg-surface);
box-shadow: var(--sg-shadow-sm);
}
.section-title {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 20px;
}
.section-title mat-icon {
color: var(--sg-text-muted);
}
.section-title h2 {
margin: 0;
font-size: 16px;
}
.section-title span {
margin-left: auto;
color: var(--sg-text-muted);
font-size: 12px;
}
.abstract-card p {
margin: 0;
color: var(--sg-text);
font-size: 14px;
line-height: 1.8;
}
.author-list {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.author-list article {
display: grid;
grid-template-columns: 38px minmax(0, 1fr);
gap: 11px;
align-items: center;
padding: 12px;
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-muted);
}
.avatar {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border-radius: 50%;
background: #e5ecfb;
color: var(--sg-text);
font-weight: 700;
text-transform: uppercase;
}
.author-list a,
.author-list strong {
color: var(--sg-text);
font-size: 13px;
font-weight: 700;
text-decoration: none;
}
.author-list p,
.source-list p {
margin: 3px 0 0;
color: var(--sg-text-muted);
font-size: 11px;
}
.tags span {
padding: 7px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
color: var(--sg-text-muted);
font-size: 11px;
}
.tags .topic-tag {
border-color: #cbd8f1;
background: #f5f8ff;
color: var(--sg-text);
}
.source-list,
.compact-list,
.link-list {
display: grid;
gap: 10px;
}
.source-list article,
.compact-list div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 13px 0;
border-bottom: 1px solid var(--sg-border);
}
.source-list article:last-child,
.compact-list div:last-child {
border-bottom: 0;
}
.source-actions {
display: flex;
align-items: center;
gap: 10px;
}
.source-actions a {
height: 24px;
}
.source-actions mat-icon {
width: 20px;
height: 20px;
font-size: 20px;
}
.oa-badge {
padding: 4px 8px;
border-radius: 999px;
background: var(--sg-success-soft);
color: var(--sg-success);
font-size: 10px;
font-weight: 700;
}
dl {
margin: 0;
}
dl div {
display: grid;
grid-template-columns: 115px minmax(0, 1fr);
gap: 12px;
padding: 10px 0;
border-bottom: 1px solid var(--sg-border);
}
dl div:last-child {
border-bottom: 0;
}
dt {
color: var(--sg-text-muted);
font-size: 12px;
}
dd {
margin: 0;
overflow-wrap: anywhere;
color: var(--sg-text);
font-size: 12px;
font-weight: 600;
text-align: right;
}
.compact-list div {
align-items: flex-start;
flex-direction: column;
gap: 3px;
}
.compact-list strong {
font-size: 12px;
}
.compact-list span {
color: var(--sg-text-muted);
font-size: 11px;
}
.link-list a {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 12px;
font-weight: 700;
text-decoration: none;
}
.link-list a:last-child {
border-bottom: 0;
}
.link-list mat-icon {
width: 16px;
height: 16px;
color: var(--sg-text-muted);
font-size: 16px;
}
.state {
display: grid;
place-items: center;
min-height: 380px;
color: var(--sg-text-muted);
text-align: center;
}
.error-state mat-icon {
width: 46px;
height: 46px;
font-size: 46px;
}
.empty {
color: var(--sg-text-muted);
}
@media (max-width: 1150px) {
.hero,
.content-grid {
grid-template-columns: 1fr;
}
.metrics {
width: 100%;
}
}
@media (max-width: 700px) {
.detail-page {
padding: 18px 16px 40px;
}
.hero,
.card {
padding: 22px 20px;
}
.metrics,
.author-list {
grid-template-columns: 1fr;
}
.metrics div + div {
border-top: 1px solid var(--sg-border);
border-left: 0;
}
}
@@ -0,0 +1,182 @@
import { DatePipe, DecimalPipe, UpperCasePipe } from '@angular/common';
import { Location } from '@angular/common';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { finalize } from 'rxjs';
import { Authorship, Location as ApiLocation, Work, WorksService } from '../../api';
interface DetailLink {
label: string;
url: string;
}
interface InstitutionDetail {
id: string;
name: string;
country?: string | null;
type?: string | null;
}
@Component({
selector: 'app-publication-detail',
imports: [
DatePipe,
DecimalPipe,
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
RouterLink,
UpperCasePipe,
],
templateUrl: './publication-detail.component.html',
styleUrl: './publication-detail.component.scss',
})
export class PublicationDetailComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly httpClient = inject(HttpClient);
private readonly location = inject(Location);
private readonly worksService = inject(WorksService);
publication: Work | null = null;
loading = true;
notFound = false;
ngOnInit(): void {
this.route.paramMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
const publicationId = params.get('publicationId');
if (!publicationId) {
this.loading = false;
this.notFound = true;
return;
}
this.loadPublication(publicationId);
});
}
navigateBack(): void {
this.location.back();
}
abstractText(): string | null {
const index = this.publication?.abstract_inverted_index;
if (!index || typeof index !== 'object') return null;
const words: Array<{ word: string; position: number }> = [];
for (const [word, rawPositions] of Object.entries(index)) {
if (!Array.isArray(rawPositions)) continue;
for (const position of rawPositions) {
if (typeof position === 'number') words.push({ word, position });
}
}
return words
.sort((first, second) => first.position - second.position)
.map(({ word }) => word)
.join(' ') || null;
}
authors(): Authorship[] {
return this.publication?.authorships ?? [];
}
institutions(): InstitutionDetail[] {
const institutions = new Map<string, InstitutionDetail>();
for (const authorship of this.authors()) {
for (const institution of authorship.institutions ?? []) {
if (!institution.id || !institution.display_name) continue;
institutions.set(institution.id, {
id: institution.id,
name: institution.display_name,
country: institution.country_code,
type: institution.type,
});
}
}
return Array.from(institutions.values());
}
sources(): ApiLocation[] {
const locations = [
this.publication?.primary_location,
this.publication?.best_oa_location,
...(this.publication?.locations ?? []),
].filter((location): location is ApiLocation => !!location);
const unique = new Map<string, ApiLocation>();
for (const location of locations) {
const key =
location.source?.id ??
location.landing_page_url ??
location.pdf_url ??
JSON.stringify(location);
unique.set(key, location);
}
return Array.from(unique.values());
}
externalLinks(): DetailLink[] {
if (!this.publication) return [];
const links: DetailLink[] = [];
this.addLink(links, 'Open Access', this.publication.open_access?.oa_url);
this.addLink(links, 'DOI', this.doiUrl(this.publication.doi));
return links.filter(
(link, index) => links.findIndex((candidate) => candidate.url === link.url) === index,
);
}
pages(): string | null {
const first = this.publication?.biblio?.first_page;
const last = this.publication?.biblio?.last_page;
if (first && last) return `${first}-${last}`;
return first ?? last ?? null;
}
openAccessLabel(): string {
if (this.publication?.open_access?.is_oa) {
return this.publication.open_access.oa_status
? `Open Access (${this.publication.open_access.oa_status})`
: 'Open Access';
}
return 'Kein Open Access';
}
private loadPublication(publicationId: string): void {
this.loading = true;
this.notFound = false;
this.publication = null;
const basePath = this.worksService.configuration.basePath ?? '';
this.httpClient
.get<Work>(
`${basePath}/api/works/detail/${encodeURIComponent(publicationId)}`,
)
.pipe(finalize(() => (this.loading = false)))
.subscribe({
next: (publication) => {
this.publication = publication;
},
error: () => {
this.notFound = true;
},
});
}
private doiUrl(doi: string | null | undefined): string | null {
if (!doi) return null;
return doi.startsWith('http') ? doi : `https://doi.org/${doi}`;
}
private addLink(links: DetailLink[], label: string, value: string | null | undefined) {
if (!value) return;
links.push({ label, url: value.startsWith('http') ? value : `https://${value}` });
}
}
@@ -0,0 +1,93 @@
<div class="hierarchy-container">
@if (loading()) {
<div class="loading-state">
<mat-spinner diameter="24"></mat-spinner>
<span>Lade Themen...</span>
</div>
} @else {
@if (searchQuery) {
<!-- Flat Search Results Mode -->
<div class="search-results">
<span class="results-meta">{{ filteredFlatTopics.length }} Treffer</span>
<div class="flat-list">
@for (topic of filteredFlatTopics; track topic.id) {
<div class="flat-row">
<mat-checkbox
[checked]="selectedTopics.has(topic.name)"
(change)="toggleTopic(topic.name)">
<span class="topic-name">{{ topic.name }}</span>
</mat-checkbox>
<span class="topic-path" [title]="topic.path">{{ topic.path }}</span>
</div>
} @empty {
<div class="empty-search">Keine passenden Themen.</div>
}
</div>
</div>
} @else {
<!-- Embedded Multi-Nested Hierarchy Tree Mode -->
<div class="tree-root">
@for (domain of domains; track domain.name) {
<!-- LEVEL 1: Domain -->
<div class="tree-node domain-node">
<button class="node-header domain-header" (click)="toggleDomain(domain.name)">
<mat-icon class="toggle-icon">
{{ expandedDomains.has(domain.name) ? 'expand_more' : 'chevron_right' }}
</mat-icon>
<span class="node-title domain-title">{{ domain.name }}</span>
</button>
@if (expandedDomains.has(domain.name)) {
<div class="node-children domain-children">
@for (field of domain.fields; track field.name) {
<!-- LEVEL 2: Field -->
<div class="tree-node field-node">
<button class="node-header field-header" (click)="toggleField(field.name)">
<mat-icon class="toggle-icon">
{{ expandedFields.has(field.name) ? 'expand_more' : 'chevron_right' }}
</mat-icon>
<mat-icon class="folder-icon">folder</mat-icon>
<span class="node-title field-title">{{ field.name }}</span>
</button>
@if (expandedFields.has(field.name)) {
<div class="node-children field-children">
@for (subfield of field.subfields; track subfield.name) {
<!-- LEVEL 3: Subfield -->
<div class="tree-node subfield-node">
<button class="node-header subfield-header" (click)="toggleSubfield(subfield.name)">
<mat-icon class="toggle-icon">
{{ expandedSubfields.has(subfield.name) ? 'expand_more' : 'chevron_right' }}
</mat-icon>
<mat-icon class="folder-icon">folder_open</mat-icon>
<span class="node-title subfield-title">{{ subfield.name }}</span>
</button>
@if (expandedSubfields.has(subfield.name)) {
<div class="node-children subfield-children">
@for (topic of subfield.topics; track topic.id) {
<!-- LEVEL 4: Topic Checkbox -->
<div class="tree-leaf topic-node">
<mat-checkbox
[checked]="selectedTopics.has(topic.name)"
(change)="toggleTopic(topic.name)">
<span class="topic-label" [title]="topic.name">{{ topic.name }}</span>
</mat-checkbox>
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
}
</div>
@@ -0,0 +1,194 @@
.hierarchy-container {
width: 100%;
max-height: 400px;
overflow-y: auto;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-background);
padding: 4px;
margin-top: 4px;
}
.loading-state {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 16px;
color: var(--sg-text-muted);
font-size: 12px;
}
/* Flat Search Results Styles */
.search-results {
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px;
}
.results-meta {
font-size: 11px;
font-weight: 600;
color: var(--sg-text-muted);
text-transform: uppercase;
padding-left: 4px;
}
.flat-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.flat-row {
display: flex;
flex-direction: column;
padding: 6px;
border-bottom: 1px solid var(--sg-border-soft);
&:last-child {
border-bottom: none;
}
.topic-name {
font-size: 12px;
color: var(--sg-text);
font-weight: 500;
}
.topic-path {
font-size: 10px;
color: var(--sg-text-soft);
padding-left: 28px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
}
.empty-search {
padding: 16px;
font-size: 12px;
color: var(--sg-text-muted);
text-align: center;
}
/* Hierarchy Tree Styles */
.tree-root {
display: flex;
flex-direction: column;
gap: 2px;
}
.tree-node {
display: flex;
flex-direction: column;
}
.node-header {
display: flex;
align-items: center;
width: 100%;
background: transparent;
border: none;
padding: 4px 6px;
text-align: left;
cursor: pointer;
border-radius: 4px;
color: var(--sg-text);
&:hover {
background: var(--sg-surface-soft);
}
.toggle-icon {
font-size: 16px;
width: 16px;
height: 16px;
color: var(--sg-text-soft);
margin-right: 2px;
}
.folder-icon {
font-size: 14px;
width: 14px;
height: 14px;
color: var(--sg-primary-soft);
margin-right: 4px;
}
.node-title {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
}
.domain-header {
padding-top: 6px;
padding-bottom: 6px;
.domain-title {
font-size: 12px;
font-weight: 600;
color: var(--sg-text);
}
}
.field-header {
.field-title {
font-size: 11.5px;
font-weight: 500;
color: var(--sg-text-muted);
}
}
.subfield-header {
.subfield-title {
font-size: 11px;
color: var(--sg-text-muted);
}
}
.node-children {
display: flex;
flex-direction: column;
gap: 2px;
}
.domain-children {
padding-left: 12px;
border-left: 1px solid var(--sg-border-soft);
margin-left: 12px;
margin-bottom: 4px;
}
.field-children {
padding-left: 14px;
border-left: 1px solid var(--sg-border-soft);
margin-left: 14px;
}
.subfield-children {
padding-left: 14px;
border-left: 1px dashed var(--sg-border-soft);
margin-left: 14px;
margin-bottom: 2px;
}
.tree-leaf {
padding: 2px 4px;
}
.topic-node {
.topic-label {
font-size: 11px;
color: var(--sg-text);
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: block;
max-width: 190px;
}
}
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TopicHierarchyComponent } from './topic-hierarchy.component';
describe('TopicHierarchyComponent', () => {
let component: TopicHierarchyComponent;
let fixture: ComponentFixture<TopicHierarchyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TopicHierarchyComponent]
})
.compileComponents();
fixture = TestBed.createComponent(TopicHierarchyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,156 @@
import { Component, Input, Output, EventEmitter, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { TopicsService } from '../../api/api/topics.service';
export interface TopicItem {
id: string;
name: string;
}
export interface SubfieldNode {
name: string;
topics: TopicItem[];
}
export interface FieldNode {
name: string;
subfields: SubfieldNode[];
}
export interface DomainNode {
name: string;
fields: FieldNode[];
}
interface FlatTopic {
id: string;
name: string;
path: string;
}
@Component({
selector: 'app-topic-hierarchy',
standalone: true,
imports: [
CommonModule,
MatCheckboxModule,
MatIconModule,
MatProgressSpinnerModule
],
templateUrl: './topic-hierarchy.component.html',
styleUrl: './topic-hierarchy.component.scss'
})
export class TopicHierarchyComponent implements OnInit {
@Input() selectedTopics: Set<string> = new Set<string>();
private _searchQuery = '';
@Input()
set searchQuery(value: string) {
if (value.length < 2) {
this._searchQuery = '';
} else {
this._searchQuery = value;
}
this.filterFlatTopics();
}
get searchQuery(): string {
return this._searchQuery;
}
@Output() selectionChange = new EventEmitter<Set<string>>();
domains: DomainNode[] = [];
flatTopics: FlatTopic[] = [];
filteredFlatTopics: FlatTopic[] = [];
loading = signal(true);
// Set of names of expanded nodes (lazy content rendering)
expandedDomains = new Set<string>();
expandedFields = new Set<string>();
expandedSubfields = new Set<string>();
constructor(private topicsService: TopicsService) { }
ngOnInit(): void {
this.topicsService.getTopicHierarchy().subscribe({
next: (res: any) => {
this.domains = res.domains || [];
this.flattenTopics(this.domains);
this.loading.set(false);
},
error: (err) => {
console.error('Error fetching topic hierarchy:', err);
this.loading.set(false);
}
});
}
flattenTopics(domains: DomainNode[]): void {
const flat: FlatTopic[] = [];
domains.forEach((domain) => {
domain.fields?.forEach((field) => {
field.subfields?.forEach((subfield) => {
subfield.topics?.forEach((topic) => {
if (topic.name && topic.id) {
flat.push({
id: topic.id,
name: topic.name,
path: `${domain.name} > ${field.name} > ${subfield.name}`
});
}
});
});
});
});
this.flatTopics = flat;
this.filterFlatTopics();
}
filterFlatTopics(): void {
if (!this.searchQuery) {
this.filteredFlatTopics = [];
return;
}
const query = this.searchQuery.toLowerCase();
this.filteredFlatTopics = this.flatTopics.filter((t) =>
t.name.toLowerCase().includes(query) || t.path.toLowerCase().includes(query)
);
}
toggleTopic(name: string): void {
const nextSelection = new Set(this.selectedTopics);
if (nextSelection.has(name)) {
nextSelection.delete(name);
} else {
nextSelection.add(name);
}
this.selectionChange.emit(nextSelection);
}
toggleDomain(name: string): void {
if (this.expandedDomains.has(name)) {
this.expandedDomains.delete(name);
} else {
this.expandedDomains.add(name);
}
}
toggleField(name: string): void {
if (this.expandedFields.has(name)) {
this.expandedFields.delete(name);
} else {
this.expandedFields.add(name);
}
}
toggleSubfield(name: string): void {
if (this.expandedSubfields.has(name)) {
this.expandedSubfields.delete(name);
} else {
this.expandedSubfields.add(name);
}
}
}
@@ -34,17 +34,7 @@
<span>Zurück zur Suche</span>
</button>
</div>
<label class="search-box">
<mat-icon>search</mat-icon>
<input
[formControl]="searchValue"
type="search"
placeholder="Suchen nach Personen, Themen, Projekten..."
(keyup.enter)="startSearch()"
/>
</label>
<app-searchbar/>
<div class="topbar-actions">
<ng-content select="[menu]"></ng-content>
</div>
@@ -1,5 +1,4 @@
@use '@angular/material' as mat;
@import '../../../../m3-theme.scss';
.app-shell {
height: 100svh;
@@ -72,34 +71,6 @@ mat-toolbar.main {
height: 20px;
}
.search-box {
display: flex;
align-items: center;
gap: 12px;
height: 44px;
align-self: center;
padding: 0 18px;
background: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
color: var(--sg-text-soft);
font-size: 13px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
}
.search-box input {
width: 100%;
min-width: 0;
border: 0;
outline: 0;
background: transparent;
color: var(--sg-text);
}
.search-box input::placeholder {
color: var(--sg-text-muted);
}
.drawer {
width: var(--sg-sidebar-width);
background: var(--sg-surface);
@@ -144,3 +115,45 @@ mat-toolbar.main {
min-height: calc(100svh - 124px);
}
}
.search-wrapper {
position: relative;
width: 100%;
}
.search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: white;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
z-index: 1000;
max-height: 300px;
overflow-y: auto;
}
.search-result-item {
padding: 10px 16px;
cursor: pointer;
display: flex;
flex-direction: column;
border-bottom: 1px solid var(--sg-border);
&:hover {
background: var(--sg-surface-muted);
}
.result-name {
font-weight: 500;
font-size: 14px;
color: var(--sg-text);
}
.result-affiliation {
font-size: 12px;
color: var(--sg-text-muted);
}
}
@@ -15,13 +15,12 @@ import { MediaMatcher } from '@angular/cdk/layout';
import { AppMenuComponent } from '../app-menu/app-menu.component';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CredentialService } from '../../services/credential.service';
import { FormControl,ReactiveFormsModule } from '@angular/forms';
import { SharedStateService } from '../../services/shared-state.service';
import { Location } from '@angular/common';
import { AppSearchbarComponent } from "../app-searchbar/app-searchbar.component";
@Component({
selector: 'app-layout',
imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, AppMenuComponent, MatTooltipModule,ReactiveFormsModule],
imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, AppMenuComponent, MatTooltipModule, AppSearchbarComponent],
templateUrl: './app-layout.component.html',
styleUrl: './app-layout.component.scss',
standalone: true,
@@ -35,10 +34,8 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
mediaQueryListener: () => void;
sideNavOpen = false;
searchValue = new FormControl('');
constructor(public credentialService: CredentialService, public router: Router,
private location:Location,
private state: SharedStateService,
public changeDetector: ChangeDetectorRef, media: MediaMatcher) {
this.mediaQuery = media.matchMedia('(max-width: 600px)');
this.mediaQueryListener = () => {
@@ -66,14 +63,6 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
this.credentialService.logoutAcount();
this.router.navigate(['/']);
}
startSearch(){
const query = this.searchValue.value || null;
this.state.searchValue.set(query);
this.router.navigate(['/persons'], {
queryParams: { query, page: 1 },
queryParamsHandling: 'merge',
});
}
navigateBack(){
this.location.back()
}
@@ -0,0 +1,23 @@
<label class="search-box">
<mat-icon>search</mat-icon>
<input matInput
type="search"
aria-label="Search"
[matAutocomplete]="auto"
[formControl]="searchControl"
(keydown.tab)="filteredPersons.results?.length ? onKeydownTab($any($event)) : null"
placeholder="Suche nach Personen, Themen, Projekten..."
(keyup.enter)="onEnter()"
(focus)="onFocus()">
<mat-autocomplete #auto="matAutocomplete"
>
@for (person of filteredPersons.results; track person.id) {
<mat-option [value]="person.display_name"
(click)="selectPerson(person.display_name)">
<span>{{ person.display_name }}</span>
</mat-option>
}
</mat-autocomplete>
</label>
@@ -0,0 +1,28 @@
.search-box {
display: flex;
align-items: center;
gap: 12px;
height: 44px;
align-self: center;
padding: 0 18px;
background: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
color: var(--sg-text-soft);
font-size: 13px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
}
.search-box input {
width: 100%;
min-width: 0;
border: 0;
outline: 0;
background: transparent;
color: var(--sg-text);
}
.search-box input::placeholder {
color: var(--sg-text-muted);
}
@@ -0,0 +1,112 @@
import { Component, inject, ViewChild, DestroyRef} from '@angular/core';
import { MatIcon } from '@angular/material/icon';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import {
MatAutocompleteModule,
MatAutocompleteTrigger,
MatAutocomplete,
} from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
import { PersonsService, AuthorsListResponse } from '../../../api';
@Component({
selector: 'app-searchbar',
standalone: true,
imports: [
MatIcon,
ReactiveFormsModule,
MatAutocompleteModule,
MatInputModule,
MatFormFieldModule,
],
templateUrl: './app-searchbar.component.html',
styleUrl: './app-searchbar.component.scss',
})
export class AppSearchbarComponent {
@ViewChild(MatAutocompleteTrigger)
autocompleteTrigger!: MatAutocompleteTrigger;
@ViewChild(MatAutocomplete) autocomplete!: MatAutocomplete;
searchControl = new FormControl('');
filteredPersons: AuthorsListResponse = {
meta: null,
results: [],
group_by: [],
};
private readonly destroyRef = inject(DestroyRef);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly personService = inject(PersonsService);
constructor() {
const params = new URLSearchParams(window.location.search);
const currentSearch = params.get('query') ?? '';
this.searchControl.setValue(currentSearch, { emitEvent: false });
// Autocomplete suggestions
this.searchControl.valueChanges
.pipe(
debounceTime(100),
distinctUntilChanged(),
switchMap((v) => {
const value = v ?? '';
if (value.length < 2) return of(this.emptyPersons());
return this.personService.searchPersonsAutocomplete(
value,
'display_name',
);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((results) => {
this.filteredPersons = results;
});
}
selectPerson(personName: string | undefined | null): void {
if (personName) {
this.searchControl.setValue(personName);
this.startSearch();
}
}
onKeydownTab(event: KeyboardEvent): void {
event.preventDefault();
const first = this.filteredPersons?.results?.[0];
if (first?.display_name) {
this.searchControl.setValue(first.display_name);
}
}
onEnter(): void {
this.autocompleteTrigger.closePanel();
this.startSearch();
}
onFocus(): void {
this.autocompleteTrigger.openPanel();
}
startSearch(): void {
const search = this.searchControl.value ?? '';
this.router.navigate(
this.router.url.startsWith('/persons') ? [] : ['/persons'],
{
relativeTo: this.route,
queryParams: { query: search || null, page: 1 },
queryParamsHandling: 'merge',
},
);
}
private emptyPersons(): AuthorsListResponse {
return { meta: null, results: [], group_by: [] };
}
}
+19
View File
@@ -0,0 +1,19 @@
export interface PersonFilters {
institution?: string;
//...
}
export function encodeFilters(filters: PersonFilters): string | null {
const clean = Object.fromEntries(
Object.entries(filters).filter(([, v]) => v != null && v !== '')
);
return Object.keys(clean).length ? JSON.stringify(clean) : null;
}
export function decodeFilters(raw: string | null): PersonFilters {
if (!raw) return {};
try {
return JSON.parse(raw) as PersonFilters;
} catch {
return {};
}
}