From 22dd33c0a9fc5ce355e9ffb0b8cb9ce820815fac Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sat, 30 May 2026 09:10:09 +0200 Subject: [PATCH 01/13] Add funders by author endpoint with position counts --- service/src/main/inse/config.py | 2 + service/src/main/inse/logic.py | 182 +++++++++++++++++++++++++++++++ service/src/main/inse/service.py | 19 ++++ 3 files changed, 203 insertions(+) diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index fbd6098f..2b70a56c 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -29,6 +29,8 @@ class Settings(BaseSettings): llm_model: str = 'gemma4:e4b' elasticsearch_url: str = 'https://project.nes.uni-due.de/elastic/' elasticsearch_api_key: str = 'am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==' + elasticsearch_works_url: str = 'https://project.nes.uni-due.de/elastic/openalex-works/_search' + settings = Settings() logger.info(f"Database URL: {settings.database_url}.") diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index d98c878f..013d2547 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -287,3 +287,185 @@ def generate_person_bio(author_id: str) -> str: return llm.call(system_prompt=system_prompt, user_prompt=user_prompt) +def create_publications_by_author_query( + author_id: str, + page: int = 1, + page_size: int = 20 +) -> dict: + if not author_id.startswith("https://openalex.org/"): + author_id = f"https://openalex.org/{author_id}" + + from_value = (page - 1) * page_size + + return { + "from": from_value, + "size": page_size, + "_source": [ + "id", + "title", + "display_name", + "publication_year", + "authorships.author.id", + "authorships.author.display_name", + "authorships.author_position", + "funders.id", + "funders.display_name", + "funders.ror" + ], + "query": { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": author_id + } + } + } + }, + { + "nested": { + "path": "funders", + "query": { + "exists": { + "field": "funders.id" + } + } + } + } + ] + } + } + } + +def get_publications_by_author_id( + author_id: str, + page: int = 1, + page_size: int = 20 +) -> dict: + headers = { + "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", + "Content-Type": "application/json" + } + + payload = create_publications_by_author_query(author_id, page, page_size) + + with httpx.Client() as client: + response = client.post( + config.settings.elasticsearch_works_url, + json=payload, + headers=headers + ) + response.raise_for_status() + data = response.json() + + total = data.get("hits", {}).get("total", {}).get("value", 0) + hits = data.get("hits", {}).get("hits", []) + + return { + "author_id": author_id if author_id.startswith("https://openalex.org/") else f"https://openalex.org/{author_id}", + "page": page, + "page_size": page_size, + "total": total, + "results_count": len(hits), + "results": hits + } + +def get_author_name(author_id: str) -> str | None: + short_author_id = author_id.replace("https://openalex.org/", "") + + search_result = search_persons(author_id=short_author_id) + + if not search_result.persons: + return None + + return search_result.persons[0].name + +def get_author_position_in_publication(publication: dict, author_id: str) -> str: + normalized_author_id = ( + author_id if author_id.startswith("https://openalex.org/") + else f"https://openalex.org/{author_id}" + ) + + for authorship in publication.get("authorships", []): + author = authorship.get("author", {}) + if author.get("id") == normalized_author_id: + return authorship.get("author_position", "unknown") + + return "unknown" + +def get_funders_by_author_id(author_id: str) -> dict: + page = 1 + page_size = 100 + funder_counts = {} + + normalized_author_id = ( + author_id if author_id.startswith("https://openalex.org/") + else f"https://openalex.org/{author_id}" + ) + + author_name = get_author_name(author_id) + + while True: + data = get_publications_by_author_id(author_id, page, page_size) + results = data.get("results", []) + + if not results: + break + + for hit in results: + publication = hit.get("_source", {}) + publication_id = publication.get("id") + author_position = get_author_position_in_publication(publication, author_id) + publication_funders = set() + + # Funders field + for funder in publication.get("funders", []): + funder_id = funder.get("id") + funder_name = funder.get("display_name") + + if funder_id or funder_name: + key = funder_id or funder_name + publication_funders.add((key, funder_id, funder_name)) + + # Count each funder only once per publication + for key, funder_id, funder_name in publication_funders: + if key not in funder_counts: + funder_counts[key] = { + "funder_id": funder_id, + "funder_name": funder_name, + "publication_count": 0, + "author_position_count": { + "first": 0, + "middle": 0, + "last": 0, + "unknown": 0 + }, + "publication_ids": { + "first": [], + "middle": [], + "last": [], + "unknown": [] + } + } + + funder_counts[key]["publication_count"] += 1 + if author_position not in funder_counts[key]["author_position_count"]: + author_position = "unknown" + + funder_counts[key]["author_position_count"][author_position] += 1 + funder_counts[key]["publication_ids"][author_position].append(publication_id) + + if len(results) < page_size: + break + + page += 1 + + return { + "author_id": normalized_author_id, + "author_name": author_name, + "funder_count": len(funder_counts), + "funders": list(funder_counts.values()) + } \ No newline at end of file diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 22a16a19..43a78e5f 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -179,3 +179,22 @@ def search_persons(author_id: Annotated[str, Query(description="OpenAlex author def generate_person_bio(author_id: Annotated[str, Query(description="OpenAlex author ID (e.g., A5093075883)")]): bio = logic.generate_person_bio(author_id) return model.PersonBio(bio=bio) + + +@app.get('/authors/{author_id}/publications', + operation_id='getPublicationsByAuthor', + summary='Get publications by author.', + tags=['Publications']) +def get_publications_by_author( + author_id: str, + page: int = 1, + page_size: int = 20 +): + return logic.get_publications_by_author_id(author_id, page, page_size) + +@app.get('/authors/{author_id}/funders', + operation_id='getFundersByAuthor', + summary='Get funding organizations by author.', + tags=['Funding']) +def get_funders_by_author(author_id: str): + return logic.get_funders_by_author_id(author_id) \ No newline at end of file -- 2.56.1 From ce4ccbf15456be8e0b69f1dd08b29a772c26dabc Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sun, 31 May 2026 09:10:50 +0200 Subject: [PATCH 02/13] Add person funding frontend view --- webapp/src/app/app.routes.ts | 7 +++++++ .../person-funding/person-funding.component.html | 1 + .../person-funding/person-funding.component.scss | 0 .../person-funding/person-funding.component.ts | 11 +++++++++++ webapp/src/app/modules/person/person.component.ts | 1 + 5 files changed, 20 insertions(+) create mode 100644 webapp/src/app/modules/person-funding/person-funding.component.html create mode 100644 webapp/src/app/modules/person-funding/person-funding.component.scss create mode 100644 webapp/src/app/modules/person-funding/person-funding.component.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a257d1fc..cacc3028 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -51,6 +51,13 @@ export const routes: Routes = [ (mod) => mod.PersonPublicationsComponent, ), }, + { + path: 'funding', + loadComponent: () => + import('./modules/person-funding/person-funding.component').then( + (mod) => mod.PersonFundingComponent, + ), + }, ], }, { diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html new file mode 100644 index 00000000..364b6d5b --- /dev/null +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -0,0 +1 @@ +

person-funding!

diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts new file mode 100644 index 00000000..db6f9dc1 --- /dev/null +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -0,0 +1,11 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-person-funding', + imports: [], + templateUrl: './person-funding.component.html', + styleUrl: './person-funding.component.scss', +}) +export class PersonFundingComponent { + +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index f8f6ebe6..faa3ffe5 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -77,6 +77,7 @@ export class PersonComponent implements OnInit, OnDestroy { { label: 'Publikationen', path: 'publications', disabled: false }, { label: 'Netzwerk', path: 'network', disabled: false }, { label: 'Gründungen', path: 'foundings', disabled: true }, + { label: 'Förderungen', path: 'funding', disabled: false }, ]; ngOnInit(): void { -- 2.56.1 From fac08044a8682677f02ee8098734bbfcc01aa67e Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Mon, 1 Jun 2026 14:02:25 +0200 Subject: [PATCH 03/13] Add Person funding View and API integration --- webapp/src/app/api/api/persons.service.ts | 26 ++- .../person-funding.component.html | 94 ++++++++- .../person-funding.component.scss | 197 ++++++++++++++++++ .../person-funding.component.ts | 81 ++++++- 4 files changed, 392 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index cd7c95f2..5d72133b 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -1,7 +1,7 @@ /** * My App Service * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,7 +11,7 @@ import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; @@ -165,4 +165,26 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi ); } + public getFundersByAuthor(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 getFundersByAuthor.'); + } + + let localVarHeaders = this.defaultHeaders; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + let localVarPath = `/authors/${encodeURIComponent(authorId)}/funders`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: 'json', + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); +} + } diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 364b6d5b..56eef4cb 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -1 +1,93 @@ -

