diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index 74078444..a04eb6fd 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -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 diff --git a/service/src/main/inse/funders/service.py b/service/src/main/inse/funders/service.py index a99b661e..b6c8c05f 100644 --- a/service/src/main/inse/funders/service.py +++ b/service/src/main/inse/funders/service.py @@ -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( diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 3d744ad9..2bb78629 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -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() diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 645df10b..353626d6 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -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} diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 96f6e5a8..4e0e62d2 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -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) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index aaac61b1..669f049f 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -36,8 +36,5 @@ class Page(BaseModel, Generic[T]): class ItemPage(Page[Item]): pass -class PersonBio(BaseModel): - bio: str = Field(description="The generated biography.") - diff --git a/service/src/main/inse/persons/__init__.py b/service/src/main/inse/persons/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py new file mode 100644 index 00000000..a4dc5c0f --- /dev/null +++ b/service/src/main/inse/persons/logic.py @@ -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 + ) + ) diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py new file mode 100644 index 00000000..49fc03bc --- /dev/null +++ b/service/src/main/inse/persons/model.py @@ -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 \ No newline at end of file diff --git a/service/src/main/inse/search/query_builder.py b/service/src/main/inse/persons/query_builder.py similarity index 68% rename from service/src/main/inse/search/query_builder.py rename to service/src/main/inse/persons/query_builder.py index e882abcd..e6b18902 100644 --- a/service/src/main/inse/search/query_builder.py +++ b/service/src/main/inse/persons/query_builder.py @@ -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: diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py new file mode 100644 index 00000000..c442b578 --- /dev/null +++ b/service/src/main/inse/persons/service.py @@ -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, + ) diff --git a/service/src/main/inse/search/__init__.py b/service/src/main/inse/search/__init__.py deleted file mode 100644 index 40a96afc..00000000 --- a/service/src/main/inse/search/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/service/src/main/inse/search/logic.py b/service/src/main/inse/search/logic.py deleted file mode 100644 index 536efb1b..00000000 --- a/service/src/main/inse/search/logic.py +++ /dev/null @@ -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 - ) - ) diff --git a/service/src/main/inse/search/model.py b/service/src/main/inse/search/model.py deleted file mode 100644 index 6d04a644..00000000 --- a/service/src/main/inse/search/model.py +++ /dev/null @@ -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 diff --git a/service/src/main/inse/search/service.py b/service/src/main/inse/search/service.py deleted file mode 100644 index 8d6227ce..00000000 --- a/service/src/main/inse/search/service.py +++ /dev/null @@ -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, - ) diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 108dcd3a..6e3dadc5 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -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() diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index da4fc410..645e2235 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -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) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 68623388..13d8ad8b 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -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 diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 7a97fdae..27d4e254 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -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]; diff --git a/webapp/src/app/api/api/inse-service.service.ts b/webapp/src/app/api/api/inse-service.service.ts index b2058459..dbca3805 100644 --- a/webapp/src/app/api/api/inse-service.service.ts +++ b/webapp/src/app/api/api/inse-service.service.ts @@ -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. diff --git a/webapp/src/app/api/api/inse-service.serviceInterface.ts b/webapp/src/app/api/api/inse-service.serviceInterface.ts index e7f18df1..979f6465 100644 --- a/webapp/src/app/api/api/inse-service.serviceInterface.ts +++ b/webapp/src/app/api/api/inse-service.serviceInterface.ts @@ -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; /** +<<<<<<< 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; /** +>>>>>>> 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; /** +<<<<<<< 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; /** +>>>>>>> 33f767dea36fe8a44c8249dbb74537d47c186c5d * Updates the item with the id. * * @endpoint put /api/inse-service/items/{id} diff --git a/webapp/src/app/api/api/persons-search.serviceInterface.ts b/webapp/src/app/api/api/persons-search.serviceInterface.ts index 8221785d..23155580 100644 --- a/webapp/src/app/api/api/persons-search.serviceInterface.ts +++ b/webapp/src/app/api/api/persons-search.serviceInterface.ts @@ -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'; diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index a2d22321..c80c7c64 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -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; + public getPersonByID_1(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID_1(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID_1(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + 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, + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: 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; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + 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, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: 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; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + 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, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: 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; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + 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 { 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 institutionName, 'institution_name'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: 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; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + 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 { + 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, + institutionName, 'institution_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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; - public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + 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 { 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 authorName, 'author_name'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: 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; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + 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 { + 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, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, 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; + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, 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>; + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, 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>; + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, 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 { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -403,6 +755,93 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa include, 'include'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, strict, 'strict'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterMode, 'filterMode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Searches for persons with advanced filters (Topic & 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, 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; + public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, 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>; + public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, 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>; + public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, 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 { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institutionName'); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + strict, 'strict'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterMode, 'filterMode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterYear, 'filterYear'); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/api/persons.serviceInterface.ts b/webapp/src/app/api/api/persons.serviceInterface.ts index 7ee1d04a..22232b9b 100644 --- a/webapp/src/app/api/api/persons.serviceInterface.ts +++ b/webapp/src/app/api/api/persons.serviceInterface.ts @@ -43,6 +43,15 @@ export interface PersonsServiceInterface { */ getPersonByID(id: string, include: string, extraHttpRequestParams?: any): Observable; + /** + * 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; + /** * Searches for persons by ID or name. * @@ -53,14 +62,45 @@ export interface PersonsServiceInterface { */ searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable; + /** + * 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; + + /** + * 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; + /** * 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; + searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable; + + /** + * 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; /** * 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; + searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable; + + /** + * 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; + + searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable; /** * Searches for persons with advanced filters (Topic & 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, page?: number, pageSize?: number, include?: string, strict?: boolean, extraHttpRequestParams?: any): Observable; + searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable; } diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 193a1b1f..8635bf04 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -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; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/api/topics.serviceInterface.ts b/webapp/src/app/api/api/topics.serviceInterface.ts index 6a60f441..baebd5f6 100644 --- a/webapp/src/app/api/api/topics.serviceInterface.ts +++ b/webapp/src/app/api/api/topics.serviceInterface.ts @@ -39,4 +39,11 @@ export interface TopicsServiceInterface { */ countTopicHierarchy(topic: Array, extraHttpRequestParams?: any): Observable; + /** + * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * + * @endpoint get /api/inse-service/topics/hierarchy + */ + getTopicHierarchy(extraHttpRequestParams?: any): Observable; + } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 7121b4a2..cd80c9ac 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -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 diff --git a/webapp/src/app/api/api/works.serviceInterface.ts b/webapp/src/app/api/api/works.serviceInterface.ts index ed81c297..792f42f7 100644 --- a/webapp/src/app/api/api/works.serviceInterface.ts +++ b/webapp/src/app/api/api/works.serviceInterface.ts @@ -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, type?: Array, language?: Array, extraHttpRequestParams?: any): Observable; - /** - * 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>; - /** * Returns topics grouped by publication year for an author. * diff --git a/webapp/src/app/api/model/person-filters.ts b/webapp/src/app/api/model/person-filters.ts new file mode 100644 index 00000000..625bc459 --- /dev/null +++ b/webapp/src/app/api/model/person-filters.ts @@ -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; +} + diff --git a/webapp/src/app/api/model/person-search-request.ts b/webapp/src/app/api/model/person-search-request.ts new file mode 100644 index 00000000..9ed6e5bc --- /dev/null +++ b/webapp/src/app/api/model/person-search-request.ts @@ -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; +} + diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts index c33c2d57..4e0a074d 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -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], diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 9867fd05..2b9d5f40 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -92,11 +92,13 @@

{{ person.display_name }}

-

{{ institution(person) }}

+

{{ institution(person)?.display_name }} +

{{ getDistinguishingId(person) }}

- Works: {{ person.works_count }} · - Citations: {{ person.cited_by_count }} + Publikationen: {{ person.works_count }} · + Zitationen: {{ person.cited_by_count }}

@@ -182,21 +184,9 @@ } -
- @for (topic of filteredTopicsList; track topic) { - - } - - @if (topicsList.length > 5 && !topicSearchControl.value) { - - } -
+ + @@ -212,11 +202,35 @@ } -
- +
+ + Zusammenarbeit nach Jahr + filtern + + + @if (yearFilterEnabledControl.value) { +
+ + Genau + in + Seit + + + + Jahr + + @if (filterYearControl.hasError('min')) { + Jahr muss ≥ 1900 sein + } + @if (filterYearControl.hasError('max')) { + Zukünftige Jahre sind nicht erlaubt + } + +
+ }
diff --git a/webapp/src/app/modules/person-list/person-list.component.scss b/webapp/src/app/modules/person-list/person-list.component.scss index 097911a1..2c0c5e8f 100644 --- a/webapp/src/app/modules/person-list/person-list.component.scss +++ b/webapp/src/app/modules/person-list/person-list.component.scss @@ -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); } diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index d119bb9f..6be52be4 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -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(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(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): 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 ''; } diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index 883d017d..e3c31b4a 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -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, diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 82b8726f..fbb05a83 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -32,14 +32,6 @@ mail uni-email@uni-due.de - - @if (openAlexId()) { -
- person - {{ openAlexId() }} -
- } - @if (orcid()) {
verified diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 8dda3951..5aef3001 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -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( diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html new file mode 100644 index 00000000..f40782a2 --- /dev/null +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html @@ -0,0 +1,93 @@ +
+ @if (loading()) { +
+ + Lade Themen... +
+ } @else { + @if (searchQuery) { + +
+ {{ filteredFlatTopics.length }} Treffer +
+ @for (topic of filteredFlatTopics; track topic.id) { +
+ + {{ topic.name }} + + {{ topic.path }} +
+ } @empty { + + } +
+
+ } @else { + +
+ @for (domain of domains; track domain.name) { + +
+ + + @if (expandedDomains.has(domain.name)) { +
+ @for (field of domain.fields; track field.name) { + +
+ + + @if (expandedFields.has(field.name)) { +
+ @for (subfield of field.subfields; track subfield.name) { + +
+ + + @if (expandedSubfields.has(subfield.name)) { +
+ @for (topic of subfield.topics; track topic.id) { + +
+ + {{ topic.name }} + +
+ } +
+ } +
+ } +
+ } +
+ } +
+ } +
+ } +
+ } + } +
diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss new file mode 100644 index 00000000..cca028e3 --- /dev/null +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss @@ -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; + } +} diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.spec.ts b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.spec.ts new file mode 100644 index 00000000..0fd487ff --- /dev/null +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.spec.ts @@ -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; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [TopicHierarchyComponent] + }) + .compileComponents(); + + fixture = TestBed.createComponent(TopicHierarchyComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts new file mode 100644 index 00000000..331ec004 --- /dev/null +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts @@ -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 = new Set(); + + 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>(); + + domains: DomainNode[] = []; + flatTopics: FlatTopic[] = []; + filteredFlatTopics: FlatTopic[] = []; + loading = signal(true); + + // Set of names of expanded nodes (lazy content rendering) + expandedDomains = new Set(); + expandedFields = new Set(); + expandedSubfields = new Set(); + + 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); + } + } +} diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index b2fe1274..ef8b9baa 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -34,17 +34,7 @@ Zurück zur Suche
- - - +
diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index e7864dd0..92054c33 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -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); diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index d92dd9f2..45987649 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -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() } diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html new file mode 100644 index 00000000..145c976a --- /dev/null +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html @@ -0,0 +1,23 @@ + \ No newline at end of file diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss new file mode 100644 index 00000000..3f1cae7d --- /dev/null +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss @@ -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); +} diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts new file mode 100644 index 00000000..711c0211 --- /dev/null +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts @@ -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: [] }; + } +} diff --git a/webapp/src/app/shared/utils/filters.ts b/webapp/src/app/shared/utils/filters.ts new file mode 100644 index 00000000..e89dc6d9 --- /dev/null +++ b/webapp/src/app/shared/utils/filters.ts @@ -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 {}; + } +} \ No newline at end of file