diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py index 5b848c80..637fee1b 100644 --- a/service/src/main/inse/funders/elastic_search_client.py +++ b/service/src/main/inse/funders/elastic_search_client.py @@ -34,21 +34,32 @@ class FundedPublicationsSearchClient: short_id = author_id.strip().removeprefix("https://openalex.org/") return f"https://openalex.org/{short_id}" - def funded_publications_by_author_query( + def publications_by_author_query( self, author_id: str, page: int, size: int, ) -> dict[str, Any]: + """ + Fetch all works for an author from the OpenAlex works Elasticsearch index. + Funder filtering is done in application logic (not in the ES query). + """ indexed_author_id = self.indexed_author_id(author_id) return { "from": (page - 1) * size, "size": size, + "track_total_hits": True, "_source": [ "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", @@ -73,38 +84,19 @@ class FundedPublicationsSearchClient: }, }, }, - { - "bool": { - "should": [ - { - "nested": { - "path": "funders", - "query": { - "exists": { - "field": "funders.id", - }, - }, - }, - }, - { - "nested": { - "path": "awards", - "query": { - "exists": { - "field": "awards.funder_id", - }, - }, - }, - }, - ], - "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) + 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.") diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index b7383ecf..0cdfa83b 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -28,21 +28,22 @@ async def get_publications_by_author_id( 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) + total_works, all_hits = await _fetch_all_author_work_hits(search_client, author_id) + 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=total, - results_count=len(hits), - results=hits, + total_works=total_works, + total=len(funded_hits), + results_count=len(funded_hits[start:end]), + results=funded_hits[start:end], ) @@ -51,31 +52,19 @@ async def get_funders_by_author_id( 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, + _, all_hits = await _fetch_all_author_work_hits(search_client, author_id) + _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, ) - 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(), @@ -91,6 +80,33 @@ async def get_funders_by_author_id( ) +async def _fetch_all_author_work_hits( + search_client: FundedPublicationsSearchClient, + author_id: str, + page_size: int = 100, +) -> tuple[int, list[dict]]: + page = 1 + total_works = 0 + all_hits: list[dict] = [] + + while True: + data = await _search_funded_publications( + search_client, + author_id, + page, + page_size, + ) + total_works, hits = _parse_publication_search_response(data) + all_hits.extend(hits) + + if not hits or page * page_size >= total_works: + break + + page += 1 + + return total_works, all_hits + + async def _search_funded_publications( search_client: FundedPublicationsSearchClient, author_id: str, @@ -98,7 +114,7 @@ async def _search_funded_publications( page_size: int, ) -> dict: try: - payload = search_client.funded_publications_by_author_query( + payload = search_client.publications_by_author_query( author_id, page, page_size, @@ -125,7 +141,11 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: if isinstance(total, dict): total = total.get("value", 0) - return total, hits.get("hits", []) + 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: @@ -152,6 +172,44 @@ def _get_author_position_in_publication(publication: dict, author_id: str) -> st 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, @@ -159,7 +217,11 @@ def _collect_funders_from_publications( ) -> 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() @@ -195,9 +257,12 @@ def _collect_funders_from_publications( "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 diff --git a/service/src/main/inse/funders/model.py b/service/src/main/inse/funders/model.py index d7b90fa1..d2207541 100644 --- a/service/src/main/inse/funders/model.py +++ b/service/src/main/inse/funders/model.py @@ -7,6 +7,7 @@ class PublicationsByAuthorResponse(BaseModel): author_id: str page: int page_size: int + total_works: int total: int results_count: int results: list[dict[str, Any]] @@ -32,10 +33,11 @@ class FunderByAuthor(BaseModel): 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] \ No newline at end of file + funders: list[FunderByAuthor] diff --git a/service/src/main/inse/funders/service.py b/service/src/main/inse/funders/service.py index 9ead124d..a99b661e 100644 --- a/service/src/main/inse/funders/service.py +++ b/service/src/main/inse/funders/service.py @@ -24,7 +24,7 @@ router = APIRouter(prefix="/authors", tags=["Funding"]) 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, + page_size: Annotated[int, Query(ge=1, le=1000)] = 200, ): return await logic.get_publications_by_author_id(author_id, page, page_size) diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py index a49a7559..d5a116d8 100644 --- a/service/src/main/inse/funders/test_logic.py +++ b/service/src/main/inse/funders/test_logic.py @@ -21,9 +21,13 @@ def _funded_publication_hit( 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": { @@ -69,6 +73,7 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc 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", @@ -111,6 +116,8 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc 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 @@ -157,7 +164,81 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m @pytest.mark.anyio -async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(): +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", (), {"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("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", (), {"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("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", (), {"persons": []})(), + ) client = FundedPublicationsSearchClient(api_key="") with pytest.raises(HTTPException) as exc: 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 138a74ff..ff01f61e 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -7,15 +7,15 @@ } @else {
-
- {{ getUniquePublicationCount() }} - Einzigartige Publikationen +

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

+

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

-
- {{ filteredFunders.length }} - Förderer -
-
@@ -92,7 +92,7 @@ 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 e7514cd5..10ff3081 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.ts +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -17,7 +17,6 @@ export class PersonFundingComponent implements OnInit { private initialSelectedFunderKey: string | null = null; private initialPublicationPage = 1; private initialFunderListPage = 1; - private publicationUrlCache = new Map(); funders: any[] = []; filteredFunders: any[] = []; @@ -198,9 +197,9 @@ export class PersonFundingComponent implements OnInit { this.updateQueryParams(); } - async openPublication(event: MouseEvent, publicationId: string): Promise { + openPublication(event: MouseEvent, publicationId: string): void { event.preventDefault(); - const url = await this.resolvePreferredPublicationUrl(publicationId); + const url = this.getPublicationUrl(publicationId); window.open(url, '_blank', 'noopener'); } @@ -234,42 +233,8 @@ 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; - } + getPublicationUrl(publicationId: string): string { + return this.selectedFunder?.publication_urls?.[publicationId] ?? publicationId; } private getPublicationPageCountForFunder(funder: any): number {