person-funding!

+@if (loading) { +

Lade Förderungen...

+} @else if (error) { +

Fehler beim Laden der Förderungen.

+} @else if (funders.length === 0) { +

Keine Förderungen gefunden.

+} @else { +
+ Einzigartige Publikationen: + {{ getUniquePublicationCount() }} +
+
+
+ Förderer: + {{ funders.length }} +
+
+ + +
+ + +
+ Filter nach Position: + + + + +
+ +
+ + +
+ + + + + + + + + @for (funder of filteredFunders; track funder.funder_id) { + + + + + } + +
FördererPublikationen
{{ funder.funder_name }}{{ funder.publication_count }}
+
+ + + @if (selectedFunder) { +
+

{{ selectedFunder.funder_name }}

+ +
+
+ Erstautor + {{ selectedFunder.author_position_count.first }} +
+
+ Mitautor + {{ selectedFunder.author_position_count.middle }} +
+
+ Letztautor + {{ selectedFunder.author_position_count.last }} +
+
+ +

Publikationen

+
    + @for (id of getPublicationIds(selectedFunder); track id) { +
  • + {{ id }} +
  • + } +
+
+ } @else { +
+

Klicke auf einen Förderer für Details.

+
+ } + +
+
+} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index e69de29b..f9337e9d 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -0,0 +1,197 @@ +.message { + padding: 16px; + color: #666; +} + +.funding-container { + padding: 16px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.filter-bar { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + + span { + font-weight: 500; + color: #555; + } + + button { + padding: 6px 14px; + border: 1px solid #ccc; + border-radius: 20px; + background: white; + cursor: pointer; + font-size: 14px; + transition: all 0.2s; + + &:hover { + background: #f0f0f0; + } + + &.active { + background: #3f51b5; + color: white; + border-color: #3f51b5; + } + } +} + +.funding-content { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.funding-list { + flex: 1; + + table { + width: 100%; + border-collapse: collapse; + + th { + text-align: left; + padding: 10px 12px; + border-bottom: 2px solid #e0e0e0; + font-weight: 600; + color: #333; + } + + tr { + cursor: pointer; + transition: background 0.15s; + + &:hover { + background: #f5f5f5; + } + + &.selected { + background: #e8eaf6; + } + } + + td { + padding: 10px 12px; + border-bottom: 1px solid #f0f0f0; + } + + .funder-name { + color: #3f51b5; + font-weight: 500; + } + } +} + +.funding-detail { + width: 340px; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 20px; + background: #fafafa; + + &.empty { + display: flex; + align-items: center; + justify-content: center; + color: #999; + min-height: 200px; + } + + h3 { + margin: 0 0 16px 0; + font-size: 16px; + color: #333; + } + + h4 { + margin: 16px 0 8px 0; + font-size: 14px; + color: #555; + } +} + +.position-stats { + display: flex; + gap: 12px; + margin-bottom: 16px; + + .stat { + flex: 1; + text-align: center; + background: white; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 10px; + + .stat-label { + display: block; + font-size: 12px; + color: #666; + margin-bottom: 4px; + } + + .stat-value { + display: block; + font-size: 22px; + font-weight: bold; + color: #3f51b5; + } + } +} + +.publication-list { + list-style: none; + padding: 0; + margin: 0; + max-height: 300px; + overflow-y: auto; + + li { + padding: 6px 0; + border-bottom: 1px solid #f0f0f0; + font-size: 13px; + + a { + color: #3f51b5; + text-decoration: none; + word-break: break-all; + + &:hover { + text-decoration: underline; + } + } + } + .funding-summary { + display: flex; + gap: 16px; + margin-bottom: 16px; + + .summary-card { + background: #e8eaf6; + border-radius: 8px; + padding: 16px 24px; + text-align: center; + min-width: 150px; + + .summary-value { + display: block; + font-size: 32px; + font-weight: bold; + color: #3f51b5; + } + + .summary-label { + display: block; + font-size: 14px; + color: #555; + margin-top: 4px; + } + } +} +} 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 db6f9dc1..59213f28 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -1,11 +1,86 @@ -import { Component } from '@angular/core'; +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute } from '@angular/router'; +import { PersonsOpenApiService } from '../../api'; @Component({ selector: 'app-person-funding', - imports: [], + imports: [CommonModule], templateUrl: './person-funding.component.html', styleUrl: './person-funding.component.scss', }) -export class PersonFundingComponent { +export class PersonFundingComponent implements OnInit { + private route = inject(ActivatedRoute); + private personsApi = inject(PersonsOpenApiService); + funders: any[] = []; + filteredFunders: any[] = []; + selectedFunder: any = null; + activeFilter: string = 'all'; + loading = true; + error = false; + + ngOnInit(): void { + const authorId = this.route.parent?.snapshot.paramMap.get('id') ?? ''; + if (authorId) { + this.personsApi.getFundersByAuthor(authorId).subscribe({ + next: (result) => { + this.funders = result.funders ?? []; + this.filteredFunders = this.funders; + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + } + }); + } + } + + selectFunder(funder: any): void { + this.selectedFunder = funder; + } + + setFilter(filter: string): void { + this.activeFilter = filter; + this.selectedFunder = null; + if (filter === 'all') { + this.filteredFunders = this.funders; + } else { + this.filteredFunders = this.funders.filter( + f => f.author_position_count[filter] > 0 + ); + } + } + + getPublicationIds(funder: any): string[] { + if (this.activeFilter === 'all') { + return [ + ...funder.publication_ids.first, + ...funder.publication_ids.middle, + ...funder.publication_ids.last, + ...funder.publication_ids.unknown + ]; + } + return funder.publication_ids[this.activeFilter] ?? []; + } + + getPositionLabel(position: string): string { + const labels: Record = { + first: 'Erstautor', + middle: 'Mitautor', + last: 'Letztautor', + unknown: 'Unbekannt' + }; + return labels[position] ?? position; + } + getUniquePublicationCount(): number { + const allIds = new Set(); + for (const funder of this.funders) { + for (const ids of Object.values(funder.publication_ids) as string[][]) { + ids.forEach(id => allIds.add(id)); + } + } + return allIds.size; +} } -- 2.56.1 From 5294d26552ad7ccab2049ec6712fa13b210bbf41 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 1 Jun 2026 22:21:50 +0200 Subject: [PATCH 04/13] Refactor funders logic into separate module and add tests --- service/src/main/inse/funders/__init__.py | 5 + .../inse/funders/elastic_search_client.py | 123 +++++++++++ service/src/main/inse/funders/logic.py | 203 ++++++++++++++++++ service/src/main/inse/funders/model.py | 41 ++++ service/src/main/inse/funders/service.py | 39 ++++ service/src/main/inse/funders/test_logic.py | 166 ++++++++++++++ service/src/main/inse/logic.py | 186 +--------------- service/src/main/inse/service.py | 20 +- 8 files changed, 580 insertions(+), 203 deletions(-) create mode 100644 service/src/main/inse/funders/__init__.py create mode 100644 service/src/main/inse/funders/elastic_search_client.py create mode 100644 service/src/main/inse/funders/logic.py create mode 100644 service/src/main/inse/funders/model.py create mode 100644 service/src/main/inse/funders/service.py create mode 100644 service/src/main/inse/funders/test_logic.py diff --git a/service/src/main/inse/funders/__init__.py b/service/src/main/inse/funders/__init__.py new file mode 100644 index 00000000..a12699fd --- /dev/null +++ b/service/src/main/inse/funders/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Funders domain package. +""" diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py new file mode 100644 index 00000000..5b848c80 --- /dev/null +++ b/service/src/main/inse/funders/elastic_search_client.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + HTTP client for funded-publication searches in the OpenAlex works index. +""" +from typing import Any + +import httpx + +from .. import config + + +class MissingApiKeyError(Exception): + pass + + +class FundedPublicationsSearchClient: + def __init__( + self, + base_url: str | None = None, + index: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/") + self.index = index or config.settings.openalex_works_search_index + self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key + self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds + self.transport = transport + + @staticmethod + def indexed_author_id(author_id: str) -> str: + short_id = author_id.strip().removeprefix("https://openalex.org/") + return f"https://openalex.org/{short_id}" + + def funded_publications_by_author_query( + self, + author_id: str, + page: int, + size: int, + ) -> dict[str, Any]: + indexed_author_id = self.indexed_author_id(author_id) + return { + "from": (page - 1) * size, + "size": size, + "_source": [ + "id", + "title", + "display_name", + "publication_year", + "authorships.author.id", + "authorships.author.display_name", + "authorships.author_position", + "funders.id", + "funders.display_name", + "funders.ror", + "awards.id", + "awards.funder_id", + "awards.funder_display_name", + "awards.funder_award_id", + ], + "query": { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": indexed_author_id, + }, + }, + }, + }, + { + "bool": { + "should": [ + { + "nested": { + "path": "funders", + "query": { + "exists": { + "field": "funders.id", + }, + }, + }, + }, + { + "nested": { + "path": "awards", + "query": { + "exists": { + "field": "awards.funder_id", + }, + }, + }, + }, + ], + "minimum_should_match": 1, + }, + }, + ], + }, + }, + } + + async def search(self, payload: dict[str, Any]) -> dict[str, Any]: + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{self.index}/_search", + headers={"Authorization": f"ApiKey {self.api_key}"}, + json=payload, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py new file mode 100644 index 00000000..b7383ecf --- /dev/null +++ b/service/src/main/inse/funders/logic.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Business logic for author funding based on publication works. +""" +import logging +from typing import Any + +import httpx +from fastapi import HTTPException +from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_503_SERVICE_UNAVAILABLE + +from .. import logic as person_logic +from . import model +from .elastic_search_client import FundedPublicationsSearchClient +from .elastic_search_client import MissingApiKeyError + +logger = logging.getLogger(__name__) + +_VALID_AUTHOR_POSITIONS = frozenset({"first", "middle", "last"}) + + +async def get_publications_by_author_id( + author_id: str, + page: int = 1, + page_size: int = 20, + client: FundedPublicationsSearchClient | None = None, +) -> model.PublicationsByAuthorResponse: + search_client = client or FundedPublicationsSearchClient() + data = await _search_funded_publications( + search_client, + author_id, + page, + page_size, + ) + total, hits = _parse_publication_search_response(data) + + return model.PublicationsByAuthorResponse( + author_id=FundedPublicationsSearchClient.indexed_author_id(author_id), + page=page, + page_size=page_size, + total=total, + results_count=len(hits), + results=hits, + ) + + +async def get_funders_by_author_id( + author_id: str, + client: FundedPublicationsSearchClient | None = None, +) -> model.FundersByAuthorResponse: + search_client = client or FundedPublicationsSearchClient() + page = 1 + page_size = 100 + funder_counts: dict[str, dict[str, Any]] = {} + + normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id) + author_name = _get_author_name(author_id) + + while True: + data = await _search_funded_publications( + search_client, + author_id, + page, + page_size, + ) + total, results = _parse_publication_search_response(data) + + if not results: + break + + _collect_funders_from_publications(results, author_id, funder_counts) + + if page * page_size >= total: + break + + page += 1 + + funders = sorted( + funder_counts.values(), + key=lambda entry: entry["publication_count"], + reverse=True, + ) + + return model.FundersByAuthorResponse( + author_id=normalized_author_id, + author_name=author_name, + funder_count=len(funders), + funders=[model.FunderByAuthor.model_validate(entry) for entry in funders], + ) + + +async def _search_funded_publications( + search_client: FundedPublicationsSearchClient, + author_id: str, + page: int, + page_size: int, +) -> dict: + try: + payload = search_client.funded_publications_by_author_query( + author_id, + page, + page_size, + ) + return await search_client.search(payload) + except MissingApiKeyError as exc: + logger.error("OpenAlex works Elasticsearch API key is not configured.") + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="OpenAlex works search is not configured.", + ) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex works search request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + + +def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: + hits = data.get("hits", {}) + total = hits.get("total", 0) + + if isinstance(total, dict): + total = total.get("value", 0) + + return total, hits.get("hits", []) + + +def _get_author_name(author_id: str) -> str | None: + short_author_id = author_id.replace("https://openalex.org/", "") + search_result = person_logic.search_persons(author_id=short_author_id) + + if not search_result.persons: + return None + + return search_result.persons[0].name + + +def _get_author_position_in_publication(publication: dict, author_id: str) -> str: + normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id) + + for authorship in publication.get("authorships", []): + author = authorship.get("author", {}) + if author.get("id") == normalized_author_id: + position = authorship.get("author_position", "unknown") + if position in _VALID_AUTHOR_POSITIONS: + return position + return "unknown" + + return "unknown" + + +def _collect_funders_from_publications( + results: list[dict], + author_id: str, + funder_counts: dict[str, dict[str, Any]], +) -> None: + for hit in results: + publication = hit.get("_source", {}) + publication_id = publication.get("id") + author_position = _get_author_position_in_publication(publication, author_id) + publication_funders: set[tuple[str, str | None, str | None]] = set() + + for funder in publication.get("funders", []): + funder_id = funder.get("id") + funder_name = funder.get("display_name") + if funder_id or funder_name: + key = funder_id or funder_name + publication_funders.add((key, funder_id, funder_name)) + + for award in publication.get("awards", []): + funder_id = award.get("funder_id") + funder_name = award.get("funder_display_name") + if funder_id or funder_name: + key = funder_id or funder_name + publication_funders.add((key, funder_id, funder_name)) + + for key, funder_id, funder_name in publication_funders: + if key not in funder_counts: + funder_counts[key] = { + "funder_id": funder_id, + "funder_name": funder_name, + "publication_count": 0, + "author_position_count": { + "first": 0, + "middle": 0, + "last": 0, + "unknown": 0, + }, + "publication_ids": { + "first": [], + "middle": [], + "last": [], + "unknown": [], + }, + } + + entry = funder_counts[key] + entry["publication_count"] += 1 + entry["author_position_count"][author_position] += 1 + entry["publication_ids"][author_position].append(publication_id) diff --git a/service/src/main/inse/funders/model.py b/service/src/main/inse/funders/model.py new file mode 100644 index 00000000..d7b90fa1 --- /dev/null +++ b/service/src/main/inse/funders/model.py @@ -0,0 +1,41 @@ +from typing import Any + +from pydantic import BaseModel + + +class PublicationsByAuthorResponse(BaseModel): + author_id: str + page: int + page_size: int + total: int + results_count: int + results: list[dict[str, Any]] + + +class PublicationIdsByAuthorPosition(BaseModel): + first: list[str] = [] + middle: list[str] = [] + last: list[str] = [] + unknown: list[str] = [] + + +class AuthorPositionCount(BaseModel): + first: int = 0 + middle: int = 0 + last: int = 0 + unknown: int = 0 + + +class FunderByAuthor(BaseModel): + funder_id: str | None = None + funder_name: str | None = None + publication_count: int + author_position_count: AuthorPositionCount + publication_ids: PublicationIdsByAuthorPosition + + +class FundersByAuthorResponse(BaseModel): + author_id: str + author_name: str | None = None + funder_count: int + funders: list[FunderByAuthor] \ No newline at end of file diff --git a/service/src/main/inse/funders/service.py b/service/src/main/inse/funders/service.py new file mode 100644 index 00000000..9ead124d --- /dev/null +++ b/service/src/main/inse/funders/service.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + REST API for author publications and funding. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from . import logic +from . import model + + +router = APIRouter(prefix="/authors", tags=["Funding"]) + + +@router.get( + "/{author_id}/publications", + operation_id="getPublicationsByAuthor", + response_model=model.PublicationsByAuthorResponse, + summary="Get funded publications by author.", +) +async def get_publications_by_author( + author_id: str, + page: Annotated[int, Query(ge=1)] = 1, + page_size: Annotated[int, Query(ge=1, le=1000)] = 20, +): + return await logic.get_publications_by_author_id(author_id, page, page_size) + + +@router.get( + "/{author_id}/funders", + operation_id="getFundersByAuthor", + response_model=model.FundersByAuthorResponse, + summary="Get funding organizations by author.", +) +async def get_funders_by_author(author_id: str): + return await logic.get_funders_by_author_id(author_id) diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py new file mode 100644 index 00000000..a49a7559 --- /dev/null +++ b/service/src/main/inse/funders/test_logic.py @@ -0,0 +1,166 @@ +import json + +import httpx +import pytest +from fastapi import HTTPException + +from inse.funders import logic +from inse.funders.elastic_search_client import FundedPublicationsSearchClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def _funded_publication_hit( + work_id: str, + *, + funder_id: str | None = "https://openalex.org/F123", + funder_name: str | None = "Example Funder", + author_position: str = "first", + award_funder_id: str | None = None, + award_funder_name: str | None = None, +) -> dict: + source: dict = { + "id": work_id, + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5023888391", + "display_name": "Example Author", + }, + "author_position": author_position, + } + ], + "funders": [], + "awards": [], + } + if funder_id or funder_name: + source["funders"].append( + { + "id": funder_id, + "display_name": funder_name, + } + ) + if award_funder_id or award_funder_name: + source["awards"].append( + { + "funder_id": award_funder_id, + "funder_display_name": award_funder_name, + } + ) + return {"_source": source} + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content.decode("utf-8")) + assert payload["from"] == 0 + return httpx.Response( + 200, + json={ + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + author_position="first", + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + author_position="last", + ), + ], + }, + }, + ) + + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type( + "Result", + (), + {"persons": [type("Person", (), {"name": "Example Author"})()]}, + )(), + ) + + client = FundedPublicationsSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + response = await logic.get_funders_by_author_id("A5023888391", client=client) + + assert response.author_id == "https://openalex.org/A5023888391" + assert response.author_name == "Example Author" + assert response.funder_count == 1 + assert response.funders[0].funder_id == "https://openalex.org/F123" + assert response.funders[0].funder_name == "Funder A" + assert response.funders[0].publication_count == 2 + assert response.funders[0].author_position_count.first == 1 + assert response.funders[0].author_position_count.last == 1 + assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"] + assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"] + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch): + requested_pages: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content.decode("utf-8")) + page = payload["from"] // payload["size"] + 1 + requested_pages.append(page) + return httpx.Response( + 200, + json={ + "hits": { + "total": {"value": 101}, + "hits": [ + _funded_publication_hit( + f"https://openalex.org/W{page}", + funder_id=f"https://openalex.org/F{page}", + funder_name=f"Funder {page}", + ) + ], + }, + }, + ) + + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type("Result", (), {"persons": []})(), + ) + + client = FundedPublicationsSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + response = await logic.get_funders_by_author_id("A5023888391", client=client) + + assert requested_pages == [1, 2] + assert response.funder_count == 2 + assert {funder.funder_name for funder in response.funders} == {"Funder 1", "Funder 2"} + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(): + client = FundedPublicationsSearchClient(api_key="") + + with pytest.raises(HTTPException) as exc: + await logic.get_funders_by_author_id("A5023888391", client=client) + + assert exc.value.status_code == 503 diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 013d2547..9c1728f4 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -284,188 +284,4 @@ def generate_person_bio(author_id: str) -> str: system_prompt = "Erstelle eine Beschreibung der Person in 3-5 Sätzen. Gebe nur die Beschreibung zurück, ohne Einleitung oder Schluss." user_prompt = f"Daten zur Person:\n{person_json}" - return llm.call(system_prompt=system_prompt, user_prompt=user_prompt) - - -def create_publications_by_author_query( - author_id: str, - page: int = 1, - page_size: int = 20 -) -> dict: - if not author_id.startswith("https://openalex.org/"): - author_id = f"https://openalex.org/{author_id}" - - from_value = (page - 1) * page_size - - return { - "from": from_value, - "size": page_size, - "_source": [ - "id", - "title", - "display_name", - "publication_year", - "authorships.author.id", - "authorships.author.display_name", - "authorships.author_position", - "funders.id", - "funders.display_name", - "funders.ror" - ], - "query": { - "bool": { - "must": [ - { - "nested": { - "path": "authorships", - "query": { - "term": { - "authorships.author.id": author_id - } - } - } - }, - { - "nested": { - "path": "funders", - "query": { - "exists": { - "field": "funders.id" - } - } - } - } - ] - } - } - } - -def get_publications_by_author_id( - author_id: str, - page: int = 1, - page_size: int = 20 -) -> dict: - headers = { - "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", - "Content-Type": "application/json" - } - - payload = create_publications_by_author_query(author_id, page, page_size) - - with httpx.Client() as client: - response = client.post( - config.settings.elasticsearch_works_url, - json=payload, - headers=headers - ) - response.raise_for_status() - data = response.json() - - total = data.get("hits", {}).get("total", {}).get("value", 0) - hits = data.get("hits", {}).get("hits", []) - - return { - "author_id": author_id if author_id.startswith("https://openalex.org/") else f"https://openalex.org/{author_id}", - "page": page, - "page_size": page_size, - "total": total, - "results_count": len(hits), - "results": hits - } - -def get_author_name(author_id: str) -> str | None: - short_author_id = author_id.replace("https://openalex.org/", "") - - search_result = search_persons(author_id=short_author_id) - - if not search_result.persons: - return None - - return search_result.persons[0].name - -def get_author_position_in_publication(publication: dict, author_id: str) -> str: - normalized_author_id = ( - author_id if author_id.startswith("https://openalex.org/") - else f"https://openalex.org/{author_id}" - ) - - for authorship in publication.get("authorships", []): - author = authorship.get("author", {}) - if author.get("id") == normalized_author_id: - return authorship.get("author_position", "unknown") - - return "unknown" - -def get_funders_by_author_id(author_id: str) -> dict: - page = 1 - page_size = 100 - funder_counts = {} - - normalized_author_id = ( - author_id if author_id.startswith("https://openalex.org/") - else f"https://openalex.org/{author_id}" - ) - - author_name = get_author_name(author_id) - - while True: - data = get_publications_by_author_id(author_id, page, page_size) - results = data.get("results", []) - - if not results: - break - - for hit in results: - publication = hit.get("_source", {}) - publication_id = publication.get("id") - author_position = get_author_position_in_publication(publication, author_id) - publication_funders = set() - - # Funders field - for funder in publication.get("funders", []): - funder_id = funder.get("id") - funder_name = funder.get("display_name") - - if funder_id or funder_name: - key = funder_id or funder_name - publication_funders.add((key, funder_id, funder_name)) - - # Count each funder only once per publication - for key, funder_id, funder_name in publication_funders: - if key not in funder_counts: - funder_counts[key] = { - "funder_id": funder_id, - "funder_name": funder_name, - "publication_count": 0, - "author_position_count": { - "first": 0, - "middle": 0, - "last": 0, - "unknown": 0 - }, - "publication_ids": { - "first": [], - "middle": [], - "last": [], - "unknown": [] - } - } - - funder_counts[key]["publication_count"] += 1 - if author_position not in funder_counts[key]["author_position_count"]: - author_position = "unknown" - - funder_counts[key]["author_position_count"][author_position] += 1 - funder_counts[key]["publication_ids"][author_position].append(publication_id) - - if len(results) < page_size: - break - - page += 1 - - return { - "author_id": normalized_author_id, - "author_name": author_name, - "funder_count": len(funder_counts), - "funders": list(funder_counts.values()) - } \ No newline at end of file + return llm.call(system_prompt=system_prompt, user_prompt=user_prompt) \ No newline at end of file diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 43a78e5f..23fd6b05 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -23,6 +23,7 @@ from . import database from . import security from . import util from .works import service as works_service +from .funders import service as funders_service logger = logging.getLogger(__name__) @@ -34,6 +35,7 @@ app = FastAPI(redoc_url=None, summary='My App Service API', version='1.0.0') app.include_router(works_service.router) +app.include_router(funders_service.router) @app.get("/", include_in_schema=False) async def show_api(): @@ -180,21 +182,3 @@ def generate_person_bio(author_id: Annotated[str, Query(description="OpenAlex au bio = logic.generate_person_bio(author_id) return model.PersonBio(bio=bio) - -@app.get('/authors/{author_id}/publications', - operation_id='getPublicationsByAuthor', - summary='Get publications by author.', - tags=['Publications']) -def get_publications_by_author( - author_id: str, - page: int = 1, - page_size: int = 20 -): - return logic.get_publications_by_author_id(author_id, page, page_size) - -@app.get('/authors/{author_id}/funders', - operation_id='getFundersByAuthor', - summary='Get funding organizations by author.', - tags=['Funding']) -def get_funders_by_author(author_id: str): - return logic.get_funders_by_author_id(author_id) \ No newline at end of file -- 2.56.1 From 6fe70c8738c1c7cdd59c53c3e15400e2133669e1 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 1 Jun 2026 22:49:33 +0200 Subject: [PATCH 05/13] Update person funding frontend --- .../person-funding.component.html | 4 +-- .../person-funding.component.ts | 30 ++++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 56eef4cb..7c59a864 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -12,7 +12,7 @@
Förderer: - {{ funders.length }} + {{ filteredFunders.length }}
@@ -46,7 +46,7 @@ (click)="selectFunder(funder)" > {{ funder.funder_name }} - {{ funder.publication_count }} + {{ getPublicationCount(funder) }} } 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 59213f28..6ba90014 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -16,7 +16,7 @@ export class PersonFundingComponent implements OnInit { funders: any[] = []; filteredFunders: any[] = []; selectedFunder: any = null; - activeFilter: string = 'all'; + activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all'; loading = true; error = false; @@ -41,7 +41,7 @@ export class PersonFundingComponent implements OnInit { this.selectedFunder = funder; } - setFilter(filter: string): void { + setFilter(filter: 'all' | 'first' | 'middle' | 'last'): void { this.activeFilter = filter; this.selectedFunder = null; if (filter === 'all') { @@ -53,6 +53,13 @@ export class PersonFundingComponent implements OnInit { } } + getPublicationCount(funder: any): number { + if (this.activeFilter === 'all') { + return funder.publication_count ?? 0; + } + return funder.author_position_count?.[this.activeFilter] ?? 0; + } + getPublicationIds(funder: any): string[] { if (this.activeFilter === 'all') { return [ @@ -74,13 +81,20 @@ export class PersonFundingComponent implements OnInit { }; return labels[position] ?? position; } + getUniquePublicationCount(): number { - const allIds = new Set(); - for (const funder of this.funders) { - for (const ids of Object.values(funder.publication_ids) as string[][]) { - ids.forEach(id => allIds.add(id)); + const allIds = new Set(); + for (const funder of this.funders) { + if (this.activeFilter === 'all') { + for (const ids of Object.values(funder.publication_ids) as string[][]) { + ids.forEach((id: string) => allIds.add(id)); + } + } else { + (funder.publication_ids[this.activeFilter] ?? []).forEach((id: string) => + allIds.add(id), + ); + } } + return allIds.size; } - return allIds.size; -} } -- 2.56.1 From 9c4919162980aa462d4765a15a921c523b02cdbf Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Tue, 2 Jun 2026 12:35:44 +0200 Subject: [PATCH 06/13] Persist funding tab state after reload via query params --- .../person-funding.component.ts | 58 ++++++++++++++++++- 1 file changed, 55 insertions(+), 3 deletions(-) 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 6ba90014..bc8446dd 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -1,6 +1,7 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute } from '@angular/router'; +import { Router } from '@angular/router'; import { PersonsOpenApiService } from '../../api'; @Component({ @@ -11,7 +12,9 @@ import { PersonsOpenApiService } from '../../api'; }) export class PersonFundingComponent implements OnInit { private route = inject(ActivatedRoute); + private router = inject(Router); private personsApi = inject(PersonsOpenApiService); + private initialSelectedFunderKey: string | null = null; funders: any[] = []; filteredFunders: any[] = []; @@ -22,11 +25,18 @@ export class PersonFundingComponent implements OnInit { ngOnInit(): void { const authorId = this.route.parent?.snapshot.paramMap.get('id') ?? ''; + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (authorId) { this.personsApi.getFundersByAuthor(authorId).subscribe({ next: (result) => { this.funders = result.funders ?? []; - this.filteredFunders = this.funders; + this.applyFilter(); + this.restoreSelectedFunderFromUrl(); this.loading = false; }, error: () => { @@ -39,20 +49,62 @@ export class PersonFundingComponent implements OnInit { selectFunder(funder: any): void { this.selectedFunder = funder; + this.updateQueryParams(); } setFilter(filter: 'all' | 'first' | 'middle' | 'last'): void { this.activeFilter = filter; + this.applyFilter(); + this.updateQueryParams(); + } + + private applyFilter(): void { this.selectedFunder = null; - if (filter === 'all') { + if (this.activeFilter === 'all') { this.filteredFunders = this.funders; } else { this.filteredFunders = this.funders.filter( - f => f.author_position_count[filter] > 0 + f => f.author_position_count[this.activeFilter] > 0 ); } } + private restoreSelectedFunderFromUrl(): void { + if (!this.initialSelectedFunderKey) { + return; + } + + const matchedFunder = this.filteredFunders.find( + (funder: any) => this.getFunderKey(funder) === this.initialSelectedFunderKey + ); + + if (matchedFunder) { + this.selectedFunder = matchedFunder; + } else { + this.updateQueryParams(); + } + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null + }, + queryParamsHandling: 'merge', + replaceUrl: true + }); + } + + private getFunderKey(funder: any): string { + return funder.funder_id ?? funder.funder_name ?? ''; + } + + private isValidFilter(value: string | null): value is 'all' | 'first' | 'middle' | 'last' { + return value === 'all' || value === 'first' || value === 'middle' || value === 'last'; + } + getPublicationCount(funder: any): number { if (this.activeFilter === 'all') { return funder.publication_count ?? 0; -- 2.56.1 From 300a618cfde4c3773e34a2d2a9e29693ed1cdc49 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Tue, 2 Jun 2026 12:52:50 +0200 Subject: [PATCH 07/13] Open publication links directly as PDF with HTML fallback --- .../person-funding.component.html | 2 +- .../person-funding.component.ts | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 7c59a864..075e1e2b 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -77,7 +77,7 @@
    @for (id of getPublicationIds(selectedFunder); track id) {
  • - {{ id }} + {{ id }}
  • }
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 bc8446dd..d736bd1f 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -15,6 +15,7 @@ export class PersonFundingComponent implements OnInit { private router = inject(Router); private personsApi = inject(PersonsOpenApiService); private initialSelectedFunderKey: string | null = null; + private publicationUrlCache = new Map(); funders: any[] = []; filteredFunders: any[] = []; @@ -124,6 +125,12 @@ export class PersonFundingComponent implements OnInit { return funder.publication_ids[this.activeFilter] ?? []; } + async openPublication(event: MouseEvent, publicationId: string): Promise { + event.preventDefault(); + const url = await this.resolvePreferredPublicationUrl(publicationId); + window.open(url, '_blank', 'noopener'); + } + getPositionLabel(position: string): string { const labels: Record = { first: 'Erstautor', @@ -149,4 +156,42 @@ export class PersonFundingComponent implements OnInit { } return allIds.size; } + + private async resolvePreferredPublicationUrl(publicationId: string): Promise { + const cached = this.publicationUrlCache.get(publicationId); + if (cached) { + return cached; + } + + const fallbackUrl = publicationId; + const workId = publicationId.replace('https://openalex.org/', '').trim(); + if (!workId) { + return fallbackUrl; + } + + try { + const response = await fetch(`https://api.openalex.org/works/${encodeURIComponent(workId)}`); + if (!response.ok) { + return fallbackUrl; + } + + const work = await response.json(); + const pdfUrl = + work?.primary_location?.pdf_url ?? + work?.best_oa_location?.pdf_url ?? + null; + + const htmlUrl = + work?.primary_location?.landing_page_url ?? + work?.best_oa_location?.landing_page_url ?? + work?.open_access?.oa_url ?? + null; + + const resolvedUrl = pdfUrl || htmlUrl || fallbackUrl; + this.publicationUrlCache.set(publicationId, resolvedUrl); + return resolvedUrl; + } catch { + return fallbackUrl; + } + } } -- 2.56.1 From b2996b07c66196d1c6f3aba97ce0cb50ffa5b48b Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Tue, 2 Jun 2026 13:05:36 +0200 Subject: [PATCH 08/13] Refine funding detail view by showing position stats per active filter --- .../modules/person-funding/person-funding.component.html | 6 ++++++ .../app/modules/person-funding/person-funding.component.ts | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 075e1e2b..8469b157 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -59,18 +59,24 @@

{{ selectedFunder.funder_name }}

+ @if (shouldShowPosition('first')) {
Erstautor {{ selectedFunder.author_position_count.first }}
+ } + @if (shouldShowPosition('middle')) {
Mitautor {{ selectedFunder.author_position_count.middle }}
+ } + @if (shouldShowPosition('last')) {
Letztautor {{ selectedFunder.author_position_count.last }}
+ }

Publikationen

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 d736bd1f..76861ca0 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -141,6 +141,10 @@ export class PersonFundingComponent implements OnInit { return labels[position] ?? position; } + shouldShowPosition(position: 'first' | 'middle' | 'last'): boolean { + return this.activeFilter === 'all' || this.activeFilter === position; + } + getUniquePublicationCount(): number { const allIds = new Set(); for (const funder of this.funders) { -- 2.56.1 From fd09c5e08c5d4e9be783c6c88be8c1845424f95b Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Wed, 3 Jun 2026 09:14:46 +0200 Subject: [PATCH 09/13] Improve funding view pagination and UI styling --- .../person-funding.component.html | 42 +++++++-- .../person-funding.component.scss | 80 ++++++++++------ .../person-funding.component.ts | 94 ++++++++++++++++++- 3 files changed, 177 insertions(+), 39 deletions(-) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 8469b157..a93080b6 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -5,16 +5,16 @@ } @else if (funders.length === 0) {

Keine Förderungen gefunden.

} @else { -
- Einzigartige Publikationen: - {{ getUniquePublicationCount() }} -
-
- Förderer: - {{ filteredFunders.length }} +

+ Einzigartige Publikationen: + {{ getUniquePublicationCount() }} +

+

+ Förderer: + {{ filteredFunders.length }} +

-
@@ -40,7 +40,7 @@ - @for (funder of filteredFunders; track funder.funder_id) { + @for (funder of getPagedFunders(); track funder.funder_id) { + @if (hasFunderListPagination()) { +
+ + Seite {{ selectedFunderListPage }} von {{ getFunderListPageCount() }} + +
+ }
@@ -81,12 +92,23 @@

Publikationen

    - @for (id of getPublicationIds(selectedFunder); track id) { + @for (id of getSelectedPublicationIdsPage(); track id) {
  • {{ id }}
  • }
+ @if (hasPublicationPagination()) { +
+ + Seite {{ selectedPublicationPage }} von {{ getSelectedPublicationPageCount() }} + +
+ } } @else {
diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss index f9337e9d..b9f511c9 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.scss +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -35,9 +35,13 @@ } &.active { - background: #3f51b5; - color: white; - border-color: #3f51b5; + background: + radial-gradient(circle at 50% 30%, rgba(255, 255, 255, 0.78), transparent 34%), + linear-gradient(145deg, #c8d9ff, #f7faff 48%, #88a9ee); + color: var(--sg-primary); + border-color: var(--sg-border); + font-weight: 600; + box-shadow: var(--sg-shadow-sm); } } } @@ -72,7 +76,7 @@ } &.selected { - background: #e8eaf6; + background: #f0f0f0; } } @@ -82,7 +86,7 @@ } .funder-name { - color: #3f51b5; + color: #333; font-weight: 500; } } @@ -140,7 +144,7 @@ display: block; font-size: 22px; font-weight: bold; - color: #3f51b5; + color: #333; } } } @@ -158,40 +162,60 @@ font-size: 13px; a { - color: #3f51b5; + color: #2563eb; text-decoration: none; word-break: break-all; &:hover { + color: #1d4ed8; text-decoration: underline; } } } - .funding-summary { +} + +.publication-pagination { display: flex; - gap: 16px; - margin-bottom: 16px; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 12px; - .summary-card { - background: #e8eaf6; - border-radius: 8px; - padding: 16px 24px; - text-align: center; - min-width: 150px; + button { + padding: 4px 10px; + border: 1px solid #d0d0d0; + border-radius: 6px; + background: white; + cursor: pointer; + font-size: 12px; - .summary-value { - display: block; - font-size: 32px; - font-weight: bold; - color: #3f51b5; - } - - .summary-label { - display: block; - font-size: 14px; - color: #555; - margin-top: 4px; + &:disabled { + opacity: 0.5; + cursor: default; } } + + span { + font-size: 12px; + color: #666; + } } + +.funding-summary { + margin-bottom: 16px; + + .summary-line { + margin: 0 0 4px 0; + font-size: 14px; + color: #333; + } + + .summary-label { + color: #333; + } + + .summary-value { + font-weight: 600; + color: #333; + } } 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 76861ca0..5e9662ea 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -15,11 +15,17 @@ export class PersonFundingComponent implements OnInit { private router = inject(Router); private personsApi = inject(PersonsOpenApiService); private initialSelectedFunderKey: string | null = null; + private initialPublicationPage = 1; + private initialFunderListPage = 1; private publicationUrlCache = new Map(); funders: any[] = []; filteredFunders: any[] = []; selectedFunder: any = null; + selectedFunderListPage = 1; + selectedPublicationPage = 1; + readonly funderListPageSize = 10; + readonly publicationPageSize = 10; activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all'; loading = true; error = false; @@ -28,6 +34,10 @@ export class PersonFundingComponent implements OnInit { const authorId = this.route.parent?.snapshot.paramMap.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); + this.initialPublicationPage = this.parsePageParam( + this.route.snapshot.queryParamMap.get('publicationPage') ?? this.route.snapshot.queryParamMap.get('page') + ); + this.initialFunderListPage = this.parsePageParam(this.route.snapshot.queryParamMap.get('funderPage')); if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } @@ -37,6 +47,7 @@ export class PersonFundingComponent implements OnInit { next: (result) => { this.funders = result.funders ?? []; this.applyFilter(); + this.selectedFunderListPage = this.clampPage(this.initialFunderListPage, this.getFunderListPageCount()); this.restoreSelectedFunderFromUrl(); this.loading = false; }, @@ -50,6 +61,7 @@ export class PersonFundingComponent implements OnInit { selectFunder(funder: any): void { this.selectedFunder = funder; + this.selectedPublicationPage = 1; this.updateQueryParams(); } @@ -61,6 +73,8 @@ export class PersonFundingComponent implements OnInit { private applyFilter(): void { this.selectedFunder = null; + this.selectedFunderListPage = 1; + this.selectedPublicationPage = 1; if (this.activeFilter === 'all') { this.filteredFunders = this.funders; } else { @@ -81,6 +95,17 @@ export class PersonFundingComponent implements OnInit { if (matchedFunder) { this.selectedFunder = matchedFunder; + const matchedIndex = this.filteredFunders.findIndex( + (funder: any) => this.getFunderKey(funder) === this.getFunderKey(matchedFunder) + ); + if (matchedIndex >= 0) { + this.selectedFunderListPage = Math.floor(matchedIndex / this.funderListPageSize) + 1; + } + this.selectedPublicationPage = this.clampPublicationPage( + this.initialPublicationPage, + this.getPublicationPageCountForFunder(matchedFunder), + ); + this.updateQueryParams(); } else { this.updateQueryParams(); } @@ -91,7 +116,9 @@ export class PersonFundingComponent implements OnInit { relativeTo: this.route, queryParams: { filter: this.activeFilter, - funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null + funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null, + publicationPage: this.selectedFunder ? this.selectedPublicationPage : null, + funderPage: this.selectedFunderListPage }, queryParamsHandling: 'merge', replaceUrl: true @@ -125,6 +152,50 @@ export class PersonFundingComponent implements OnInit { return funder.publication_ids[this.activeFilter] ?? []; } + getPagedFunders(): any[] { + const startIndex = (this.selectedFunderListPage - 1) * this.funderListPageSize; + return this.filteredFunders.slice(startIndex, startIndex + this.funderListPageSize); + } + + hasFunderListPagination(): boolean { + return this.getFunderListPageCount() > 1; + } + + getFunderListPageCount(): number { + return Math.max(1, Math.ceil(this.filteredFunders.length / this.funderListPageSize)); + } + + setFunderListPage(page: number): void { + this.selectedFunderListPage = this.clampPage(page, this.getFunderListPageCount()); + this.updateQueryParams(); + } + + getSelectedPublicationIdsPage(): string[] { + if (!this.selectedFunder) { + return []; + } + const allPublicationIds = this.getPublicationIds(this.selectedFunder); + const startIndex = (this.selectedPublicationPage - 1) * this.publicationPageSize; + return allPublicationIds.slice(startIndex, startIndex + this.publicationPageSize); + } + + hasPublicationPagination(): boolean { + return this.getSelectedPublicationPageCount() > 1; + } + + getSelectedPublicationPageCount(): number { + if (!this.selectedFunder) { + return 1; + } + return this.getPublicationPageCountForFunder(this.selectedFunder); + } + + setPublicationPage(page: number): void { + const totalPages = this.getSelectedPublicationPageCount(); + this.selectedPublicationPage = this.clampPublicationPage(page, totalPages); + this.updateQueryParams(); + } + async openPublication(event: MouseEvent, publicationId: string): Promise { event.preventDefault(); const url = await this.resolvePreferredPublicationUrl(publicationId); @@ -198,4 +269,25 @@ export class PersonFundingComponent implements OnInit { return fallbackUrl; } } + + private getPublicationPageCountForFunder(funder: any): number { + const publicationCount = this.getPublicationIds(funder).length; + return Math.max(1, Math.ceil(publicationCount / this.publicationPageSize)); + } + + private clampPublicationPage(page: number, totalPages: number): number { + return this.clampPage(page, totalPages); + } + + private clampPage(page: number, totalPages: number): number { + return Math.min(Math.max(page, 1), totalPages); + } + + private parsePageParam(value: string | null): number { + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < 1) { + return 1; + } + return parsed; + } } -- 2.56.1 From e898f15583c546179afbb272ea502d77e3e59e9c Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 3 Jun 2026 09:39:25 +0200 Subject: [PATCH 10/13] =?UTF-8?q?feat:=20Personensuche=20in=20der=20Naviga?= =?UTF-8?q?tionsleiste=20hinzugef=C3=BCgt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../person-funding.component.html | 21 +++++----- .../person-funding.component.ts | 12 +++++- .../ui/app-layout/app-layout.component.html | 34 +++++++++++---- .../ui/app-layout/app-layout.component.scss | 41 +++++++++++++++++++ .../ui/app-layout/app-layout.component.ts | 39 ++++++++++++++++-- 5 files changed, 123 insertions(+), 24 deletions(-) diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index 8469b157..a7492f4a 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -5,19 +5,18 @@ } @else if (funders.length === 0) {

Keine Förderungen gefunden.

} @else { -
- Einzigartige Publikationen: - {{ getUniquePublicationCount() }} -
-
-
- Förderer: - {{ filteredFunders.length }} -
-
-
+
+
+ {{ getUniquePublicationCount() }} + Einzigartige Publikationen +
+
+ {{ filteredFunders.length }} + Förderer +
+
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 76861ca0..9097ac9c 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -25,9 +25,16 @@ export class PersonFundingComponent implements OnInit { error = false; ngOnInit(): void { - const authorId = this.route.parent?.snapshot.paramMap.get('id') ?? ''; + this.route.parent?.paramMap.subscribe(params => { + const authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); + this.funders = []; + this.filteredFunders = []; + this.selectedFunder = null; + this.loading = true; + this.error = false; + if (this.isValidFilter(filterFromUrl)) { this.activeFilter = filterFromUrl; } @@ -46,7 +53,8 @@ export class PersonFundingComponent implements OnInit { } }); } - } + }); +} selectFunder(funder: any): void { this.selectedFunder = funder; 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 8f21ec4a..0467e59e 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 @@ -35,13 +35,33 @@
- +
+ + @if (showResults) { +
+ @if (searchResults.length === 0) { +
Keine Ergebnisse gefunden.
+ } + @for (person of searchResults; track person.id) { +
+ {{ person.name }} + @if (person.affiliations?.length > 0) { + {{ person.affiliations[0].institution }} + } +
+ } +
+ } +
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 83fb51a9..a0f0070b 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 @@ -144,3 +144,44 @@ mat-toolbar.main { min-height: calc(100svh - 124px); } } +.search-wrapper { + position: relative; + width: 100%; +} + +.search-results { + position: absolute; + top: 100%; + left: 0; + right: 0; + background: white; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + box-shadow: 0 4px 12px rgba(0,0,0,0.1); + z-index: 1000; + max-height: 300px; + overflow-y: auto; +} + +.search-result-item { + padding: 10px 16px; + cursor: pointer; + display: flex; + flex-direction: column; + border-bottom: 1px solid var(--sg-border); + + &:hover { + background: var(--sg-surface-muted); + } + + .result-name { + font-weight: 500; + font-size: 14px; + color: var(--sg-text); + } + + .result-affiliation { + font-size: 12px; + color: var(--sg-text-muted); + } +} 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 54911500..869a8d50 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 @@ -9,10 +9,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 { FormsModule } from '@angular/forms'; +import { PersonsOpenApiService } from '../../../api'; @Component({ selector: 'app-layout', - imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, RouterLink, AppMenuComponent, MatTooltipModule], + imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, RouterLink, AppMenuComponent, MatTooltipModule, FormsModule], templateUrl: './app-layout.component.html', styleUrl: './app-layout.component.scss', standalone: true, @@ -27,9 +29,13 @@ export class AppLayoutComponent implements OnInit, OnDestroy { mediaQueryListener: () => void; sideNavOpen = false; + searchQuery: string = ''; +searchResults: any[] = []; +showResults: boolean = false; - constructor(public credentialService: CredentialService, public router: Router, - public changeDetector: ChangeDetectorRef, media: MediaMatcher) { + constructor(public credentialService: CredentialService, public router: Router, + public changeDetector: ChangeDetectorRef, media: MediaMatcher, + private personsApi: PersonsOpenApiService) { this.mediaQuery = media.matchMedia('(max-width: 600px)'); this.mediaQueryListener = () => { this.sideNavOpen = !this.mediaQuery.matches @@ -42,6 +48,31 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.drawer.toggle(); } } + onSearch(event: KeyboardEvent): void { + if (event.key === 'Enter' && this.searchQuery.trim()) { + this.personsApi.searchPersons(undefined, this.searchQuery.trim()).subscribe({ + next: (result) => { + this.searchResults = result.persons ?? []; + this.showResults = true; + }, + error: () => { + this.searchResults = []; + this.showResults = false; + } + }); + } +} + +goToPerson(personId: string): void { + this.showResults = false; + this.searchQuery = ''; + const shortId = personId.replace('https://openalex.org/', ''); + this.router.navigate(['/person', shortId, 'funding']); +} + +hideResults(): void { + setTimeout(() => this.showResults = false, 200); +} ngOnInit() { this.sideNavOpen = !this.mediaQuery.matches; @@ -50,7 +81,7 @@ export class AppLayoutComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.mediaQuery.removeEventListener('change', this.mediaQueryListener); - } + } logout() { this.credentialService.logoutAcount(); -- 2.56.1 From 8df18efd8fed29e111e2bff88795711659d56a65 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 3 Jun 2026 10:46:24 +0200 Subject: [PATCH 11/13] =?UTF-8?q?Personensuche=20in=20der=20Navigationslei?= =?UTF-8?q?ste=20hinzugef=C3=BCgt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webapp/src/app/shared/ui/app-layout/app-layout.component.html | 2 +- webapp/src/app/shared/ui/app-layout/app-layout.component.scss | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) 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 0467e59e..2cd812bb 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 @@ -36,7 +36,7 @@
-