ts-86-get-funding-by-author-clean #107

Merged
taguesokoudjou merged 16 commits from ts-86-get-funding-by-author-clean into dev 2026-06-05 12:53:59 +02:00
14 changed files with 1487 additions and 2 deletions
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Funders domain package.
"""
@@ -0,0 +1,160 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for funded-publication searches in the OpenAlex works index.
"""
from typing import Any
import httpx
from .. import config
class MissingApiKeyError(Exception):
pass
class FundedPublicationsSearchClient:
def __init__(
self,
base_url: str | None = None,
index: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
@staticmethod
def indexed_author_id(author_id: str) -> str:
short_id = author_id.strip().removeprefix("https://openalex.org/")
return f"https://openalex.org/{short_id}"
def publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
*,
funded_only: bool = False,
) -> dict[str, Any]:
indexed_author_id = self.indexed_author_id(author_id)
must: list[dict[str, Any]] = [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": indexed_author_id,
},
},
},
},
]
if funded_only:
must.append(self._has_funding_clause())
return {
"from": (page - 1) * size,
"size": size,
"track_total_hits": True,
"_source": self._publication_source_fields(),
"query": {
"bool": {
"must": must,
},
},
}
@staticmethod
def _publication_source_fields() -> list[str]:
return [
"id",
"doi",
"title",
"display_name",
"publication_year",
"primary_location.landing_page_url",
"primary_location.pdf_url",
"best_oa_location.landing_page_url",
"best_oa_location.pdf_url",
"open_access.oa_url",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"funders.id",
"funders.display_name",
"funders.ror",
"awards.id",
"awards.funder_id",
"awards.funder_display_name",
"awards.funder_award_id",
]
@staticmethod
def _has_funding_clause() -> dict[str, Any]:
return {
"bool": {
"should": [
{
"nested": {
"path": "funders",
"query": {
"bool": {
"should": [
{"exists": {"field": "funders.id"}},
{"exists": {"field": "funders.display_name"}},
],
"minimum_should_match": 1,
},
},
},
},
{
"nested": {
"path": "awards",
"query": {
"bool": {
"should": [
{"exists": {"field": "awards.funder_id"}},
{"exists": {"field": "awards.funder_display_name"}},
],
"minimum_should_match": 1,
},
},
},
},
],
"minimum_should_match": 1,
},
}
def funded_publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
) -> dict[str, Any]:
return self.publications_by_author_query(author_id, page, size, funded_only=True)
async def search(self, payload: dict[str, Any]) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{self.index}/_search",
headers={"Authorization": f"ApiKey {self.api_key}"},
json=payload,
)
response.raise_for_status()
return response.json()
+300
View File
@@ -0,0 +1,300 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for author funding based on publication works.
"""
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from .. import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from .elastic_search_client import MissingApiKeyError
logger = logging.getLogger(__name__)
_VALID_AUTHOR_POSITIONS = frozenset({"first", "middle", "last"})
_ES_PAGE_SIZE = 500
_MAX_ES_PAGES = 100
async def get_publications_by_author_id(
author_id: str,
page: int = 1,
page_size: int = 20,
client: FundedPublicationsSearchClient | None = None,
) -> model.PublicationsByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
total_works, all_hits = await _fetch_all_author_work_hits(
search_client,
author_id,
funded_only=True,
)
funded_hits = [
hit for hit in all_hits
if _publication_has_funder_data(hit.get("_source", {}))
]
start = (page - 1) * page_size
end = start + page_size
return model.PublicationsByAuthorResponse(
author_id=FundedPublicationsSearchClient.indexed_author_id(author_id),
page=page,
page_size=page_size,
total_works=total_works,
total=len(funded_hits),
results_count=len(funded_hits[start:end]),
results=funded_hits[start:end],
)
async def get_funders_by_author_id(
author_id: str,
client: FundedPublicationsSearchClient | None = None,
) -> model.FundersByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
funder_counts: dict[str, dict[str, Any]] = {}
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
author_name = _get_author_name(author_id)
try:
_, all_hits = await _fetch_all_author_work_hits(
search_client,
author_id,
funded_only=True,
)
_collect_funders_from_publications(all_hits, author_id, funder_counts)
if not funder_counts:
logger.info(
"No funders aggregated for author %s from Elasticsearch.",
normalized_author_id,
)
funders = sorted(
funder_counts.values(),
key=lambda entry: entry["publication_count"],
reverse=True,
)
return model.FundersByAuthorResponse(
author_id=normalized_author_id,
author_name=author_name,
funder_count=len(funders),
funders=[model.FunderByAuthor.model_validate(entry) for entry in funders],
)
except ValidationError as exc:
logger.exception("Funders response could not be validated for author %s.", author_id)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Funders response could not be parsed.",
) from exc
async def _fetch_all_author_work_hits(
search_client: FundedPublicationsSearchClient,
author_id: str,
*,
funded_only: bool = False,
page_size: int = _ES_PAGE_SIZE,
) -> tuple[int, list[dict]]:
page = 1
total_works = 0
all_hits: list[dict] = []
while page <= _MAX_ES_PAGES:
data = await _search_funded_publications(
search_client,
author_id,
page,
page_size,
funded_only=funded_only,
)
total_works, hits = _parse_publication_search_response(data)
all_hits.extend(hits)
if not hits or page * page_size >= total_works:
break
page += 1
if page > _MAX_ES_PAGES and page * page_size < total_works:
logger.warning(
"Stopped pagination for author %s at %s pages (total works: %s).",
author_id,
_MAX_ES_PAGES,
total_works,
)
return total_works, all_hits
async def _search_funded_publications(
search_client: FundedPublicationsSearchClient,
author_id: str,
page: int,
page_size: int,
*,
funded_only: bool = False,
) -> dict:
try:
payload = search_client.publications_by_author_query(
author_id,
page,
page_size,
funded_only=funded_only,
)
return await search_client.search(payload)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="OpenAlex works search is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex works search request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
hits = data.get("hits", {})
total = hits.get("total", 0)
if isinstance(total, dict):
total = total.get("value", 0)
results = hits.get("hits", [])
for hit in results:
_add_publication_url(hit.get("_source", {}))
return total, results
def _get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
search_result = person_logic.search_persons(author_id=short_author_id)
if not search_result.results:
return None
return search_result.results[0].display_name
def _get_author_position_in_publication(publication: dict, author_id: str) -> str:
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
for authorship in publication.get("authorships", []):
author = authorship.get("author", {})
if author.get("id") == normalized_author_id:
position = authorship.get("author_position", "unknown")
if position in _VALID_AUTHOR_POSITIONS:
return position
return "unknown"
return "unknown"
def _publication_has_funder_data(publication: dict) -> bool:
for funder in publication.get("funders", []):
if funder.get("id") or funder.get("display_name"):
return True
for award in publication.get("awards", []):
if award.get("funder_id") or award.get("funder_display_name"):
return True
return False
def _add_publication_url(publication: dict) -> None:
publication["publication_url"] = _resolve_publication_url(publication)
def _resolve_publication_url(publication: dict) -> str | None:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
open_access = publication.get("open_access") or {}
for url in (
primary_location.get("pdf_url"),
best_oa_location.get("pdf_url"),
primary_location.get("landing_page_url"),
best_oa_location.get("landing_page_url"),
open_access.get("oa_url"),
):
if url:
return url
doi = publication.get("doi")
if doi:
return doi if doi.startswith("http") else f"https://doi.org/{doi}"
return publication.get("id")
def _collect_funders_from_publications(
results: list[dict],
author_id: str,
funder_counts: dict[str, dict[str, Any]],
) -> None:
for hit in results:
publication = hit.get("_source", {})
if not _publication_has_funder_data(publication):
continue
publication_id = publication.get("id")
publication_url = publication.get("publication_url") or _resolve_publication_url(publication)
author_position = _get_author_position_in_publication(publication, author_id)
publication_funders: set[tuple[str, str | None, str | None]] = set()
for funder in publication.get("funders", []):
funder_id = funder.get("id")
funder_name = funder.get("display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for award in publication.get("awards", []):
funder_id = award.get("funder_id")
funder_name = award.get("funder_display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for key, funder_id, funder_name in publication_funders:
if key not in funder_counts:
funder_counts[key] = {
"funder_id": funder_id,
"funder_name": funder_name,
"publication_count": 0,
"author_position_count": {
"first": 0,
"middle": 0,
"last": 0,
"unknown": 0,
},
"publication_ids": {
"first": [],
"middle": [],
"last": [],
"unknown": [],
},
"publication_urls": {},
}
entry = funder_counts[key]
entry["publication_count"] += 1
entry["author_position_count"][author_position] += 1
entry["publication_ids"][author_position].append(publication_id)
if publication_id and publication_url:
entry["publication_urls"][publication_id] = publication_url
+43
View File
@@ -0,0 +1,43 @@
from typing import Any
from pydantic import BaseModel
class PublicationsByAuthorResponse(BaseModel):
author_id: str
page: int
page_size: int
total_works: int
total: int
results_count: int
results: list[dict[str, Any]]
class PublicationIdsByAuthorPosition(BaseModel):
first: list[str] = []
middle: list[str] = []
last: list[str] = []
unknown: list[str] = []
class AuthorPositionCount(BaseModel):
first: int = 0
middle: int = 0
last: int = 0
unknown: int = 0
class FunderByAuthor(BaseModel):
funder_id: str | None = None
funder_name: str | None = None
publication_count: int
author_position_count: AuthorPositionCount
publication_ids: PublicationIdsByAuthorPosition
publication_urls: dict[str, str] = {}
class FundersByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
funder_count: int
funders: list[FunderByAuthor]
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for author publications and funding.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from . import logic
from . import model
router = APIRouter(prefix="/authors", tags=["Funding"])
@router.get(
"/{author_id}/publications",
operation_id="getPublicationsByAuthor",
response_model=model.PublicationsByAuthorResponse,
summary="Get funded publications by author.",
)
async def get_publications_by_author(
author_id: str,
page: Annotated[int, Query(ge=1)] = 1,
page_size: Annotated[int, Query(ge=1, le=1000)] = 200,
):
return await logic.get_publications_by_author_id(author_id, page, page_size)
@router.get(
"/{author_id}/funders",
operation_id="getFundersByAuthor",
response_model=model.FundersByAuthorResponse,
summary="Get funding organizations by author.",
)
async def get_funders_by_author(author_id: str):
return await logic.get_funders_by_author_id(author_id)
+263
View File
@@ -0,0 +1,263 @@
import json
import httpx
import pytest
from fastapi import HTTPException
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def _funded_publication_hit(
work_id: str,
*,
funder_id: str | None = "https://openalex.org/F123",
funder_name: str | None = "Example Funder",
author_position: str = "first",
award_funder_id: str | None = None,
award_funder_name: str | None = None,
pdf_url: str | None = None,
) -> dict:
source: dict = {
"id": work_id,
"primary_location": {
"pdf_url": pdf_url,
},
"authorships": [
{
"author": {
"id": "https://openalex.org/A5023888391",
"display_name": "Example Author",
},
"author_position": author_position,
}
],
"funders": [],
"awards": [],
}
if funder_id or funder_name:
source["funders"].append(
{
"id": funder_id,
"display_name": funder_name,
}
)
if award_funder_id or award_funder_name:
source["awards"].append(
{
"funder_id": award_funder_id,
"funder_display_name": award_funder_name,
}
)
return {"_source": source}
@pytest.mark.anyio
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
assert payload["from"] == 0
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Funder A",
author_position="first",
pdf_url="https://example.org/w1.pdf",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
award_funder_id="https://openalex.org/F123",
award_funder_name="Funder A",
author_position="last",
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type(
"Result",
(),
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
)(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert response.author_id == "https://openalex.org/A5023888391"
assert response.author_name == "Example Author"
assert response.funder_count == 1
assert response.funders[0].funder_id == "https://openalex.org/F123"
assert response.funders[0].funder_name == "Funder A"
assert response.funders[0].publication_count == 2
assert response.funders[0].author_position_count.first == 1
assert response.funders[0].author_position_count.last == 1
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
@pytest.mark.anyio
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
requested_pages: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
size = payload["size"]
offset = payload["from"]
page = offset // size + 1
requested_pages.append(page)
total = size + 1
if page == 1:
hits = [
_funded_publication_hit(
f"https://openalex.org/W{i}",
funder_id=f"https://openalex.org/F{i}",
funder_name=f"Funder {i}",
)
for i in range(1, size + 1)
]
else:
hits = [
_funded_publication_hit(
f"https://openalex.org/W{total}",
funder_id=f"https://openalex.org/F{total}",
funder_name=f"Funder {total}",
)
]
return httpx.Response(
200,
json={
"hits": {
"total": {"value": total},
"hits": hits,
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert requested_pages == [1, 2]
assert response.funder_count > 1
funder_names = {funder.funder_name for funder in response.funders}
assert "Funder 1" in funder_names
@pytest.mark.anyio
async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Bundesministerium",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5093075883", client=client)
assert response.funder_count == 1
assert response.funders[0].funder_name == "Bundesministerium"
assert response.funders[0].publication_count == 1
@pytest.mark.anyio
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={"hits": {"total": {"value": 0}, "hits": []}},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5093075883", client=client)
assert response.funder_count == 0
assert response.funders == []
@pytest.mark.anyio
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(api_key="")
with pytest.raises(HTTPException) as exc:
await logic.get_funders_by_author_id("A5023888391", client=client)
assert exc.value.status_code == 503
+3
View File
@@ -28,6 +28,8 @@ from . import database
from . import security
from . import util
from .works import service as works_service
from .funders import service as funders_service
from inse.models.authors_list_response import AuthorsListResponse
@@ -44,6 +46,7 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
)
router.include_router(funders_service.router)
# @app.get("/", include_in_schema=False)
# async def show_api():
+24 -2
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* 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';
@@ -442,4 +442,26 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
);
}
public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
let localVarPath = `/api/inse-service/authors/${encodeURIComponent(authorId)}/funders`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: 'json',
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}
+7
View File
@@ -80,6 +80,13 @@ export const routes: Routes = [
(mod) => mod.PersonPublicationsComponent,
),
},
{
path: 'funding',
loadComponent: () =>
import('./modules/person-funding/person-funding.component').then(
(mod) => mod.PersonFundingComponent,
),
},
],
},
{
@@ -0,0 +1,119 @@
@if (loading) {
<p class="message">Lade Förderungen...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Förderungen.</p>
} @else if (funders.length === 0) {
<p class="message">Keine Förderungen gefunden.</p>
} @else {
<div class="funding-container">
<div class="funding-summary">
<p class="summary-line">
<span class="summary-value">{{ getUniquePublicationCount() }}</span>
<span class="summary-label"> Einzigartige Publikationen</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ filteredFunders.length }}</span>
<span class="summary-label"> Förderer</span>
</p>
</div>
<!-- Filter Buttons -->
<div class="filter-bar">
<span>Filter nach Position:</span>
<button [class.active]="activeFilter === 'all'" (click)="setFilter('all')">Alle</button>
<button [class.active]="activeFilter === 'first'" (click)="setFilter('first')">Erstautor</button>
<button [class.active]="activeFilter === 'middle'" (click)="setFilter('middle')">Mitautor</button>
<button [class.active]="activeFilter === 'last'" (click)="setFilter('last')">Letztautor</button>
</div>
<div class="funding-content">
<!-- Linke Seite: Tabelle -->
<div class="funding-list">
<table>
<thead>
<tr>
<th>Förderer</th>
<th>Publikationen</th>
</tr>
</thead>
<tbody>
@for (funder of getPagedFunders(); track funder.funder_id) {
<tr
[class.selected]="selectedFunder === funder"
(click)="selectFunder(funder)"
>
<td class="funder-name">{{ funder.funder_name }}</td>
<td>{{ getPublicationCount(funder) }}</td>
</tr>
}
</tbody>
</table>
@if (hasFunderListPagination()) {
<div class="publication-pagination">
<button [disabled]="selectedFunderListPage === 1" (click)="setFunderListPage(selectedFunderListPage - 1)">
Zurück
</button>
<span>Seite {{ selectedFunderListPage }} von {{ getFunderListPageCount() }}</span>
<button [disabled]="selectedFunderListPage === getFunderListPageCount()" (click)="setFunderListPage(selectedFunderListPage + 1)">
Weiter
</button>
</div>
}
</div>
<!-- Rechte Seite: Details -->
@if (selectedFunder) {
<div class="funding-detail">
<h3>{{ selectedFunder.funder_name }}</h3>
<div class="position-stats">
@if (shouldShowPosition('first')) {
<div class="stat">
<span class="stat-label">Erstautor</span>
<span class="stat-value">{{ selectedFunder.author_position_count.first }}</span>
</div>
}
@if (shouldShowPosition('middle')) {
<div class="stat">
<span class="stat-label">Mitautor</span>
<span class="stat-value">{{ selectedFunder.author_position_count.middle }}</span>
</div>
}
@if (shouldShowPosition('last')) {
<div class="stat">
<span class="stat-label">Letztautor</span>
<span class="stat-value">{{ selectedFunder.author_position_count.last }}</span>
</div>
}
</div>
<h4>Publikationen</h4>
<ul class="publication-list">
@for (id of getSelectedPublicationIdsPage(); track id) {
<li>
<a [href]="getPublicationUrl(id)" target="_blank" rel="noopener" (click)="openPublication($event, id)">{{ id }}</a>
</li>
}
</ul>
@if (hasPublicationPagination()) {
<div class="publication-pagination">
<button [disabled]="selectedPublicationPage === 1" (click)="setPublicationPage(selectedPublicationPage - 1)">
Zurück
</button>
<span>Seite {{ selectedPublicationPage }} von {{ getSelectedPublicationPageCount() }}</span>
<button [disabled]="selectedPublicationPage === getSelectedPublicationPageCount()" (click)="setPublicationPage(selectedPublicationPage + 1)">
Weiter
</button>
</div>
}
</div>
} @else {
<div class="funding-detail empty">
<p>Klicke auf einen Förderer für Details.</p>
</div>
}
</div>
</div>
}
@@ -0,0 +1,221 @@
.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:
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);
}
}
}
.funding-content {
display: flex;
gap: 24px;
align-items: flex-start;
}
.funding-list {
flex: 1;
table {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #333;
}
tr {
cursor: pointer;
transition: background 0.15s;
&:hover {
background: #f5f5f5;
}
&.selected {
background: #f0f0f0;
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
}
.funder-name {
color: #333;
font-weight: 500;
}
}
}
.funding-detail {
width: 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: #333;
}
}
}
.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: #2563eb;
text-decoration: none;
word-break: break-all;
&:hover {
color: #1d4ed8;
text-decoration: underline;
}
}
}
}
.publication-pagination {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
button {
padding: 4px 10px;
border: 1px solid #d0d0d0;
border-radius: 6px;
background: white;
cursor: pointer;
font-size: 12px;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
span {
font-size: 12px;
color: #666;
}
}
.funding-summary {
margin-bottom: 16px;
.summary-line {
margin: 0 0 4px 0;
font-size: 14px;
color: #333;
}
.summary-label {
color: #333;
}
.summary-value {
font-weight: 600;
color: #333;
}
}
@@ -0,0 +1,260 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { PersonsService } from '../../api';
@Component({
selector: 'app-person-funding',
imports: [CommonModule],
templateUrl: './person-funding.component.html',
styleUrl: './person-funding.component.scss',
})
export class PersonFundingComponent implements OnInit {
private route = inject(ActivatedRoute);
private router = inject(Router);
private personsApi = inject(PersonsService);
private initialSelectedFunderKey: string | null = null;
private initialPublicationPage = 1;
private initialFunderListPage = 1;
funders: any[] = [];
filteredFunders: any[] = [];
selectedFunder: any = null;
selectedFunderListPage = 1;
selectedPublicationPage = 1;
readonly funderListPageSize = 10;
readonly publicationPageSize = 10;
activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all';
loading = true;
error = false;
ngOnInit(): void {
this.route.parent?.paramMap.subscribe(params => {
const authorId = params.get('id') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder');
this.initialPublicationPage = this.parsePageParam(
this.route.snapshot.queryParamMap.get('publicationPage') ?? this.route.snapshot.queryParamMap.get('page')
);
this.initialFunderListPage = this.parsePageParam(this.route.snapshot.queryParamMap.get('funderPage'));
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (authorId) {
this.personsApi.getFundersByAuthor(authorId).subscribe({
next: (result: any) => {
this.funders = result.funders ?? [];
this.applyFilter();
this.selectedFunderListPage = this.clampPage(this.initialFunderListPage, this.getFunderListPageCount());
this.restoreSelectedFunderFromUrl();
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
}
});
}
});
}
selectFunder(funder: any): void {
this.selectedFunder = funder;
this.selectedPublicationPage = 1;
this.updateQueryParams();
}
setFilter(filter: 'all' | 'first' | 'middle' | 'last'): void {
this.activeFilter = filter;
this.applyFilter();
this.updateQueryParams();
}
private applyFilter(): void {
this.selectedFunder = null;
this.selectedFunderListPage = 1;
this.selectedPublicationPage = 1;
if (this.activeFilter === 'all') {
this.filteredFunders = this.funders;
} else {
this.filteredFunders = this.funders.filter(
f => f.author_position_count[this.activeFilter] > 0
);
}
}
private restoreSelectedFunderFromUrl(): void {
if (!this.initialSelectedFunderKey) {
return;
}
const matchedFunder = this.filteredFunders.find(
(funder: any) => this.getFunderKey(funder) === this.initialSelectedFunderKey
);
if (matchedFunder) {
this.selectedFunder = matchedFunder;
const matchedIndex = this.filteredFunders.findIndex(
(funder: any) => this.getFunderKey(funder) === this.getFunderKey(matchedFunder)
);
if (matchedIndex >= 0) {
this.selectedFunderListPage = Math.floor(matchedIndex / this.funderListPageSize) + 1;
}
this.selectedPublicationPage = this.clampPublicationPage(
this.initialPublicationPage,
this.getPublicationPageCountForFunder(matchedFunder),
);
this.updateQueryParams();
} else {
this.updateQueryParams();
}
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null,
publicationPage: this.selectedFunder ? this.selectedPublicationPage : null,
funderPage: this.selectedFunderListPage
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
private getFunderKey(funder: any): string {
return funder.funder_id ?? funder.funder_name ?? '';
}
private isValidFilter(value: string | null): value is 'all' | 'first' | 'middle' | 'last' {
return value === 'all' || value === 'first' || value === 'middle' || value === 'last';
}
getPublicationCount(funder: any): number {
if (this.activeFilter === 'all') {
return funder.publication_count ?? 0;
}
return funder.author_position_count?.[this.activeFilter] ?? 0;
}
getPublicationIds(funder: any): string[] {
if (this.activeFilter === 'all') {
return [
...funder.publication_ids.first,
...funder.publication_ids.middle,
...funder.publication_ids.last,
...funder.publication_ids.unknown
];
}
return funder.publication_ids[this.activeFilter] ?? [];
}
getPagedFunders(): any[] {
const startIndex = (this.selectedFunderListPage - 1) * this.funderListPageSize;
return this.filteredFunders.slice(startIndex, startIndex + this.funderListPageSize);
}
hasFunderListPagination(): boolean {
return this.getFunderListPageCount() > 1;
}
getFunderListPageCount(): number {
return Math.max(1, Math.ceil(this.filteredFunders.length / this.funderListPageSize));
}
setFunderListPage(page: number): void {
this.selectedFunderListPage = this.clampPage(page, this.getFunderListPageCount());
this.updateQueryParams();
}
getSelectedPublicationIdsPage(): string[] {
if (!this.selectedFunder) {
return [];
}
const allPublicationIds = this.getPublicationIds(this.selectedFunder);
const startIndex = (this.selectedPublicationPage - 1) * this.publicationPageSize;
return allPublicationIds.slice(startIndex, startIndex + this.publicationPageSize);
}
hasPublicationPagination(): boolean {
return this.getSelectedPublicationPageCount() > 1;
}
getSelectedPublicationPageCount(): number {
if (!this.selectedFunder) {
return 1;
}
return this.getPublicationPageCountForFunder(this.selectedFunder);
}
setPublicationPage(page: number): void {
const totalPages = this.getSelectedPublicationPageCount();
this.selectedPublicationPage = this.clampPublicationPage(page, totalPages);
this.updateQueryParams();
}
openPublication(event: MouseEvent, publicationId: string): void {
event.preventDefault();
const url = this.getPublicationUrl(publicationId);
window.open(url, '_blank', 'noopener');
}
getPositionLabel(position: string): string {
const labels: Record<string, string> = {
first: 'Erstautor',
middle: 'Mitautor',
last: 'Letztautor',
unknown: 'Unbekannt'
};
return labels[position] ?? position;
}
shouldShowPosition(position: 'first' | 'middle' | 'last'): boolean {
return this.activeFilter === 'all' || this.activeFilter === position;
}
getUniquePublicationCount(): number {
const allIds = new Set<string>();
for (const funder of this.funders) {
if (this.activeFilter === 'all') {
for (const ids of Object.values(funder.publication_ids) as string[][]) {
ids.forEach((id: string) => allIds.add(id));
}
} else {
(funder.publication_ids[this.activeFilter] ?? []).forEach((id: string) =>
allIds.add(id),
);
}
}
return allIds.size;
}
getPublicationUrl(publicationId: string): string {
return this.selectedFunder?.publication_urls?.[publicationId] ?? publicationId;
}
private getPublicationPageCountForFunder(funder: any): number {
const publicationCount = this.getPublicationIds(funder).length;
return Math.max(1, Math.ceil(publicationCount / this.publicationPageSize));
}
private clampPublicationPage(page: number, totalPages: number): number {
return this.clampPage(page, totalPages);
}
private clampPage(page: number, totalPages: number): number {
return Math.min(Math.max(page, 1), totalPages);
}
private parsePageParam(value: string | null): number {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1) {
return 1;
}
return parsed;
}
}
@@ -123,6 +123,7 @@ readonly personBio = toSignal(
{ label: 'Publikationen', path: 'publications', disabled: false },
{ label: 'Netzwerk', path: 'network', disabled: false },
{ label: 'Gründungen', path: 'foundings', disabled: true },
{ label: 'Förderungen', path: 'funding', disabled: false },
];
private getId(key: string): string | null {
@@ -144,3 +144,45 @@ mat-toolbar.main {
min-height: calc(100svh - 124px);
}
}
.search-wrapper {
position: relative;
width: 100%;
}
.search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: white;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
z-index: 1000;
max-height: 300px;
overflow-y: auto;
}
.search-result-item {
padding: 10px 16px;
cursor: pointer;
display: flex;
flex-direction: column;
border-bottom: 1px solid var(--sg-border);
&:hover {
background: var(--sg-surface-muted);
}
.result-name {
font-weight: 500;
font-size: 14px;
color: var(--sg-text);
}
.result-affiliation {
font-size: 12px;
color: var(--sg-text-muted);
}
}