diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index e3ad986f..3d744ad9 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -5,8 +5,13 @@ from .. import config def search( index: str, - query_field: str, - query_value: str + query_field: str = None, + query_value: str = None, + query: dict = None, + source = None, + size: int = None, + sort: list = None, + body: dict = None, ) -> dict[str, Any]: headers = { @@ -14,14 +19,25 @@ def search( "Content-Type": "application/json" } - payload = { - "query": { - "query_string": { - "default_field": query_field, - "query": query_value + if body is not None: + payload = body + elif query is not None: + payload = {"query": query} + if source is not None: + payload["_source"] = source + if size is not None: + payload["size"] = size + if sort is not None: + payload["sort"] = sort + else: + payload = { + "query": { + "query_string": { + "default_field": query_field, + "query": query_value + } } } - } with httpx.Client() as client: response = client.post( @@ -31,3 +47,27 @@ def search( ) response.raise_for_status() return response.json() +def get( + index: str, + doc_id:str, + body: dict = None, + +) -> dict[str, Any]: + + headers = { + "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", + "Content-Type": "application/json" + } + payload = body + + # get document directly + with httpx.Client() as client: + response = client.get( + f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}", + json=payload, + headers=headers + ) + response.raise_for_status() + return response.json() + + diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 88c95c16..688c81d9 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -55,9 +55,8 @@ es_client = _init_es_client() topic_cache_filename: str = "topic_hierarchy_cache.json" -S = TypeVar("S", bound=schema.Base) -M = TypeVar("M", bound=model.BaseModel) - +S = TypeVar('S', bound=schema.Base) +M = TypeVar('M', bound=model.BaseModel) def filter_none(): return True @@ -346,17 +345,17 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s return bio +def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: + body = { + "_source":include.split(",") if include else True, + } -def get_person_by_id( - author_id: str, include: Optional[str] = None -) -> AuthorsListResponse: try: - hit = es_client.get( + hit = elasticsearch.get( index="openalex-authors", - id=author_id, - source=include.split(",") if include else True, + body=body, + doc_id=author_id ) - except NotFoundError: raise HTTPException( status_code=404, detail=f"Person with id {author_id} not found" @@ -384,13 +383,20 @@ def search_persons_by_name( "display_name": {"query": author_name, "boost": 3} } }, - {"match": {"display_name": {"query": author_name, "fuzziness": 1}}}, + # { + # "match": { + # "display_name": { + # "query": author_name, + # "fuzziness": 1 + # } + # } + # } ], "minimum_should_match": 1, } } try: - response = es_client.search( + response = elasticsearch.search( index="openalex-authors", query=search_query, source=include.split(",") if include else True, @@ -426,12 +432,11 @@ def search_persons_by_institution( }, } } - print(include, institution_name) try: - response = es_client.search( + response = elasticsearch.search( index="openalex-authors", - source=include.split(",") if include else True, query=search_query, + source=include.split(",") if include else True, size=limit, sort=[{"works_count": {"order": "desc"}}], ) diff --git a/service/src/main/inse/models/topic_count.py b/service/src/main/inse/models/topic_count.py new file mode 100644 index 00000000..3e0d1f1e --- /dev/null +++ b/service/src/main/inse/models/topic_count.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel, Field + + +class TopicCount(BaseModel): + name: str = Field(description="The topic display name.") + count: int = Field(default=0, description="The number of occurrences.") diff --git a/service/src/main/inse/models/topics_by_time.py b/service/src/main/inse/models/topics_by_time.py new file mode 100644 index 00000000..4b495e5a --- /dev/null +++ b/service/src/main/inse/models/topics_by_time.py @@ -0,0 +1,10 @@ +from typing import List + +from pydantic import BaseModel, Field + +from inse.models.topics_by_year import TopicsByYear + + +class TopicsByTime(BaseModel): + elements: List[TopicsByYear] = Field(default_factory=list, description="Topics grouped by year.") + total: int = Field(default=0, description="The number of years.") diff --git a/service/src/main/inse/models/topics_by_year.py b/service/src/main/inse/models/topics_by_year.py new file mode 100644 index 00000000..91efe7c6 --- /dev/null +++ b/service/src/main/inse/models/topics_by_year.py @@ -0,0 +1,12 @@ +from typing import List + +from pydantic import BaseModel, Field + +from inse.models.topic_count import TopicCount + + +class TopicsByYear(BaseModel): + year: int = Field(description="The publication year.") + publication_count: int = Field(default=0, description="The number of works in this year.") + topics: List[TopicCount] = Field(default_factory=list, description="The topics in this year.") + primary_topics: List[TopicCount] = Field(default_factory=list, description="The primary topics in this year.") diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 379e99e1..98648398 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -17,6 +17,9 @@ from inse.models.work import Work from inse.models.work_page import WorkPage from inse.models.works_list_response import WorksListResponse from inse.models.meta import Meta +from inse.models.topic_count import TopicCount +from inse.models.topics_by_year import TopicsByYear +from inse.models.topics_by_time import TopicsByTime from .search_client import MissingApiKeyError from .search_client import OpenAlexWorksSearchClient @@ -87,6 +90,87 @@ async def get_all_author_works( ) +async def get_topics_by_time_by_author( + author_id: str, + max_topics_per_year: int = 3, + client: OpenAlexWorksSearchClient | None = None, +) -> TopicsByTime: + works = await get_all_author_works(author_id, client=client) + + years = {} + + for work in works.results or []: + if work.publication_year is None: + continue + + year = work.publication_year + + if year not in years: + years[year] = { + "publication_count": 0, + "topics": {}, + "primary_topics": {}, + } + + years[year]["publication_count"] += 1 + + for topic in work.topics or []: + if topic.display_name: + topic_name = topic.display_name + + if topic_name not in years[year]["topics"]: + years[year]["topics"][topic_name] = 0 + + years[year]["topics"][topic_name] += 1 + + primary_topic = work.primary_topic + + if primary_topic and primary_topic.display_name: + primary_topic_name = primary_topic.display_name + + if primary_topic_name not in years[year]["primary_topics"]: + years[year]["primary_topics"][primary_topic_name] = 0 + + years[year]["primary_topics"][primary_topic_name] += 1 + + elements = [] + + for year in sorted(years.keys()): + topic_items = list(years[year]["topics"].items()) + topic_items.sort(key=lambda item: item[1], reverse=True) + + topics = [] + + for topic_name, count in topic_items[:max_topics_per_year]: + topics.append(TopicCount( + name=topic_name, + count=count, + )) + + primary_topic_items = list(years[year]["primary_topics"].items()) + primary_topic_items.sort(key=lambda item: item[1], reverse=True) + + primary_topics = [] + + for topic_name, count in primary_topic_items[:max_topics_per_year]: + primary_topics.append(TopicCount( + name=topic_name, + count=count, + )) + + elements.append(TopicsByYear( + year=year, + publication_count=years[year]["publication_count"], + topics=topics, + primary_topics=primary_topics, + )) + + return TopicsByTime( + elements=elements, + total=len(elements), + ) + + async def _search_author_works_data( search_client: OpenAlexWorksSearchClient, author_id: str, diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 3e27e61d..476f2b9a 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -17,6 +17,7 @@ from .. import security from . import logic from inse.models.work_page import WorkPage from inse.models.works_list_response import WorksListResponse +from inse.models.topics_by_time import TopicsByTime router = APIRouter(prefix="/api/works", tags=[Tags.WORKS]) @@ -68,3 +69,18 @@ async def get_all_author_works( principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), ): return await logic.get_all_author_works(author_id) + + +@router.get("/{author_id}/topics-by-time", + operation_id="getTopicsByTimeByAuthor", + response_model=TopicsByTime, + summary="Returns topics grouped by publication year for an author.") +async def get_topics_by_time_by_author( + author_id: Annotated[str, Path(description="The author id, for example A5023888391.")], + max_topics_per_year: Annotated[int, Query(description="The maximum number of topics per year.", ge=1, le=20)] = 3, + principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), +): + return await logic.get_topics_by_time_by_author( + author_id, + max_topics_per_year=max_topics_per_year, + ) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 1ad70f62..87266ecf 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -66,6 +66,11 @@ model/person-bio.ts model/score.ts model/validation-error-loc-inner.ts model/validation-error.ts +model/topicCount.ts +model/topicsByTime.ts +model/topicsByYear.ts +model/validationError.ts +model/validationErrorLocInner.ts model/value.ts model/work-biblio.ts model/work-citation-normalized-percentile.ts diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 228548cb..2a156323 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -9,23 +9,26 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/http-validation-error'; // @ts-ignore -import { WorkPage } from '../model/work-page'; +import { TopicsByTime } from '../model/topicsByTime'; +// @ts-ignore +import { WorkPage } from '../model/workPage'; // @ts-ignore import { WorksListResponse } from '../model/works-list-response'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; import { WorksServiceInterface @@ -34,11 +37,11 @@ import { @Injectable({ - providedIn: 'root' + providedIn: 'root' }) export class WorksService extends BaseService implements WorksServiceInterface { - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string | string[], @Optional() configuration?: Configuration) { super(basePath, configuration); } @@ -49,10 +52,10 @@ export class WorksService extends BaseService implements WorksServiceInterface { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable; + public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling getAllAuthorWorks.'); } @@ -85,7 +88,7 @@ export class WorksService extends BaseService implements WorksServiceInterface { } } - let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/all`; + let localVarPath = `/api/works/${this.configuration.encodeParam({ name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined })}/all`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { @@ -112,35 +115,35 @@ export class WorksService extends BaseService implements WorksServiceInterface { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); } - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); + page, 'page'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - size, 'size'); + size, 'size'); if (publicationYear) { publicationYear.forEach((element) => { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'publication_year'); + element, 'publication_year'); }) } if (type) { type.forEach((element) => { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'type'); + element, 'type'); }) } if (language) { language.forEach((element) => { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'language'); + element, 'language'); }) } @@ -172,7 +175,7 @@ export class WorksService extends BaseService implements WorksServiceInterface { } } - let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + let localVarPath = `/api/works/${this.configuration.encodeParam({ name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined })}`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { @@ -188,4 +191,68 @@ export class WorksService extends BaseService implements WorksServiceInterface { ); } + /** + * Returns topics grouped by publication year for an author. + * @endpoint get /api/works/{author_id}/topics-by-time + * @param authorId The author id, for example A5023888391. + * @param maxTopicsPerYear The maximum number of topics per year. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.'); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + maxTopicsPerYear, 'max_topics_per_year'); + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/works/${this.configuration.encodeParam({ name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined })}/topics-by-time`; + 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/model/models.ts b/webapp/src/app/api/model/models.ts index a69cc6ae..7010515c 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -39,6 +39,9 @@ export * from './person-bio'; export * from './score'; export * from './validation-error'; export * from './validation-error-loc-inner'; +export * from './topicCount'; +export * from './topicsByTime'; +export * from './topicsByYear'; export * from './value'; export * from './work'; export * from './work-biblio'; diff --git a/webapp/src/app/api/model/topicCount.ts b/webapp/src/app/api/model/topicCount.ts new file mode 100644 index 00000000..d6c3c481 --- /dev/null +++ b/webapp/src/app/api/model/topicCount.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface TopicCount { + /** + * The topic display name. + */ + name: string; + /** + * The number of occurrences. + */ + count?: number; +} + diff --git a/webapp/src/app/api/model/topicsByTime.ts b/webapp/src/app/api/model/topicsByTime.ts new file mode 100644 index 00000000..0dac04a7 --- /dev/null +++ b/webapp/src/app/api/model/topicsByTime.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { TopicsByYear } from './topicsByYear'; + + +export interface TopicsByTime { + /** + * Topics grouped by year. + */ + elements?: Array; + /** + * The number of years. + */ + total?: number; +} + diff --git a/webapp/src/app/api/model/topicsByYear.ts b/webapp/src/app/api/model/topicsByYear.ts new file mode 100644 index 00000000..fded8da0 --- /dev/null +++ b/webapp/src/app/api/model/topicsByYear.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { TopicCount } from './topicCount'; + + +export interface TopicsByYear { + /** + * The publication year. + */ + year: number; + /** + * The number of works in this year. + */ + publication_count?: number; + /** + * The topics in this year. + */ + topics?: Array; + /** + * The primary topics in this year. + */ + primary_topics?: Array; +} + diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html new file mode 100644 index 00000000..cfd25c2e --- /dev/null +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -0,0 +1,249 @@ +
+
+
+

Forschungstimeline

+

+ Entwicklung der Forschungsthemen im Zeitverlauf + (basierend auf Publikationen) +

+
+ +
+ + + +
+ +
+
+ Zeitraum + + +
+ +
+ {{ selectedStartYear }} + bis + {{ selectedEndYear }} +
+ +
+
+ + + + +
+ +
+ {{ minYear }} + {{ maxYear }} +
+
+
+ +
+ Forschungstimeline wird geladen ... +
+ +
+ Forschungstimeline konnte nicht geladen werden. +
+ + + + +
+
+ + +
+
+ {{ item.year }} + +
+
+ +
+
+

{{ getMainTopic(item) }}

+ + + {{ item.publication_count }} + {{ item.publication_count === 1 ? 'Publikation' : 'Publikationen' }} + + +
+ + + {{ topic.name }} + {{ topic.count }} + + + + + + Keine weiteren Topics + + +
+
+
+
+
+
+ + +
+
+
+ + +
+ {{ getPhaseYearLabel(phase) }} +

{{ phase.primaryTopicName }}

+ + {{ phase.publication_count }} + {{ phase.publication_count === 1 ? 'Publikation' : 'Publikationen' }} + +
+
+ +
+ + + {{ topic.name }} + {{ topic.count }} + + + + + + Keine weiteren Topics + + +
+ + + +
+
+
+ {{ year.year }} + + {{ year.publication_count }} + {{ year.publication_count === 1 ? 'Publikation' : 'Publikationen' }} + +
+ +
+ + + {{ topic.name }} + {{ topic.count }} + + + + + + Keine weiteren Topics + + +
+
+
+
+
+
+ +
+ + + Hauptforschungsschwerpunkte im jeweiligen Zeitraum + +
+
+
+ + +
+ Keine Timeline-Daten vorhanden. +
+
+
\ No newline at end of file diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss new file mode 100644 index 00000000..f5daf94e --- /dev/null +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -0,0 +1,670 @@ +.research-timeline-card { + width: 100%; + padding: 24px 28px; + border: 1px solid #d7e4ff; + border-radius: 16px; + background: #ffffff; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + box-sizing: border-box; +} + +.timeline-header { + display: grid; + grid-template-columns: minmax(260px, 1fr) auto minmax(260px, 1fr); + align-items: flex-start; + gap: 24px; + margin-bottom: 28px; +} + +.timeline-title { + min-width: 0; + + h2 { + margin: 0 0 6px; + color: #07163d; + font-size: 20px; + font-weight: 700; + line-height: 1.25; + } + + p { + margin: 0; + color: #64718f; + font-size: 14px; + line-height: 1.4; + + span { + color: #74809b; + } + } +} + +.year-filter { + justify-self: end; + width: min(285px, 100%); + padding: 8px 10px; + border: 1px solid #dbe5f6; + border-radius: 10px; + background: #fbfdff; +} + +.year-filter-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 4px; +} + +.year-filter-label { + color: #07163d; + font-size: 12px; + font-weight: 700; +} + +.reset-range-button { + border: none; + background: transparent; + color: #0057ff; + font-size: 11px; + cursor: pointer; + padding: 0; + + &:disabled { + color: #9aa5bc; + cursor: default; + } +} + +.year-filter-values { + display: flex; + align-items: center; + justify-content: center; + gap: 7px; + margin-bottom: 5px; + color: #40506f; + font-size: 12px; + font-weight: 600; +} + +.year-range-slider { + --range-start: 0%; + --range-end: 100%; + + position: relative; + height: 22px; + margin: 0; +} + +.range-track { + position: absolute; + top: 50%; + left: 0; + right: 0; + height: 5px; + transform: translateY(-50%); + border-radius: 999px; + background: + linear-gradient( + to right, + #d8e2f4 0%, + #d8e2f4 var(--range-start), + #0057ff var(--range-start), + #0057ff var(--range-end), + #d8e2f4 var(--range-end), + #d8e2f4 100% + ); +} + +.range-input { + position: absolute; + top: 0; + left: 0; + width: 100%; + margin: 0; + height: 22px; + appearance: none; + background: transparent; + pointer-events: none; +} + +.range-input::-webkit-slider-runnable-track { + height: 5px; + background: transparent; + border: none; +} + +.range-input::-moz-range-track { + height: 5px; + background: transparent; + border: none; +} + +.range-input::-webkit-slider-thumb { + appearance: none; + width: 15px; + height: 15px; + margin-top: -5px; + border: 2px solid #ffffff; + border-radius: 50%; + background: #0057ff; + box-shadow: 0 0 0 1px #9ab7ff, 0 2px 6px rgba(0, 87, 255, 0.22); + cursor: pointer; + pointer-events: auto; +} + +.range-input::-moz-range-thumb { + width: 15px; + height: 15px; + border: 2px solid #ffffff; + border-radius: 50%; + background: #0057ff; + box-shadow: 0 0 0 1px #9ab7ff, 0 2px 6px rgba(0, 87, 255, 0.22); + cursor: pointer; + pointer-events: auto; +} + +.range-input:focus-visible::-webkit-slider-thumb { + outline: 2px solid #07163d; + outline-offset: 2px; +} + +.range-input:focus-visible::-moz-range-thumb { + outline: 2px solid #07163d; + outline-offset: 2px; +} + +.range-input-start { + z-index: 2; +} + +.range-input-end { + z-index: 3; +} + +.year-filter-bounds { + display: flex; + justify-content: space-between; + margin-top: 1px; + color: #7c88a3; + font-size: 10px; +} + +.view-toggle { + justify-self: center; + display: flex; + gap: 4px; + padding: 4px; + border: 1px solid #dbe5f6; + border-radius: 10px; + background: #ffffff; + + button { + border: none; + border-radius: 8px; + padding: 9px 18px; + background: transparent; + color: #3f4b66; + font-size: 14px; + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: #f2f6ff; + } + + &.active { + background: #eef4ff; + color: #0057ff; + box-shadow: inset 0 0 0 1px #3d7cff; + } + } +} + +.timeline-wrapper { + width: 100%; + overflow-x: auto; + overflow-y: hidden; + padding: 4px 0 8px; +} + +.timeline-inner { + position: relative; + padding: 0 34px 8px; +} + +.timeline-axis { + position: absolute; + top: 34px; + left: 34px; + right: 34px; + height: 2px; + background: #23395d; +} + +.timeline-axis::after { + content: ""; + position: absolute; + top: -5px; + right: -10px; + width: 0; + height: 0; + border-top: 6px solid transparent; + border-bottom: 6px solid transparent; + border-left: 12px solid #23395d; +} + +.timeline-points { + position: relative; + z-index: 1; + display: grid; + align-items: start; + min-height: 58px; +} + +.timeline-point { + display: flex; + flex-direction: column; + align-items: center; + min-width: 0; + + .year { + margin-bottom: 9px; + color: #15213f; + font-size: 14px; + font-weight: 700; + line-height: 18px; + white-space: nowrap; + } + + .dot { + width: 13px; + height: 13px; + border: 3px solid #ffffff; + border-radius: 50%; + box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.16); + } +} + +.timeline-content { + display: grid; + gap: 0; + margin-top: 8px; +} + +.timeline-item { + min-width: 0; + padding: 0 16px; + text-align: center; + + h3 { + min-height: 42px; + margin: 0 0 8px; + color: #07163d; + font-size: 15px; + font-weight: 700; + line-height: 1.35; + overflow-wrap: anywhere; + } +} + +.publication-count { + display: block; + margin-bottom: 14px; + color: #68748f; + font-size: 12px; +} + +.topic-list { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; +} + +.topic-chip { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + width: fit-content; + max-width: 210px; + min-height: 34px; + padding: 6px 10px; + border-radius: 8px; + font-size: 12px; + font-weight: 500; + line-height: 1.25; +} + +.topic-name { + min-width: 0; + overflow-wrap: anywhere; +} + +.topic-count { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + justify-content: center; + min-width: 18px; + height: 18px; + padding: 0 5px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.78); + color: inherit; + font-size: 11px; + font-weight: 700; +} + +.no-topics { + color: #9aa5bc; + font-size: 12px; +} + +.compact-phase-list { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: 14px; +} + +.phase-card { + flex: 0 1 calc((100% - 28px) / 3); + max-width: 520px; + min-width: 300px; + box-sizing: border-box; + padding: 15px 16px; + border: 1px solid #dbe5f6; + border-left-width: 4px; + border-radius: 14px; + background: #fbfdff; +} + +.phase-card-header { + display: flex; + align-items: flex-start; + gap: 10px; +} + +.phase-marker { + flex: 0 0 auto; + width: 11px; + height: 11px; + margin-top: 5px; + border: 3px solid #ffffff; + border-radius: 50%; + box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.14); +} + +.phase-title-block { + min-width: 0; + + h3 { + margin: 3px 0 4px; + color: #07163d; + font-size: 15px; + font-weight: 700; + line-height: 1.35; + } +} + +.phase-years { + display: inline-flex; + width: fit-content; + padding: 2px 8px; + border-radius: 999px; + background: #eef4ff; + color: #0057ff; + font-size: 12px; + font-weight: 700; +} + +.phase-publications { + color: #68748f; + font-size: 12px; +} + +.phase-topics { + display: flex; + flex-wrap: wrap; + gap: 7px; + margin-top: 14px; +} + +.phase-toggle { + margin-top: 13px; + border: none; + background: transparent; + color: #0057ff; + font-size: 12px; + font-weight: 700; + cursor: pointer; + padding: 0; +} + +.phase-year-details { + display: flex; + flex-direction: column; + margin-top: 13px; + padding-top: 4px; + border-top: 1px solid #dbe5f6; +} + +.phase-year-row { + display: grid; + grid-template-columns: 72px 1fr; + gap: 10px; + align-items: start; + padding: 10px 0; +} + +.phase-year-row + .phase-year-row { + border-top: 1px solid #e4ebf7; +} + +.phase-year-meta { + display: flex; + flex-direction: column; + gap: 2px; + + strong { + color: #07163d; + font-size: 13px; + } + + span { + color: #68748f; + font-size: 11px; + } +} + +.phase-year-topics { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.mini-topic-chip { + display: inline-flex; + align-items: center; + gap: 5px; + max-width: 100%; + padding: 4px 7px; + border-radius: 7px; + background: #f2f6ff; + color: #40506f; + font-size: 11px; + line-height: 1.25; + + span { + overflow-wrap: anywhere; + } + + strong { + color: #0057ff; + font-size: 10px; + } +} + +.purple { + .dot, + .phase-marker { + background: #7255d9; + } +} + +.blue { + .dot, + .phase-marker { + background: #2678e8; + } +} + +.green { + .dot, + .phase-marker { + background: #39a96b; + } +} + +.orange { + .dot, + .phase-marker { + background: #f59e0b; + } +} + +.pink { + .dot, + .phase-marker { + background: #e0527c; + } +} + +.phase-card.purple { + border-left-color: #7255d9; +} + +.phase-card.blue { + border-left-color: #2678e8; +} + +.phase-card.green { + border-left-color: #39a96b; +} + +.phase-card.orange { + border-left-color: #f59e0b; +} + +.phase-card.pink { + border-left-color: #e0527c; +} + +.topic-chip.purple { + border: 1px solid #d8cafe; + background: #f6f0ff; + color: #7255d9; +} + +.topic-chip.blue { + border: 1px solid #bdd4ff; + background: #f0f6ff; + color: #0b63ce; +} + +.topic-chip.green { + border: 1px solid #bdebcf; + background: #effaf3; + color: #24834f; +} + +.topic-chip.orange { + border: 1px solid #ffd796; + background: #fff7e8; + color: #c67500; +} + +.topic-chip.pink { + border: 1px solid #ffc7d7; + background: #fff1f5; + color: #d12f61; +} + +.timeline-note { + display: flex; + justify-content: center; + align-items: center; + gap: 10px; + margin-top: 18px; + color: #68748f; + font-size: 13px; + text-align: center; +} + +.note-dot { + width: 10px; + height: 10px; + border: 3px solid #dce5f5; + border-radius: 50%; + background: #52627f; +} + +.timeline-state { + display: flex; + min-height: 140px; + align-items: center; + justify-content: center; + padding: 20px; + color: #68748f; + font-size: 14px; + text-align: center; +} + +.timeline-state-error { + color: #b42318; +} + +@media (max-width: 1100px) { + .timeline-header { + grid-template-columns: 1fr; + } + + .view-toggle { + justify-self: start; + } + + .year-filter { + justify-self: stretch; + width: 100%; + } + + .phase-card { + flex-basis: calc((100% - 14px) / 2); + max-width: none; + } +} + +@media (max-width: 700px) { + .research-timeline-card { + padding: 20px; + } + + .view-toggle { + width: 100%; + + button { + flex: 1; + } + } + + .phase-card { + flex-basis: 100%; + min-width: 0; + } + + .phase-year-row { + grid-template-columns: 1fr; + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts new file mode 100644 index 00000000..1f478634 --- /dev/null +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -0,0 +1,373 @@ +import { CommonModule } from '@angular/common'; +import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; + +export interface TopicTimelineTopic { + name: string; + count: number; +} + +export interface TopicTimelineElement { + year: number; + publication_count: number; + topics: TopicTimelineTopic[]; + primary_topics?: TopicTimelineTopic[]; +} + +type TimelineViewMode = 'years' | 'compact'; + +interface ResearchTimelinePhase { + id: string; + startYear: number; + endYear: number; + publication_count: number; + primaryTopicName: string; + years: TopicTimelineElement[]; + topics: TopicTimelineTopic[]; +} + +interface WorkingResearchTimelinePhase { + startYear: number; + endYear: number; + publication_count: number; + primaryTopicName: string; + years: TopicTimelineElement[]; +} + +@Component({ + selector: 'app-research-timeline', + standalone: true, + imports: [CommonModule], + templateUrl: './research-timeline.component.html', + styleUrl: './research-timeline.component.scss', +}) +export class ResearchTimelineComponent implements OnChanges { + @Input() elements: TopicTimelineElement[] = []; + @Input() loading = false; + @Input() loadFailed = false; + + timelineViewMode: TimelineViewMode = 'years'; + + minYear = 0; + maxYear = 0; + selectedStartYear = 0; + selectedEndYear = 0; + + private readonly colors = ['purple', 'blue', 'green', 'orange', 'pink']; + private readonly columnWidth = 240; + private readonly displayedTopicLimit = 3; + private readonly displayedPhaseTopicLimit = 4; + private readonly expandedPhaseIds = new Set(); + + ngOnChanges(changes: SimpleChanges): void { + if (changes['elements']) { + this.initializeYearRange(); + } + } + + get timelineItems(): TopicTimelineElement[] { + return this.sortedElements.filter((item) => { + return item.year >= this.selectedStartYear && item.year <= this.selectedEndYear; + }); + } + + get compactPhases(): ResearchTimelinePhase[] { + return this.buildCompactPhases(this.timelineItems); + } + + get hasYearRange(): boolean { + return this.minYear > 0 && this.maxYear > 0 && this.minYear < this.maxYear; + } + + get canResetYearRange(): boolean { + return this.selectedStartYear !== this.minYear || this.selectedEndYear !== this.maxYear; + } + + get rangeStartPercent(): string { + return `${this.calculateRangePercent(this.selectedStartYear)}%`; + } + + get rangeEndPercent(): string { + return `${this.calculateRangePercent(this.selectedEndYear)}%`; + } + + get gridTemplateColumns(): string { + const count = Math.max(this.timelineItems.length, 1); + return `repeat(${count}, minmax(${this.columnWidth}px, 1fr))`; + } + + get timelineMinWidth(): number { + const count = Math.max(this.timelineItems.length, 1); + return Math.max(count * this.columnWidth, 1000); + } + + setTimelineViewMode(mode: TimelineViewMode): void { + this.timelineViewMode = mode; + } + + onStartYearInput(event: Event): void { + const nextStartYear = this.parseYearInput(event); + + this.selectedStartYear = this.clampYear(nextStartYear); + + if (this.selectedStartYear > this.selectedEndYear) { + this.selectedEndYear = this.selectedStartYear; + } + } + + onEndYearInput(event: Event): void { + const nextEndYear = this.parseYearInput(event); + + this.selectedEndYear = this.clampYear(nextEndYear); + + if (this.selectedEndYear < this.selectedStartYear) { + this.selectedStartYear = this.selectedEndYear; + } + } + + resetYearRange(): void { + this.selectedStartYear = this.minYear; + this.selectedEndYear = this.maxYear; + } + + getPrimaryTopic(item: TopicTimelineElement): TopicTimelineTopic | undefined { + return (item.primary_topics ?? [])[0]; + } + + getMainTopic(item: TopicTimelineElement): string { + return this.getPrimaryTopic(item)?.name ?? this.getFirstTopic(item)?.name ?? 'Keine Topics'; + } + + getDisplayedTopics(item: TopicTimelineElement): TopicTimelineTopic[] { + const primaryTopicName = this.getPrimaryTopic(item)?.name; + + return this.getDisplayedTopicsForPrimaryTopic(item, primaryTopicName); + } + + getDisplayedTopicsForPrimaryTopic( + item: TopicTimelineElement, + primaryTopicName: string | undefined, + ): TopicTimelineTopic[] { + return (item.topics ?? []) + .filter((topic) => !this.isSameTopic(topic.name, primaryTopicName)) + .slice(0, this.displayedTopicLimit); + } + + getPhaseYearLabel(phase: ResearchTimelinePhase): string { + if (phase.startYear === phase.endYear) { + return `${phase.startYear}`; + } + + return `${phase.startYear}–${phase.endYear}`; + } + + togglePhase(phase: ResearchTimelinePhase): void { + if (this.expandedPhaseIds.has(phase.id)) { + this.expandedPhaseIds.delete(phase.id); + return; + } + + this.expandedPhaseIds.add(phase.id); + } + + isPhaseExpanded(phase: ResearchTimelinePhase): boolean { + return this.expandedPhaseIds.has(phase.id); + } + + getColorClass(index: number): string { + return this.colors[index % this.colors.length]; + } + + trackByYear(_: number, item: TopicTimelineElement): number { + return item.year; + } + + trackByTopic(_: number, topic: TopicTimelineTopic): string { + return topic.name; + } + + trackByPhase(_: number, phase: ResearchTimelinePhase): string { + return phase.id; + } + + private get sortedElements(): TopicTimelineElement[] { + return [...(this.elements ?? [])].sort((left, right) => left.year - right.year); + } + + private initializeYearRange(): void { + const years = this.sortedElements + .map((item) => item.year) + .filter((year) => Number.isFinite(year)); + + if (years.length === 0) { + this.minYear = 0; + this.maxYear = 0; + this.selectedStartYear = 0; + this.selectedEndYear = 0; + return; + } + + this.minYear = Math.min(...years); + this.maxYear = Math.max(...years); + this.resetYearRange(); + } + + private buildCompactPhases(items: TopicTimelineElement[]): ResearchTimelinePhase[] { + const phases: ResearchTimelinePhase[] = []; + let currentPhase: WorkingResearchTimelinePhase | undefined; + + for (const item of items) { + const candidates = this.getDominantPrimaryTopicCandidates(item); + + if (candidates.length === 0) { + this.pushWorkingPhase(phases, currentPhase); + currentPhase = this.createWorkingPhase(item, this.getMainTopic(item)); + continue; + } + + const matchingCandidate = currentPhase + ? candidates.find((candidate) => this.isSameTopic(candidate.name, currentPhase?.primaryTopicName)) + : undefined; + + const canExtendCurrentPhase = + Boolean(currentPhase) && + Boolean(matchingCandidate) && + item.year === currentPhase!.endYear + 1; + + if (currentPhase && canExtendCurrentPhase) { + currentPhase.endYear = item.year; + currentPhase.publication_count += item.publication_count; + currentPhase.years.push(item); + continue; + } + + this.pushWorkingPhase(phases, currentPhase); + currentPhase = this.createWorkingPhase(item, candidates[0].name); + } + + this.pushWorkingPhase(phases, currentPhase); + + return phases; + } + + private createWorkingPhase( + item: TopicTimelineElement, + primaryTopicName: string, + ): WorkingResearchTimelinePhase { + return { + startYear: item.year, + endYear: item.year, + publication_count: item.publication_count, + primaryTopicName, + years: [item], + }; + } + + private pushWorkingPhase( + phases: ResearchTimelinePhase[], + workingPhase: WorkingResearchTimelinePhase | undefined, + ): void { + if (!workingPhase) { + return; + } + + phases.push({ + ...workingPhase, + id: `${workingPhase.startYear}-${workingPhase.endYear}-${this.normalizeTopicName( + workingPhase.primaryTopicName, + )}`, + topics: this.aggregatePhaseTopics(workingPhase.years, workingPhase.primaryTopicName), + }); + } + + private aggregatePhaseTopics( + years: TopicTimelineElement[], + primaryTopicName: string, + ): TopicTimelineTopic[] { + const counts = new Map(); + const originalNames = new Map(); + + for (const year of years) { + for (const topic of year.topics ?? []) { + if (this.isSameTopic(topic.name, primaryTopicName)) { + continue; + } + + const normalizedName = this.normalizeTopicName(topic.name); + + originalNames.set(normalizedName, topic.name); + counts.set(normalizedName, (counts.get(normalizedName) ?? 0) + topic.count); + } + } + + return Array.from(counts.entries()) + .map(([normalizedName, count]) => ({ + name: originalNames.get(normalizedName) ?? normalizedName, + count, + })) + .sort((left, right) => { + if (right.count !== left.count) { + return right.count - left.count; + } + + return left.name.localeCompare(right.name); + }) + .slice(0, this.displayedPhaseTopicLimit); + } + + private getDominantPrimaryTopicCandidates(item: TopicTimelineElement): TopicTimelineTopic[] { + const primaryTopics = item.primary_topics ?? []; + + if (primaryTopics.length === 0) { + return []; + } + + const maxCount = Math.max(...primaryTopics.map((topic) => topic.count)); + + return primaryTopics.filter((topic) => topic.count === maxCount); + } + + private getFirstTopic(item: TopicTimelineElement): TopicTimelineTopic | undefined { + return (item.topics ?? [])[0]; + } + + private isSameTopic(topicName: string, primaryTopicName: string | undefined): boolean { + if (!primaryTopicName) { + return false; + } + + return this.normalizeTopicName(topicName) === this.normalizeTopicName(primaryTopicName); + } + + private normalizeTopicName(topicName: string): string { + return topicName.trim().toLowerCase(); + } + + private parseYearInput(event: Event): number { + const input = event.target as HTMLInputElement | null; + const value = Number(input?.value ?? this.minYear); + + if (!Number.isFinite(value)) { + return this.minYear; + } + + return value; + } + + private clampYear(year: number): number { + return Math.min(Math.max(year, this.minYear), this.maxYear); + } + + private calculateRangePercent(year: number): number { + if (!this.hasYearRange) { + return 0; + } + + const totalRange = this.maxYear - this.minYear; + + if (totalRange <= 0) { + return 0; + } + + return ((year - this.minYear) / totalRange) * 100; + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index 938179bf..3f70b27a 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -1 +1,7 @@ -Dummy \ No newline at end of file +
+ +
\ No newline at end of file diff --git a/webapp/src/app/modules/person-overview/person-overview.component.scss b/webapp/src/app/modules/person-overview/person-overview.component.scss index e69de29b..52461a52 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.scss +++ b/webapp/src/app/modules/person-overview/person-overview.component.scss @@ -0,0 +1,4 @@ +.person-overview { + width: 100%; + display: block; +} \ No newline at end of file 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 a7f7ae5d..ef984db6 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -1,11 +1,98 @@ -import { Component } from '@angular/core'; -import { MatProgressSpinner } from '@angular/material/progress-spinner'; +import { CommonModule } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, ParamMap } from '@angular/router'; +import { combineLatest, distinctUntilChanged, map } from 'rxjs'; + +import { TopicCount, TopicsByYear, WorksService } from '../../api'; +import { + ResearchTimelineComponent, + TopicTimelineElement, + TopicTimelineTopic, +} from './components/research-timeline/research-timeline.component'; + @Component({ selector: 'app-person-overview', - imports: [], + standalone: true, + imports: [CommonModule, ResearchTimelineComponent], templateUrl: './person-overview.component.html', styleUrl: './person-overview.component.scss', }) -export class PersonOverviewComponent { +export class PersonOverviewComponent implements OnInit { + private readonly route = inject(ActivatedRoute); + private readonly worksService = inject(WorksService); + private readonly destroyRef = inject(DestroyRef); + topicTimelineElements: TopicTimelineElement[] = []; + loadingTimeline = false; + timelineLoadFailed = false; + + ngOnInit(): void { + combineLatest(this.route.pathFromRoot.map((route) => route.paramMap)) + .pipe( + map((paramMaps) => this.findAuthorId(paramMaps)), + distinctUntilChanged(), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((authorId) => { + this.loadTopicTimeline(authorId); + }); + } + + private findAuthorId(paramMaps: readonly ParamMap[]): string { + return ( + paramMaps + .map((paramMap) => paramMap.get('id')) + .find((id): id is string => Boolean(id)) ?? '' + ); + } + + private loadTopicTimeline(authorId: string): void { + if (!authorId || authorId === '0') { + this.topicTimelineElements = []; + this.loadingTimeline = false; + this.timelineLoadFailed = false; + return; + } + + this.loadingTimeline = true; + this.timelineLoadFailed = false; + + const topicCountLimit = 4; + + this.worksService + .getTopicsByTimeByAuthor(authorId, topicCountLimit) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (response) => { + this.topicTimelineElements = this.mapTimelineElements(response.elements); + this.loadingTimeline = false; + this.timelineLoadFailed = false; + }, + error: (error) => { + console.error('Topic timeline could not be loaded.', error); + this.topicTimelineElements = []; + this.loadingTimeline = false; + this.timelineLoadFailed = true; + }, + }); + } + + private mapTimelineElements( + elements: TopicsByYear[] | undefined, + ): TopicTimelineElement[] { + return (elements ?? []).map((element) => ({ + year: element.year, + publication_count: element.publication_count ?? 0, + topics: this.mapTopicCounts(element.topics), + primary_topics: this.mapTopicCounts(element.primary_topics), + })); + } + + private mapTopicCounts(topics: TopicCount[] | undefined): TopicTimelineTopic[] { + return (topics ?? []).map((topic) => ({ + name: topic.name, + count: topic.count ?? 0, + })); + } } diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 283cfcce..317a5782 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -101,7 +101,13 @@ readonly personBio = toSignal( ); readonly worksCount = computed(() => this.person()?.works_count ?? null); readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null); - readonly orcid = computed(() => this.getId('orcid')); + readonly orcid = computed(() => { + const rawOrcid = this.getId('orcid'); + if (!rawOrcid) { + return null; + } + return rawOrcid.replace('https://orcid.org/', ''); + }); readonly orcidUrl = computed(() => this.orcid() ? `https://orcid.org/${this.orcid()}` : null, ); diff --git a/webapp/src/proxy.conf.json b/webapp/src/proxy.conf.json index 1e0c9ebd..54ba9d84 100644 --- a/webapp/src/proxy.conf.json +++ b/webapp/src/proxy.conf.json @@ -9,4 +9,4 @@ "secure": false, "changeOrigin": true } -} +} \ No newline at end of file