Merge pull request 'merging_persons' (#113) from merging_persons into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good

Reviewed-on: #113
This commit was merged in pull request #113.
This commit is contained in:
2026-06-06 13:18:08 +02:00
48 changed files with 2251 additions and 746 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ from pydantic import ValidationError
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from .. import logic as person_logic
from ..persons import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from .elastic_search_client import MissingApiKeyError
+1 -1
View File
@@ -12,7 +12,7 @@ from . import logic
from . import model
router = APIRouter(prefix="/authors", tags=["Funding"])
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"])
@router.get(
@@ -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}
+4 -2
View File
@@ -12,7 +12,8 @@ from fastapi.responses import RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from inse.collaboration_network.router import router as collaboration_network_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
@@ -33,7 +34,8 @@ app = FastAPI(
)
app.include_router(collaboration_network_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.")
+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
@@ -11,6 +11,9 @@ def build_authors_search(
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.
@@ -53,11 +56,20 @@ def build_authors_search(
# 2. Build Filters
filter_clauses = []
if institution_name:
if strict:
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",
@@ -71,9 +83,7 @@ def build_authors_search(
},
{
"range": {
"affiliations.years": {
"gte": target_year
}
"affiliations.years": range_query
}
}
]
@@ -83,15 +93,42 @@ def build_authors_search(
})
else:
filter_clauses.append({
"nested": {
"path": "affiliations",
"query": {
"match_phrase": {
"affiliations.institution.display_name": institution_name
"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:
@@ -142,6 +179,7 @@ def build_authors_search(
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:
+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 -*-
-134
View File
@@ -1,134 +0,0 @@
# -*- coding: utf-8 -*-
import logging
import hashlib
from typing import List, Optional
import httpx
from fastapi import HTTPException
from inse.search.query_builder import build_authors_search
from inse import util
from inse.integrations import elasticsearch as es_integration
from inse.models.author import Author
from inse.models.meta import Meta
from inse.search.model import CustomAuthor, CustomAuthorsListResponse
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
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) 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 = 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,
strict: Optional[bool] = False,
) -> 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,
)
response_dict = es_integration.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)}"
)
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
)
)
-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
-66
View File
@@ -1,66 +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,
strict: Annotated[
Optional[bool], Query(description="Strict institution search by target year")
] = False,
):
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,
)
+7 -142
View File
@@ -27,12 +27,8 @@ from . import schema
from . import database
from . import security
from . import util
from .works import service as works_service
from .funders import service as funders_service
from inse.models.authors_list_response import AuthorsListResponse
logger = logging.getLogger(__name__)
@@ -46,8 +42,6 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
)
router.include_router(funders_service.router)
# @app.get("/", include_in_schema=False)
# async def show_api():
# return RedirectResponse("api")
@@ -215,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()
+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)
@@ -13,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
+1 -4
View File
@@ -16,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 = [FundingService, INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, PersonsSearchService, TopicsService, WorksService];
export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService];
@@ -303,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)
@@ -421,6 +423,7 @@ export class INSEServiceService extends BaseService implements INSEServiceServic
}
/**
>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d
* Returns the item with the id.
* @endpoint get /api/inse-service/items/{id}
* @param id The item id.
@@ -542,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
@@ -865,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,14 +11,14 @@ import { HttpHeaders } from '@angular/comm
import { Observable } from 'rxjs';
import { AuthorsListResponse } from '../model/models';
import { FundersByAuthorResponse } 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 { PublicationsByAuthorResponse } from '../model/models';
import { PersonBio } from '../model/models'; //
import { PublicationsByAuthorResponse } from '../model/models'; //
import { Configuration } from '../configuration';
@@ -63,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
@@ -80,6 +82,7 @@ export interface INSEServiceServiceInterface {
getFundersByAuthor(authorId: string, extraHttpRequestParams?: any): Observable<FundersByAuthorResponse>;
/**
>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d
* Returns the item with the id.
*
* @endpoint get /api/inse-service/items/{id}
@@ -97,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}
@@ -144,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}
@@ -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';
+454 -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;
@@ -379,10 +731,10 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
* @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, 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> {
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,
@@ -403,6 +755,93 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
<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.
@@ -83,6 +138,6 @@ export interface PersonsServiceInterface {
* @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, strict?: boolean, 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>;
}
+1 -1
View File
@@ -19,7 +19,7 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/http-validation-error';
// @ts-ignore
import { TopicCount } from '../model/topic-count';
import { TopicCount } from '../model/topic-count'; //
// @ts-ignore
import { TopicsByTime } from '../model/topics-by-time';
// @ts-ignore
@@ -12,7 +12,7 @@ import { HttpHeaders } from '@angular/comm
import { Observable } from 'rxjs';
import { HTTPValidationError } from '../model/models';
import { TopicCount } from '../model/models';
import { TopicCount } from '../model/models'; //
import { TopicsByTime } from '../model/models';
import { WorkPage } from '../model/models';
import { WorksListResponse } from '../model/models';
@@ -47,14 +47,6 @@ export interface WorksServiceInterface {
*/
getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, extraHttpRequestParams?: any): Observable<WorkPage>;
/**
* 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.
*/
getPrimaryTopicCountsByAuthor(authorId: string, extraHttpRequestParams?: any): Observable<Array<TopicCount>>;
/**
* Returns topics grouped by publication year for an author.
*
@@ -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;
}
@@ -2,8 +2,8 @@ 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],
@@ -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,11 +202,35 @@
</button>
}
</div>
<div class="strict-search-wrapper" style="margin-top: 8px;">
<label class="checkbox-label">
<input type="checkbox" [formControl]="strictControl" (change)="applySidebarFilters()" />
<span class="checkbox-text">Letzten 2 Jahre</span>
</label>
<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>
@@ -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,7 +81,12 @@ export class PersonListComponent {
sortControl = new FormControl('relevance', { nonNullable: true });
topicSearchControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl('', { nonNullable: true });
strictControl = new FormControl(false, { 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
@@ -84,7 +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 strict = params['strict'] === 'true';
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']);
@@ -99,11 +118,17 @@ export class PersonListComponent {
if (this.institutionControl.value !== institutionName) {
this.institutionControl.setValue(institutionName);
}
if (this.strictControl.value !== strict) {
this.strictControl.setValue(strict);
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, strict);
this.load(query, page, pageSize, topics, institutionName, yearFilterEnabled, filterMode, filterYear);
});
}
@@ -113,18 +138,22 @@ export class PersonListComponent {
pageSize: number = 10,
topics?: string[],
institutionName?: string,
strict: boolean = false
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,
strict || undefined
yearFilterEnabled ? true : undefined,
yearFilterEnabled ? filterMode : undefined,
yearFilterEnabled ? filterYear : undefined
)
.pipe(
finalize(() => this.loadingState.set(false)),
@@ -202,7 +231,11 @@ export class PersonListComponent {
list.push({ category: 'topic', value: t, label: t });
});
if (this.institutionControl.value) {
const label = `Institution: ${this.institutionControl.value}${this.strictControl.value ? ' (Strict)' : ''}`;
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,
@@ -217,7 +250,9 @@ export class PersonListComponent {
this.selectedTopics.delete(filter.value);
} else if (filter.category === 'institutionName') {
this.institutionControl.setValue('');
this.strictControl.setValue(false);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
}
this.applySidebarFilters();
}
@@ -225,16 +260,24 @@ export class PersonListComponent {
clearAllFilters(): void {
this.selectedTopics.clear();
this.institutionControl.setValue('');
this.strictControl.setValue(false);
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,
strict: this.strictControl.value ? 'true' : 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',
@@ -296,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
);
}
@@ -338,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);
}
@@ -355,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 '';
}
@@ -4,7 +4,8 @@ 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,
@@ -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>
@@ -94,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);
@@ -113,7 +122,6 @@ 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 primaryTopicCounts = toSignal(
toObservable(this.authorId).pipe(
@@ -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);
@@ -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 {};
}
}