From bb791138cd1af3f609208c5c7eaad094d364815b Mon Sep 17 00:00:00 2001
From: Farajollahi
Date: Tue, 4 Aug 2026 14:41:26 +0200
Subject: [PATCH 01/19] fix news bug
---
service/src/main/inse/dashboard/service.py | 43 +++++++++++++++++--
.../src/main/inse/dashboard/test_service.py | 42 ++++++++++++++++++
2 files changed, 82 insertions(+), 3 deletions(-)
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index 4f1fe83d..7351245f 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -1214,7 +1214,11 @@ async def get_top_authors(
news = await _safe_top_authors(
"news",
- _top_news_authors(authors),
+ _top_news_authors(
+ authors,
+ from_year=period[0],
+ to_year=period[1],
+ ),
)
return TopAuthorStatistics(
@@ -2443,16 +2447,49 @@ def _normalize_author_id(value: Any) -> str | None:
return f"https://openalex.org/{short_id}"
-async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
+async def _top_news_authors(
+ authors: list[dict[str, Any]],
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> list[TopAuthor]:
if not authors:
return []
+ period = _dashboard_period(from_year, to_year)
author_names = [author["name"] for author in authors]
+ filters: list[dict[str, Any]] = [
+ {"terms": {"authors.keyword": author_names}}
+ ]
+ if period != (None, None):
+ date_range: dict[str, int] = {}
+ if period[0] is not None:
+ date_range["gte"] = period[0]
+ if period[1] is not None:
+ date_range["lte"] = period[1]
+ news_ids = [
+ str(hit["_id"])
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.AKTUELLES),
+ query={"range": {"date_year": date_range}},
+ source=False,
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ )
+ if hit.get("_id")
+ ]
+ if not news_ids:
+ return []
+ filters.append({"terms": {"news_id.keyword": news_ids}})
+
response = await elasticsearch.search(
index="aktuell_postproc",
body={
"size": 0,
- "query": {"terms": {"authors.keyword": author_names}},
+ "query": (
+ filters[0]
+ if len(filters) == 1
+ else {"bool": {"filter": filters}}
+ ),
"aggs": {
"authors": {
"terms": {
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index 630f8121..c3dae57f 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -12,6 +12,7 @@ from inse.dashboard.service import (
_openalex_work_authors_by_eu_projects,
_get_dfg_project_ids_from_projects_service,
_reconcile_project_status_counts,
+ _top_news_authors,
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_eu_projects,
@@ -50,6 +51,47 @@ def test_project_status_counts_match_authoritative_total():
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
+@pytest.mark.anyio
+async def test_top_news_authors_applies_dashboard_period():
+ response = {
+ "aggregations": {
+ "authors": {
+ "buckets": [{"key": "Ada Example", "doc_count": 3}]
+ }
+ }
+ }
+ async def scan(**kwargs):
+ assert kwargs["index"] == str(ESIndex.AKTUELLES)
+ assert kwargs["query"] == {
+ "range": {"date_year": {"gte": 2020, "lte": 2023}}
+ }
+ yield {"_id": "N1"}
+ yield {"_id": "N2"}
+
+ with patch(
+ "inse.dashboard.service.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as mocked_search, patch(
+ "inse.dashboard.service.elasticsearch.scan",
+ new=scan,
+ ):
+ result = await _top_news_authors(
+ [{"id": "https://openalex.org/A1", "name": "Ada Example"}],
+ from_year=2020,
+ to_year=2023,
+ )
+
+ assert result[0].count == 3
+ assert mocked_search.await_args.kwargs["body"]["query"] == {
+ "bool": {
+ "filter": [
+ {"terms": {"authors.keyword": ["Ada Example"]}},
+ {"terms": {"news_id.keyword": ["N1", "N2"]}},
+ ]
+ }
+ }
+
+
@pytest.mark.anyio
async def test_dfg_topic_project_ids_use_paginated_projects_service():
pages = [
From 98a742f024653960c4584076d539e35d354cb1fa Mon Sep 17 00:00:00 2001
From: spsaefan <117728614+spsaefan@users.noreply.github.com>
Date: Tue, 4 Aug 2026 22:59:36 +0200
Subject: [PATCH 02/19] Match dashboard publications with publications page
---
service/src/main/inse/dashboard/service.py | 116 ++++++-----
.../src/main/inse/dashboard/test_service.py | 194 +++++++++++++++---
2 files changed, 236 insertions(+), 74 deletions(-)
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index 4f1fe83d..babb8b5b 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -30,6 +30,7 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectType,
)
+from inse.works.v2 import service as works_v2_service
from .institute_helper import get_openalex_institution
from .model import (
@@ -241,28 +242,34 @@ async def get_dashboard_publications(
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
- institution = await institutions_v2_service.get_institution_by_id_or_raise(
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- source=["id", "works_count", "counts_by_year"],
+ must = [
+ works_v2_service._institutions_nested_query([normalized_id]),
+ ]
+ if publication_years := _dashboard_publication_years(period):
+ must.append({"terms": {"publication_year": publication_years}})
+ response = await elasticsearch.search(
+ index=ESIndex.OPENALEX_WORKS_WILDCARD,
+ body={
+ "size": 0,
+ "track_total_hits": True,
+ "query": {"bool": {"must": must}},
+ },
+ cluster=ESCluster.NES,
)
- if period == (None, None):
- value = int(institution.works_count or 0)
- else:
- value = sum(
- int(entry.works_count or 0)
- for entry in institution.counts_by_year or []
- if (
- (period[0] is None or int(entry.year or 0) >= period[0])
- and (period[1] is None or int(entry.year or 0) <= period[1])
- )
- )
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
- value=value,
+ value=_total(response),
)
+def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None:
+ from_year, to_year = period
+ if from_year is None and to_year is None:
+ return None
+ return list(range(from_year or 1900, (to_year or 2100) + 1))
+
+
async def get_dashboard_persons(
institution_id: str,
organization_name: str,
@@ -1183,7 +1190,10 @@ async def get_top_authors(
to_year = datetime.now().year
period = _dashboard_period(from_year, to_year)
authors = await _safe_institution_authors(normalized_id)
- works = _top_work_authors(authors, period)
+ works = await _safe_top_authors(
+ "works",
+ _top_work_authors(normalized_id, period),
+ )
projects = await _safe_top_authors(
"projects",
_top_project_authors(
@@ -1595,51 +1605,59 @@ def _short_author_id(value: str) -> str:
return value.replace("https://openalex.org/", "").strip().upper()
-def _top_work_authors(
- authors: list[dict[str, Any]],
+async def _top_work_authors(
+ institution_id: str,
period: DashboardPeriod,
) -> list[TopAuthor]:
- if period != (None, None):
- ranked_authors = sorted(
- (
- {
- **author,
- "selected_works_count": _works_count_in_period(author, period),
- }
- for author in authors
- ),
- key=lambda author: author["selected_works_count"],
- reverse=True,
- )
- else:
- ranked_authors = [
- {**author, "selected_works_count": author["works_count"]}
- for author in authors
- ]
+ must = [works_v2_service._institutions_nested_query([institution_id])]
+ if publication_years := _dashboard_publication_years(period):
+ must.append({"terms": {"publication_year": publication_years}})
+ author_counts: dict[str, int] = defaultdict(int)
+ author_names: dict[str, str] = {}
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.OPENALEX_WORKS_WILDCARD),
+ query={"bool": {"must": must}},
+ source=["id", "authorships.author.id", "authorships.author.display_name"],
+ page_size=1000,
+ cluster=ESCluster.NES,
+ ):
+ hit_author_ids: set[str] = set()
+ for authorship in hit.get("_source", {}).get("authorships", []):
+ author = authorship.get("author") or {}
+ author_id = author.get("id")
+ if not author_id:
+ continue
+ author_id = str(author_id)
+ hit_author_ids.add(author_id)
+ if author.get("display_name"):
+ author_names.setdefault(author_id, str(author["display_name"]))
+ for author_id in hit_author_ids:
+ author_counts[author_id] += 1
+
+ ranked_authors = sorted(
+ (
+ {
+ "id": author_id,
+ "name": author_names.get(author_id, author_id),
+ "count": count,
+ }
+ for author_id, count in author_counts.items()
+ ),
+ key=lambda author: author["count"],
+ reverse=True,
+ )
return [
TopAuthor(
id=_short_author_id(author["id"]),
name=author["name"],
- count=author["selected_works_count"],
+ count=author["count"],
)
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
- if author["selected_works_count"] > 0
+ if author["count"] > 0
]
-def _works_count_in_period(author: dict[str, Any], period: DashboardPeriod) -> int:
- from_year, to_year = period
- return sum(
- int(item.get("works_count", 0) or 0)
- for item in author.get("counts_by_year", [])
- if (
- (from_year is None or int(item.get("year", 0) or 0) >= from_year)
- and (to_year is None or int(item.get("year", 0) or 0) <= to_year)
- )
- )
-
-
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
try:
return await _institution_authors(institution_id)
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index 630f8121..1429e267 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -24,7 +24,6 @@ from inse.dashboard.service import (
get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
-from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
from inse.persons.model import CustomAuthorsListResponse
@@ -188,21 +187,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
}
@pytest.mark.anyio
-async def test_dashboard_publications_uses_institutions_v2_counts():
- institution = Institution(
- id=ORG_INSTITUTION_ID,
- works_count=250,
- counts_by_year=[
- AuthorCountsByYearInner(year=2021, works_count=10),
- AuthorCountsByYearInner(year=2022, works_count=12),
- AuthorCountsByYearInner(year=2023, works_count=14),
- ],
- )
-
+async def test_dashboard_publications_counts_matching_openalex_works():
with patch(
- "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
- new=AsyncMock(return_value=institution),
- ) as mocked_get_institution:
+ "inse.dashboard.service.elasticsearch.search",
+ new=AsyncMock(
+ side_effect=[
+ {"hits": {"total": {"value": 250}}},
+ {"hits": {"total": {"value": 22}}},
+ ]
+ ),
+ ) as mocked_search:
all_time = await get_dashboard_publications(
ORG_INSTITUTION_ID,
"Example Org",
@@ -216,10 +210,33 @@ async def test_dashboard_publications_uses_institutions_v2_counts():
assert all_time.value == 250
assert selected_period.value == 22
- assert mocked_get_institution.await_args_list[0].kwargs == {
- "raw_oa_institution_id": "I123",
- "source": ["id", "works_count", "counts_by_year"],
- }
+ all_time_body = mocked_search.await_args_list[0].kwargs["body"]
+ selected_period_body = mocked_search.await_args_list[1].kwargs["body"]
+ assert mocked_search.await_args_list[0].kwargs["index"] == (
+ ESIndex.OPENALEX_WORKS_WILDCARD
+ )
+ assert all_time_body["track_total_hits"] is True
+ assert all_time_body["query"]["bool"]["must"] == [
+ {
+ "nested": {
+ "path": "authorships",
+ "query": {
+ "nested": {
+ "path": "authorships.institutions",
+ "query": {
+ "terms": {
+ "authorships.institutions.id": [ORG_INSTITUTION_ID]
+ }
+ },
+ }
+ },
+ }
+ }
+ ]
+ assert selected_period_body["query"]["bool"]["must"] == [
+ all_time_body["query"]["bool"]["must"][0],
+ {"terms": {"publication_year": [2021, 2022]}},
+ ]
@pytest.mark.anyio
@@ -438,6 +455,45 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
return {"aggregations": {"people": {"buckets": []}}}
+ scan_calls = []
+
+ async def scan(**kwargs):
+ scan_calls.append(kwargs)
+ yield {
+ "_id": "W1",
+ "_source": {
+ "id": "https://openalex.org/W1",
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ },
+ },
+ {
+ "author": {
+ "id": "https://openalex.org/A2",
+ "display_name": "Grace Example",
+ },
+ },
+ ],
+ },
+ }
+ yield {
+ "_id": "W2",
+ "_source": {
+ "id": "https://openalex.org/W2",
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ },
+ }
+ ],
+ },
+ }
+
async def eu_projects(**kwargs):
if kwargs.get("raw_oa_institution_id"):
return EuCordisProjectSearchPage(
@@ -461,6 +517,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
+ "inse.dashboard.service.elasticsearch.scan",
+ new=scan,
+ ), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
@@ -482,7 +541,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert result.works[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
- "count": 42,
+ "count": 2,
}
assert result.patents[0].model_dump() == {
"id": "A1",
@@ -523,18 +582,43 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
assert "aggs" not in eu_body
- works_calls = [
+ assert len(scan_calls) == 1
+ assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD)
+ assert scan_calls[0]["query"]["bool"]["must"] == [
+ {
+ "nested": {
+ "path": "authorships",
+ "query": {
+ "nested": {
+ "path": "authorships.institutions",
+ "query": {
+ "terms": {
+ "authorships.institutions.id": [ORG_INSTITUTION_ID]
+ }
+ },
+ }
+ },
+ }
+ }
+ ]
+ assert scan_calls[0]["source"] == [
+ "id",
+ "authorships.author.id",
+ "authorships.author.display_name",
+ ]
+
+ eu_work_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == "openalex-works"
]
- assert len(works_calls) == 1
- works_body = works_calls[0].kwargs["body"]
- assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
+ assert len(eu_work_calls) == 1
+ eu_works_body = eu_work_calls[0].kwargs["body"]
+ assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
- assert works_body["_source"] == [
+ assert eu_works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
@@ -813,9 +897,28 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
raise RuntimeError("projects unavailable")
+ async def scan(**kwargs):
+ yield {
+ "_id": "W1",
+ "_source": {
+ "id": "https://openalex.org/W1",
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ }
+ }
+ ],
+ },
+ }
+
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
+ ), patch(
+ "inse.dashboard.service.elasticsearch.scan",
+ new=scan,
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
@@ -879,9 +982,45 @@ async def test_top_authors_can_rank_works_by_last_five_years():
}
return {"aggregations": {"people": {"buckets": []}}}
+ scan_calls = []
+
+ async def scan(**kwargs):
+ scan_calls.append(kwargs)
+ for index in range(16):
+ yield {
+ "_id": f"W-grace-{index}",
+ "_source": {
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A2",
+ "display_name": "Grace Example",
+ }
+ }
+ ]
+ },
+ }
+ for index in range(2):
+ yield {
+ "_id": f"W-ada-{index}",
+ "_source": {
+ "authorships": [
+ {
+ "author": {
+ "id": "https://openalex.org/A1",
+ "display_name": "Ada Example",
+ }
+ }
+ ]
+ },
+ }
+
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
+ ) as mocked_search, patch(
+ "inse.dashboard.service.elasticsearch.scan",
+ new=scan,
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
@@ -909,6 +1048,11 @@ async def test_top_authors_can_rank_works_by_last_five_years():
"count": 2,
}
+ assert len(scan_calls) == 1
+ assert scan_calls[0]["query"]["bool"]["must"][1] == {
+ "terms": {"publication_year": list(range(current_year - 4, current_year + 1))}
+ }
+
@pytest.mark.anyio
async def test_topic_heatmap_maps_field_year_counts_and_shares():
From c054cf99fea77bb0b990962a903c361de69ac20a Mon Sep 17 00:00:00 2001
From: spsaefan <117728614+spsaefan@users.noreply.github.com>
Date: Tue, 4 Aug 2026 23:19:50 +0200
Subject: [PATCH 03/19] Fix all time slider
---
.../modules/dashboard/dashboard.component.ts | 25 +++++++++++--------
1 file changed, 15 insertions(+), 10 deletions(-)
diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts
index cb9982c5..d1e70970 100644
--- a/webapp/src/app/modules/dashboard/dashboard.component.ts
+++ b/webapp/src/app/modules/dashboard/dashboard.component.ts
@@ -108,7 +108,7 @@ export class DashboardComponent implements OnInit {
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
- dashboardFromYear = this.topicTreemapMaxYear - 4;
+ dashboardFromYear = this.topicTreemapMinYear;
dashboardToYear = this.topicTreemapMaxYear;
selectedTopicTreemapNode?: string;
selectedDfgTopicTreemapNode?: string;
@@ -406,14 +406,16 @@ export class DashboardComponent implements OnInit {
this.dashboardPeriodMode = mode;
}
this.applyPresetPeriod();
- this.dashboardFromYear = this.parseDashboardYear(
- params.get('fromYear'),
- this.dashboardFromYear,
- );
- this.dashboardToYear = this.parseDashboardYear(
- params.get('toYear'),
- this.dashboardToYear,
- );
+ if (this.dashboardPeriodMode !== 'all_time') {
+ this.dashboardFromYear = this.parseDashboardYear(
+ params.get('fromYear'),
+ this.dashboardFromYear,
+ );
+ this.dashboardToYear = this.parseDashboardYear(
+ params.get('toYear'),
+ this.dashboardToYear,
+ );
+ }
if (this.dashboardFromYear > this.dashboardToYear) {
this.dashboardFromYear = this.dashboardToYear;
}
@@ -422,7 +424,10 @@ export class DashboardComponent implements OnInit {
private applyPresetPeriod(): void {
const currentYear = this.topicTreemapMaxYear;
- if (this.dashboardPeriodMode === 'last_10_years') {
+ if (this.dashboardPeriodMode === 'all_time') {
+ this.dashboardFromYear = this.topicTreemapMinYear;
+ this.dashboardToYear = currentYear;
+ } else if (this.dashboardPeriodMode === 'last_10_years') {
this.dashboardFromYear = currentYear - 9;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_5_years') {
From de880fb9f06f121ffda0db00549a1c0407365fa2 Mon Sep 17 00:00:00 2001
From: Farajollahi
Date: Wed, 5 Aug 2026 10:17:28 +0200
Subject: [PATCH 04/19] fix publications
---
service/src/main/inse/dashboard/service.py | 72 ++++++++-----------
.../src/main/inse/dashboard/test_service.py | 37 +++++-----
2 files changed, 47 insertions(+), 62 deletions(-)
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index 7351245f..ff80d646 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -30,6 +30,7 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectType,
)
+from inse.works.v2 import service as works_v2_service
from .institute_helper import get_openalex_institution
from .model import (
@@ -241,25 +242,32 @@ async def get_dashboard_publications(
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
- institution = await institutions_v2_service.get_institution_by_id_or_raise(
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- source=["id", "works_count", "counts_by_year"],
- )
if period == (None, None):
- value = int(institution.works_count or 0)
- else:
- value = sum(
- int(entry.works_count or 0)
- for entry in institution.counts_by_year or []
- if (
- (period[0] is None or int(entry.year or 0) >= period[0])
- and (period[1] is None or int(entry.year or 0) <= period[1])
- )
+ institution = await institutions_v2_service.get_institution_by_id_or_raise(
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ source=["id", "works_count"],
)
+ return DashboardStatisticValue(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ value=int(institution.works_count or 0),
+ )
+
+ first_year = period[0] if period[0] is not None else 1900
+ last_year = period[1] if period[1] is not None else 2100
+ publication_years = list(range(first_year, last_year + 1))
+
+ works = await works_v2_service.get_institution_works(
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ page=0,
+ size=1,
+ publication_years=publication_years,
+ )
+
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
- value=value,
+ value=works.total,
)
@@ -339,16 +347,8 @@ async def get_dashboard_eu_projects(
topic_ids=None,
filter_topic_ids=None,
title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
+ funding_start_years=[str(period[0])] if period[0] is not None else None,
+ funding_end_years=[str(period[1])] if period[1] is not None else None,
countries=None,
framework_programmes=None,
funding_schemes=None,
@@ -515,16 +515,8 @@ async def get_dashboard_bmbf_projects(
funding_arts=None,
topic_ids=None,
filter_topic_ids=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
+ funding_start_years=[str(period[0])] if period[0] is not None else None,
+ funding_end_years=[str(period[1])] if period[1] is not None else None,
countries=None,
page=0,
size=1,
@@ -632,16 +624,8 @@ async def get_dashboard_dfg_projects(
topic_ids=None,
filter_topic_ids=None,
title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
+ funding_start_years=[str(period[0])] if period[0] is not None else None,
+ funding_end_years=[str(period[1])] if period[1] is not None else None,
page=0,
size=1,
sort_by="id",
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index c3dae57f..305a27de 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -25,7 +25,6 @@ from inse.dashboard.service import (
get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
-from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
from inse.persons.model import CustomAuthorsListResponse
@@ -229,22 +228,18 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"bmbf_projects": 5,
}
-@pytest.mark.anyio
-async def test_dashboard_publications_uses_institutions_v2_counts():
- institution = Institution(
- id=ORG_INSTITUTION_ID,
- works_count=250,
- counts_by_year=[
- AuthorCountsByYearInner(year=2021, works_count=10),
- AuthorCountsByYearInner(year=2022, works_count=12),
- AuthorCountsByYearInner(year=2023, works_count=14),
- ],
- )
+@pytest.mark.anyio
+async def test_dashboard_publications_uses_works_v2_only_for_period():
with patch(
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
- new=AsyncMock(return_value=institution),
- ) as mocked_get_institution:
+ new=AsyncMock(
+ return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250)
+ ),
+ ) as mocked_get_institution, patch(
+ "inse.dashboard.service.works_v2_service.get_institution_works",
+ new=AsyncMock(return_value=SimpleNamespace(elements=[], total=22)),
+ ) as mocked_get_works:
all_time = await get_dashboard_publications(
ORG_INSTITUTION_ID,
"Example Org",
@@ -258,9 +253,15 @@ async def test_dashboard_publications_uses_institutions_v2_counts():
assert all_time.value == 250
assert selected_period.value == 22
- assert mocked_get_institution.await_args_list[0].kwargs == {
+ mocked_get_institution.assert_awaited_once_with(
+ raw_oa_institution_id="I123",
+ source=["id", "works_count"],
+ )
+ assert mocked_get_works.await_args_list[0].kwargs == {
"raw_oa_institution_id": "I123",
- "source": ["id", "works_count", "counts_by_year"],
+ "page": 0,
+ "size": 1,
+ "publication_years": [2021, 2022],
}
@@ -362,8 +363,8 @@ async def test_dashboard_eu_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"][-1] == "2021"
- assert call.kwargs["funding_end_years"][0] == "2019"
+ assert call.kwargs["funding_start_years"] == ["2019"]
+ assert call.kwargs["funding_end_years"] == ["2021"]
assert call.kwargs["project_types"] == list(EuCordisProjectType)
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
From 727c3fde671af118c0ed2ad7bc4807d8c77ff253 Mon Sep 17 00:00:00 2001
From: Farajollahi
Date: Wed, 5 Aug 2026 10:44:09 +0200
Subject: [PATCH 05/19] fix counts
---
service/src/main/inse/dashboard/service.py | 98 ++++++++++++++-----
.../src/main/inse/dashboard/test_service.py | 63 +++++++++---
.../inse/projects/projects_search_client.py | 5 +-
.../main/inse/projects/test_projects_dfg.py | 30 ++++++
4 files changed, 159 insertions(+), 37 deletions(-)
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index ff80d646..ec1a9b8f 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -30,7 +30,6 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectType,
)
-from inse.works.v2 import service as works_v2_service
from .institute_helper import get_openalex_institution
from .model import (
@@ -177,17 +176,48 @@ def _project_overlap_filter(
return {"bool": {"filter": filters}} if filters else None
-def _date_period(period: DashboardPeriod, date_format: str) -> DashboardPeriod:
+def _project_boundary_year_filter(
+ start_field: str,
+ end_field: str,
+ period: DashboardPeriod,
+ date_format: Literal["iso", "de", "year"],
+) -> dict[str, Any] | None:
from_year, to_year = period
- if date_format == "iso":
- return (
- f"{from_year}-01-01" if from_year is not None else None,
- f"{to_year}-12-31" if to_year is not None else None,
- )
- return (
- f"01.01.{from_year}" if from_year is not None else None,
- f"31.12.{to_year}" if to_year is not None else None,
- )
+ filters: list[dict[str, Any]] = []
+
+ if from_year is not None:
+ if date_format == "year":
+ filters.append({"term": {start_field: from_year}})
+ else:
+ first_day = (
+ f"{from_year}-01-01"
+ if date_format == "iso"
+ else f"01.01.{from_year}"
+ )
+ last_day = (
+ f"{from_year}-12-31"
+ if date_format == "iso"
+ else f"31.12.{from_year}"
+ )
+ filters.append(
+ {"range": {start_field: {"gte": first_day, "lte": last_day}}}
+ )
+
+ if to_year is not None:
+ if date_format == "year":
+ filters.append({"term": {end_field: to_year}})
+ else:
+ first_day = (
+ f"{to_year}-01-01" if date_format == "iso" else f"01.01.{to_year}"
+ )
+ last_day = (
+ f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
+ )
+ filters.append(
+ {"range": {end_field: {"gte": first_day, "lte": last_day}}}
+ )
+
+ return {"bool": {"filter": filters}} if filters else None
def get_dashboard_organization(
@@ -257,17 +287,36 @@ async def get_dashboard_publications(
last_year = period[1] if period[1] is not None else 2100
publication_years = list(range(first_year, last_year + 1))
- works = await works_v2_service.get_institution_works(
- raw_oa_institution_id=_raw_institution_id(normalized_id),
- page=0,
- size=1,
- publication_years=publication_years,
+ value = await elasticsearch.count(
+ index=ESIndex.OPENALEX_WORKS_WILDCARD,
+ query={
+ "bool": {
+ "filter": [
+ {
+ "nested": {
+ "path": "authorships",
+ "query": {
+ "nested": {
+ "path": "authorships.institutions",
+ "query": {
+ "term": {
+ "authorships.institutions.id": normalized_id
+ }
+ },
+ }
+ },
+ }
+ },
+ {"terms": {"publication_year": publication_years}},
+ ]
+ }
+ },
)
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
- value=works.total,
+ value=value,
)
@@ -396,10 +445,11 @@ async def get_dashboard_eu_project_statuses(
today = datetime.now().date().isoformat()
period = _dashboard_period(from_year, to_year)
filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
- if period_filter := _project_overlap_filter(
+ if period_filter := _project_boundary_year_filter(
"startDate",
"endDate",
- _date_period(period, "iso"),
+ period,
+ "iso",
):
filters.append(period_filter)
query = (
@@ -541,10 +591,11 @@ async def get_dashboard_bmbf_project_statuses(
aliases = await _institution_aliases(normalized_id, organization_name)
period = _dashboard_period(from_year, to_year)
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
- if period_filter := _project_overlap_filter(
+ if period_filter := _project_boundary_year_filter(
"funding_start",
"funding_end",
- _date_period(period, "de"),
+ period,
+ "de",
):
filters.append(period_filter)
today = datetime.now().strftime("%d.%m.%Y")
@@ -631,6 +682,7 @@ async def get_dashboard_dfg_projects(
sort_by="id",
sort_direction="asc",
fuzzy=False,
+ skip_enrichment=True,
)
return DashboardStatisticValue(
institution_id=normalized_id,
@@ -676,11 +728,11 @@ async def get_dashboard_dfg_project_statuses(
}
}
]
- if period_filter := _project_overlap_filter(
+ if period_filter := _project_boundary_year_filter(
"projects.funding_start",
"projects.funding_end",
period,
- missing_end_is_ongoing=True,
+ "year",
):
selected_project_filters.append(period_filter)
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index 305a27de..74be4583 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -9,8 +9,9 @@ from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.dashboard.service import (
- _openalex_work_authors_by_eu_projects,
_get_dfg_project_ids_from_projects_service,
+ _openalex_work_authors_by_eu_projects,
+ _project_boundary_year_filter,
_reconcile_project_status_counts,
_top_news_authors,
get_dashboard_bmbf_projects,
@@ -50,6 +51,40 @@ def test_project_status_counts_match_authoritative_total():
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
+def test_project_status_period_uses_exact_boundary_years():
+ assert _project_boundary_year_filter(
+ "startDate", "endDate", (2022, 2026), "iso"
+ ) == {
+ "bool": {
+ "filter": [
+ {
+ "range": {
+ "startDate": {"gte": "2022-01-01", "lte": "2022-12-31"}
+ }
+ },
+ {
+ "range": {
+ "endDate": {"gte": "2026-01-01", "lte": "2026-12-31"}
+ }
+ },
+ ]
+ }
+ }
+ assert _project_boundary_year_filter(
+ "projects.funding_start",
+ "projects.funding_end",
+ (2022, 2026),
+ "year",
+ ) == {
+ "bool": {
+ "filter": [
+ {"term": {"projects.funding_start": 2022}},
+ {"term": {"projects.funding_end": 2026}},
+ ]
+ }
+ }
+
+
@pytest.mark.anyio
async def test_top_news_authors_applies_dashboard_period():
response = {
@@ -230,16 +265,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
@pytest.mark.anyio
-async def test_dashboard_publications_uses_works_v2_only_for_period():
+async def test_dashboard_publications_uses_exact_es_count_for_period():
with patch(
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
new=AsyncMock(
return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250)
),
) as mocked_get_institution, patch(
- "inse.dashboard.service.works_v2_service.get_institution_works",
- new=AsyncMock(return_value=SimpleNamespace(elements=[], total=22)),
- ) as mocked_get_works:
+ "inse.dashboard.service.elasticsearch.count",
+ new=AsyncMock(return_value=22),
+ ) as mocked_count:
all_time = await get_dashboard_publications(
ORG_INSTITUTION_ID,
"Example Org",
@@ -257,12 +292,15 @@ async def test_dashboard_publications_uses_works_v2_only_for_period():
raw_oa_institution_id="I123",
source=["id", "works_count"],
)
- assert mocked_get_works.await_args_list[0].kwargs == {
- "raw_oa_institution_id": "I123",
- "page": 0,
- "size": 1,
- "publication_years": [2021, 2022],
+ mocked_count.assert_awaited_once()
+ count_call = mocked_count.await_args.kwargs
+ assert count_call["index"] == ESIndex.OPENALEX_WORKS_WILDCARD
+ filters = count_call["query"]["bool"]["filter"]
+ assert filters[0]["nested"]["path"] == "authorships"
+ assert filters[0]["nested"]["query"]["nested"]["query"] == {
+ "term": {"authorships.institutions.id": ORG_INSTITUTION_ID}
}
+ assert filters[1] == {"terms": {"publication_year": [2021, 2022]}}
@pytest.mark.anyio
@@ -311,8 +349,9 @@ async def test_dashboard_dfg_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"][-1] == "2022"
- assert call.kwargs["funding_end_years"][0] == "2020"
+ assert call.kwargs["funding_start_years"] == ["2020"]
+ assert call.kwargs["funding_end_years"] == ["2022"]
+ assert call.kwargs["skip_enrichment"] is True
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py
index 3b80b959..05911790 100644
--- a/service/src/main/inse/projects/projects_search_client.py
+++ b/service/src/main/inse/projects/projects_search_client.py
@@ -599,7 +599,6 @@ async def search_dfg_projects(
body["sort"] = [sort_config]
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
- print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body=body,
@@ -611,6 +610,9 @@ async def search_dfg_projects(
if skip_enrichment:
return _complete_response_to_dfg_project_page(response, page, size)
+ if not hits:
+ return _complete_response_to_dfg_project_page(response, page, size)
+
project_ids = [hit["_source"]["id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
@@ -647,7 +649,6 @@ async def search_dfg_projects(
# person["institute_name_en"] = institute.get("institute_name_en")
# person["address_country_de"] = institute.get("address_country_de")
# person["address_country_en"] = institute.get("address_country_en")
- print("ENRIECHED",source.get("institutions", []))
return _complete_response_to_dfg_project_page(response, page, size)
def _complete_response_to_dfg_project_page(
diff --git a/service/src/main/inse/projects/test_projects_dfg.py b/service/src/main/inse/projects/test_projects_dfg.py
index f9eb82b9..bc331c62 100644
--- a/service/src/main/inse/projects/test_projects_dfg.py
+++ b/service/src/main/inse/projects/test_projects_dfg.py
@@ -1,4 +1,7 @@
+from unittest.mock import AsyncMock, patch
+
import pytest
+
from inse.projects import projects_search_client
@@ -20,6 +23,33 @@ async def test_search_dfg_projects():
for name in element.names
)
+
+@pytest.mark.anyio
+async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash():
+ response = {
+ "hits": {
+ "total": {"value": 0},
+ "hits": [],
+ }
+ }
+ with patch(
+ "inse.projects.projects_search_client.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as mocked_search:
+ result = await projects_search_client.search_dfg_projects(
+ page=0,
+ size=1,
+ funding_start_years=["2022"],
+ funding_end_years=["2026"],
+ )
+
+ assert result.total == 0
+ assert result.elements == []
+ query = mocked_search.await_args.kwargs["body"]["query"]
+ assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"]
+ assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"]
+
+
@pytest.mark.anyio
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
From b21d8d3e88b624802ca44087ad986d647574430c Mon Sep 17 00:00:00 2001
From: Farajollahi
Date: Thu, 6 Aug 2026 11:32:05 +0200
Subject: [PATCH 06/19] revert period filters on dashboard
---
service/src/main/inse/dashboard/service.py | 84 ++++++++-----------
.../src/main/inse/dashboard/test_service.py | 42 +++++-----
.../projects/eu_cordis_projects_client.py | 18 ++++
.../inse/projects/projects_search_client.py | 18 ++++
service/src/main/inse/projects/service.py | 14 +++-
.../projects/test_eu_cordis_search_client.py | 17 +++-
6 files changed, 122 insertions(+), 71 deletions(-)
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index ec1a9b8f..a0f15733 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -185,37 +185,27 @@ def _project_boundary_year_filter(
from_year, to_year = period
filters: list[dict[str, Any]] = []
+ # A project overlaps the selected interval if it begins no later than the
+ # interval end and finishes no earlier than the interval start.
+ if to_year is not None:
+ if date_format == "year":
+ filters.append({"range": {start_field: {"lte": to_year}}})
+ else:
+ last_day = (
+ f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
+ )
+ filters.append({"range": {start_field: {"lte": last_day}}})
+
if from_year is not None:
if date_format == "year":
- filters.append({"term": {start_field: from_year}})
+ filters.append({"range": {end_field: {"gte": from_year}}})
else:
first_day = (
f"{from_year}-01-01"
if date_format == "iso"
else f"01.01.{from_year}"
)
- last_day = (
- f"{from_year}-12-31"
- if date_format == "iso"
- else f"31.12.{from_year}"
- )
- filters.append(
- {"range": {start_field: {"gte": first_day, "lte": last_day}}}
- )
-
- if to_year is not None:
- if date_format == "year":
- filters.append({"term": {end_field: to_year}})
- else:
- first_day = (
- f"{to_year}-01-01" if date_format == "iso" else f"01.01.{to_year}"
- )
- last_day = (
- f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
- )
- filters.append(
- {"range": {end_field: {"gte": first_day, "lte": last_day}}}
- )
+ filters.append({"range": {end_field: {"gte": first_day}}})
return {"bool": {"filter": filters}} if filters else None
@@ -396,8 +386,10 @@ async def get_dashboard_eu_projects(
topic_ids=None,
filter_topic_ids=None,
title=None,
- funding_start_years=[str(period[0])] if period[0] is not None else None,
- funding_end_years=[str(period[1])] if period[1] is not None else None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
countries=None,
framework_programmes=None,
funding_schemes=None,
@@ -565,8 +557,10 @@ async def get_dashboard_bmbf_projects(
funding_arts=None,
topic_ids=None,
filter_topic_ids=None,
- funding_start_years=[str(period[0])] if period[0] is not None else None,
- funding_end_years=[str(period[1])] if period[1] is not None else None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
countries=None,
page=0,
size=1,
@@ -675,8 +669,10 @@ async def get_dashboard_dfg_projects(
topic_ids=None,
filter_topic_ids=None,
title=None,
- funding_start_years=[str(period[0])] if period[0] is not None else None,
- funding_end_years=[str(period[1])] if period[1] is not None else None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
page=0,
size=1,
sort_by="id",
@@ -2323,16 +2319,10 @@ async def _get_eu_project_ids_from_projects_service(
topic_ids=None,
filter_topic_ids=None,
title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
countries=None,
framework_programmes=None,
funding_schemes=None,
@@ -2438,7 +2428,7 @@ async def _person_eu_project_count(
from_year: int | None = None,
to_year: int | None = None,
) -> int:
- """Uses the same author-only EU project search as the person detail page."""
+ """Returns the same filtered EU project total as the person projects tab."""
period = _dashboard_period(from_year, to_year)
projects = await projects_service.search_eu_cordis_projects(
page=0,
@@ -2454,16 +2444,10 @@ async def _person_eu_project_count(
topic_ids=None,
filter_topic_ids=None,
title=None,
- funding_start_years=(
- [str(year) for year in range(1900, period[1] + 1)]
- if period[1] is not None
- else None
- ),
- funding_end_years=(
- [str(year) for year in range(period[0], 2101)]
- if period[0] is not None
- else None
- ),
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
countries=None,
framework_programmes=None,
funding_schemes=None,
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index 74be4583..effb15c5 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -51,22 +51,14 @@ def test_project_status_counts_match_authoritative_total():
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
-def test_project_status_period_uses_exact_boundary_years():
+def test_project_status_period_uses_interval_overlap():
assert _project_boundary_year_filter(
"startDate", "endDate", (2022, 2026), "iso"
) == {
"bool": {
"filter": [
- {
- "range": {
- "startDate": {"gte": "2022-01-01", "lte": "2022-12-31"}
- }
- },
- {
- "range": {
- "endDate": {"gte": "2026-01-01", "lte": "2026-12-31"}
- }
- },
+ {"range": {"startDate": {"lte": "2026-12-31"}}},
+ {"range": {"endDate": {"gte": "2022-01-01"}}},
]
}
}
@@ -78,8 +70,8 @@ def test_project_status_period_uses_exact_boundary_years():
) == {
"bool": {
"filter": [
- {"term": {"projects.funding_start": 2022}},
- {"term": {"projects.funding_end": 2026}},
+ {"range": {"projects.funding_start": {"lte": 2026}}},
+ {"range": {"projects.funding_end": {"gte": 2022}}},
]
}
}
@@ -349,8 +341,10 @@ async def test_dashboard_dfg_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"] == ["2020"]
- assert call.kwargs["funding_end_years"] == ["2022"]
+ assert call.kwargs["funding_start_years"] is None
+ assert call.kwargs["funding_end_years"] is None
+ assert call.kwargs["active_from_year"] == 2020
+ assert call.kwargs["active_to_year"] == 2022
assert call.kwargs["skip_enrichment"] is True
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
@@ -375,8 +369,10 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"][-1] == "2020"
- assert call.kwargs["funding_end_years"][0] == "2018"
+ assert call.kwargs["funding_start_years"] is None
+ assert call.kwargs["funding_end_years"] is None
+ assert call.kwargs["active_from_year"] == 2018
+ assert call.kwargs["active_to_year"] == 2020
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
@@ -402,8 +398,10 @@ async def test_dashboard_eu_projects_uses_projects_service_total():
mocked_get_projects.assert_awaited_once()
call = mocked_get_projects.await_args
assert call.kwargs["raw_oa_institution_id"] == "I123"
- assert call.kwargs["funding_start_years"] == ["2019"]
- assert call.kwargs["funding_end_years"] == ["2021"]
+ assert call.kwargs["funding_start_years"] is None
+ assert call.kwargs["funding_end_years"] is None
+ assert call.kwargs["active_from_year"] == 2019
+ assert call.kwargs["active_to_year"] == 2021
assert call.kwargs["project_types"] == list(EuCordisProjectType)
assert call.kwargs["page"] == 0
assert call.kwargs["size"] == 1
@@ -833,6 +831,10 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
return {"aggregations": {"authors": {"buckets": []}}}
async def eu_projects(**kwargs):
+ assert kwargs["funding_start_years"] is None
+ assert kwargs["funding_end_years"] is None
+ assert kwargs["active_from_year"] == 2020
+ assert kwargs["active_to_year"] == 2022
if kwargs.get("raw_oa_institution_id"):
return EuCordisProjectSearchPage(
elements=[
@@ -866,6 +868,8 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
+ from_year=2020,
+ to_year=2022,
)
assert [author.model_dump() for author in result.eu_projects] == [
diff --git a/service/src/main/inse/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py
index 8f0af70f..e6946f92 100644
--- a/service/src/main/inse/projects/eu_cordis_projects_client.py
+++ b/service/src/main/inse/projects/eu_cordis_projects_client.py
@@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -876,6 +878,18 @@ async def _build_eu_cordis_search_query(
if funding_end_years:
must_clauses.append(_eu_year_filters("endDate", funding_end_years))
+ # Period-overlap filter: a project was active in the selected interval when
+ # it started no later than the interval end and ended no earlier than the
+ # interval start. This is intentionally separate from exact-year filters.
+ if active_to_year is not None:
+ must_clauses.append(
+ {"range": {"startDate": {"lte": f"{active_to_year}-12-31"}}}
+ )
+ if active_from_year is not None:
+ must_clauses.append(
+ {"range": {"endDate": {"gte": f"{active_from_year}-01-01"}}}
+ )
+
# === Project core filters ===
if framework_programmes:
must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}})
@@ -937,6 +951,8 @@ async def search_eu_cordis_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -965,6 +981,8 @@ async def search_eu_cordis_projects(
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py
index 05911790..084689ff 100644
--- a/service/src/main/inse/projects/projects_search_client.py
+++ b/service/src/main/inse/projects/projects_search_client.py
@@ -368,6 +368,8 @@ async def search_dfg_projects(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> DfgProjectPage:
"""Searches for DFG projects based on the provided filtering and sorting criteria.
@@ -488,6 +490,11 @@ async def search_dfg_projects(
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
+ if active_to_year is not None:
+ must_clauses.append({"range": {"funding_start": {"lte": str(active_to_year)}}})
+ if active_from_year is not None:
+ must_clauses.append({"range": {"funding_end": {"gte": str(active_from_year)}}})
+
if names:
name_must_clauses = []
for full_name in names:
@@ -858,6 +865,8 @@ async def search_bund_projects_with_filters(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_topic_enrichment: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> BundProjectPage:
"""
Main search function for BUND projects, analogous to the DFG search.
@@ -999,6 +1008,15 @@ async def search_bund_projects_with_filters(
if funding_end_years:
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
+ if active_to_year is not None:
+ must_clauses.append(
+ {"range": {"funding_start": {"lte": f"31.12.{active_to_year}"}}}
+ )
+ if active_from_year is not None:
+ must_clauses.append(
+ {"range": {"funding_end": {"gte": f"01.01.{active_from_year}"}}}
+ )
+
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
# === Sorting ===
sort_by = sort_by.strip().lower()
diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py
index ab5fa644..1ce656c5 100644
--- a/service/src/main/inse/projects/service.py
+++ b/service/src/main/inse/projects/service.py
@@ -175,6 +175,8 @@ async def get_dfg_projects_by_author_id(
sort_direction: str = "asc",
fuzzy: bool = False,
skip_enrichment: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> DfgProjectPage:
logger.debug(
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
@@ -250,6 +252,8 @@ async def get_dfg_projects_by_author_id(
sort_direction=sort_direction,
fuzzy=fuzzy,
skip_enrichment=skip_enrichment,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
)
async def get_institution_cordis_eu_projects_funding_over_time(
@@ -425,6 +429,8 @@ async def search_bund_projects_with_filters(
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
) -> BundProjectPage:
institution_aliases = []
if raw_oa_institution_id:
@@ -456,7 +462,9 @@ async def search_bund_projects_with_filters(
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
- fuzzy=fuzzy
+ fuzzy=fuzzy,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
)
def _calculate_funding_over_time(
@@ -618,6 +626,8 @@ async def search_eu_cordis_projects(
title: str | None = None,
funding_start_years: list[str] | None = None,
funding_end_years: list[str] | None = None,
+ active_from_year: int | None = None,
+ active_to_year: int | None = None,
countries: list[str] | None = None,
framework_programmes: list[str] | None = None,
funding_schemes: list[str] | None = None,
@@ -679,6 +689,8 @@ async def search_eu_cordis_projects(
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
+ active_from_year=active_from_year,
+ active_to_year=active_to_year,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
diff --git a/service/src/main/inse/projects/test_eu_cordis_search_client.py b/service/src/main/inse/projects/test_eu_cordis_search_client.py
index 342f383b..f6e7d5c3 100644
--- a/service/src/main/inse/projects/test_eu_cordis_search_client.py
+++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py
@@ -2,6 +2,21 @@ import pytest
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
+@pytest.mark.anyio
+async def test_active_period_filter_matches_projects_overlapping_interval():
+ query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query(
+ active_from_year=2022,
+ active_to_year=2026,
+ )
+
+ assert {"range": {"startDate": {"lte": "2026-12-31"}}} in query["bool"][
+ "must"
+ ]
+ assert {"range": {"endDate": {"gte": "2022-01-01"}}} in query["bool"][
+ "must"
+ ]
+
+
@pytest.mark.anyio
async def test_search_eu_cordis_projects_by_title():
"""Test searching EU CORDIS projects by title."""
@@ -362,4 +377,4 @@ async def test_search_eu_cordis_projects_with_fuzzy_topic_search():
# Note: This may return 0 results if the topic ID doesn't exist
# The important thing is that it doesn't crash
assert isinstance(res.total, int)
- assert isinstance(res.elements, list)
\ No newline at end of file
+ assert isinstance(res.elements, list)
From 567b5ecd4fbbbdd5d9caef59fc1707e120292118 Mon Sep 17 00:00:00 2001
From: Farajollahi
Date: Thu, 6 Aug 2026 12:16:49 +0200
Subject: [PATCH 07/19] implement Eu and Bund topics treemap
---
service/src/main/inse/dashboard/model.py | 18 ++
service/src/main/inse/dashboard/router.py | 44 ++++
service/src/main/inse/dashboard/service.py | 244 ++++++++++++++++++
.../src/main/inse/dashboard/test_service.py | 153 +++++++++++
.../dashboard/dashboard-statistics.service.ts | 23 ++
.../dashboard/dashboard.component.html | 86 ++++++
.../modules/dashboard/dashboard.component.ts | 126 ++++++++-
.../topic-wordcloud-dialog.component.ts | 2 +-
8 files changed, 687 insertions(+), 9 deletions(-)
diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py
index eae2251a..ada6c020 100644
--- a/service/src/main/inse/dashboard/model.py
+++ b/service/src/main/inse/dashboard/model.py
@@ -54,6 +54,8 @@ class DfgProjectTopic(BaseModel):
field: str | None = None
domain: str | None = None
project_count: int
+ field_project_count: int
+ subfield_project_count: int
keywords: list[DfgProjectKeyword]
@@ -65,6 +67,22 @@ class DfgProjectTopics(BaseModel):
topics: list[DfgProjectTopic]
+class EuProjectTopics(BaseModel):
+ institution_id: str
+ organization_name: str
+ project_count: int
+ matched_project_count: int
+ topics: list[DfgProjectTopic]
+
+
+class BundProjectTopics(BaseModel):
+ institution_id: str
+ organization_name: str
+ project_count: int
+ matched_project_count: int
+ topics: list[DfgProjectTopic]
+
+
class TopAuthor(BaseModel):
id: str | None = None
name: str
diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py
index bd5ad49b..fb01a93a 100644
--- a/service/src/main/inse/dashboard/router.py
+++ b/service/src/main/inse/dashboard/router.py
@@ -10,10 +10,12 @@ from inse.tags import Tags
from .model import (
BmbfProjectStatusStatistics,
+ BundProjectTopics,
DashboardStatistics,
DashboardStatisticValue,
DfgProjectStatusStatistics,
DfgProjectTopics,
+ EuProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
TopicHeatmap,
@@ -22,9 +24,11 @@ from .model import (
from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
+ get_dashboard_bund_topics,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_projects,
get_dashboard_dfg_topics,
+ get_dashboard_eu_topics,
get_dashboard_eu_project_statuses,
get_dashboard_eu_projects,
get_dashboard_organization,
@@ -256,6 +260,46 @@ async def dashboard_dfg_project_topics(
)
+@router.get(
+ "/projects/eu/topics",
+ operation_id="getDashboardEuProjectTopics",
+ response_model=EuProjectTopics,
+)
+async def dashboard_eu_project_topics(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> EuProjectTopics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_eu_topics(
+ organization.openalex_institution_id,
+ organization.name,
+ from_year=from_year,
+ to_year=to_year,
+ )
+
+
+@router.get(
+ "/projects/bund/topics",
+ operation_id="getDashboardBundProjectTopics",
+ response_model=BundProjectTopics,
+)
+async def dashboard_bund_project_topics(
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> BundProjectTopics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_bund_topics(
+ organization.openalex_institution_id,
+ organization.name,
+ from_year=from_year,
+ to_year=to_year,
+ )
+
+
@router.get(
"/top-authors",
operation_id="getDashboardTopAuthors",
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index a0f15733..f09939ab 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -1,4 +1,5 @@
import asyncio
+import hashlib
import logging
import re
from collections import defaultdict
@@ -34,12 +35,14 @@ from inse.projects.model import (
from .institute_helper import get_openalex_institution
from .model import (
BmbfProjectStatusStatistics,
+ BundProjectTopics,
DashboardStatistics,
DfgProjectKeyword,
DashboardStatisticValue,
DfgProjectStatusStatistics,
DfgProjectTopic,
DfgProjectTopics,
+ EuProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
TopAuthorStatistics,
@@ -860,6 +863,14 @@ async def get_dashboard_dfg_topics(
if keyword:
topic["keywords"].setdefault(keyword, set()).add(project_id)
+ field_project_ids: dict[str, set[str]] = defaultdict(set)
+ subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
+ for topic in topics.values():
+ field_name = str(topic["field"] or "")
+ subfield_name = str(topic["subfield"] or "")
+ field_project_ids[field_name].update(topic["project_ids"])
+ subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
+
topic_list = [
DfgProjectTopic(
id=topic["id"],
@@ -868,6 +879,12 @@ async def get_dashboard_dfg_topics(
field=topic["field"],
domain=topic["domain"],
project_count=len(topic["project_ids"]),
+ field_project_count=len(field_project_ids[str(topic["field"] or "")]),
+ subfield_project_count=len(
+ subfield_project_ids[
+ (str(topic["field"] or ""), str(topic["subfield"] or ""))
+ ]
+ ),
keywords=sorted(
[
DfgProjectKeyword(
@@ -891,6 +908,233 @@ async def get_dashboard_dfg_topics(
)
+async def get_dashboard_eu_topics(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> EuProjectTopics:
+ normalized_id = _normalize_institution_id(institution_id)
+ project_ids = await _get_eu_project_ids_from_projects_service(
+ normalized_id,
+ from_year=from_year,
+ to_year=to_year,
+ )
+ topics: dict[str, dict[str, Any]] = {}
+ matched_project_ids: set[str] = set()
+
+ if project_ids:
+ mapping_indices = (
+ ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
+ ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
+ ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
+ )
+ for mapping_index in mapping_indices:
+ async for hit in elasticsearch.scan(
+ index=str(mapping_index),
+ query={"terms": {"project_id": project_ids}},
+ source=["project_id", "keyword", "topic_matches"],
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ ):
+ source = hit.get("_source", {})
+ project_id = str(source.get("project_id") or "")
+ if not project_id:
+ continue
+ keyword = str(source.get("keyword") or "").strip()
+ matched_project_ids.add(project_id)
+ for match in source.get("topic_matches", []):
+ topic_id = str(match.get("topic_id") or "")
+ if not topic_id:
+ continue
+ topic = topics.setdefault(
+ topic_id,
+ {
+ "id": topic_id,
+ "name": str(match.get("topic_display_name") or topic_id),
+ "subfield": match.get("subfield"),
+ "field": match.get("field"),
+ "domain": match.get("domain"),
+ "project_ids": set(),
+ "keywords": {},
+ },
+ )
+ topic["project_ids"].add(project_id)
+ if keyword:
+ topic["keywords"].setdefault(keyword, set()).add(project_id)
+
+ field_project_ids: dict[str, set[str]] = defaultdict(set)
+ subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
+ for topic in topics.values():
+ field_name = str(topic["field"] or "")
+ subfield_name = str(topic["subfield"] or "")
+ field_project_ids[field_name].update(topic["project_ids"])
+ subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
+
+ topic_list = [
+ DfgProjectTopic(
+ id=topic["id"],
+ name=topic["name"],
+ subfield=topic["subfield"],
+ field=topic["field"],
+ domain=topic["domain"],
+ project_count=len(topic["project_ids"]),
+ field_project_count=len(field_project_ids[str(topic["field"] or "")]),
+ subfield_project_count=len(
+ subfield_project_ids[
+ (str(topic["field"] or ""), str(topic["subfield"] or ""))
+ ]
+ ),
+ keywords=sorted(
+ [
+ DfgProjectKeyword(
+ name=keyword,
+ project_count=len(keyword_project_ids),
+ )
+ for keyword, keyword_project_ids in topic["keywords"].items()
+ ],
+ key=lambda entry: (-entry.project_count, entry.name),
+ ),
+ )
+ for topic in topics.values()
+ ]
+ topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
+ return EuProjectTopics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ project_count=len(project_ids),
+ matched_project_count=len(matched_project_ids),
+ topics=topic_list,
+ )
+
+
+async def get_dashboard_bund_topics(
+ institution_id: str,
+ organization_name: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+) -> BundProjectTopics:
+ normalized_id = _normalize_institution_id(institution_id)
+ period = _dashboard_period(from_year, to_year)
+ page_size = 1000
+ page_number = 0
+ project_ids: set[str] = set()
+
+ while True:
+ projects = await projects_service.search_bund_projects_with_filters(
+ institutions_search_client=InstitutionsSearchClient(),
+ executing_agency=None,
+ raw_oa_institution_id=_raw_institution_id(normalized_id),
+ title=None,
+ keywords=None,
+ funding_arts=None,
+ topic_ids=None,
+ filter_topic_ids=None,
+ funding_start_years=None,
+ funding_end_years=None,
+ active_from_year=period[0],
+ active_to_year=period[1],
+ countries=None,
+ page=page_number,
+ size=page_size,
+ sort_by="id",
+ sort_direction="asc",
+ fuzzy=False,
+ )
+ project_ids.update(
+ project.funding_code
+ for project in projects.elements
+ if project.funding_code
+ )
+ if len(project_ids) >= projects.total or not projects.elements:
+ break
+ page_number += 1
+
+ topics: dict[str, dict[str, Any]] = {}
+ matched_project_ids: set[str] = set()
+ if project_ids:
+ mapping_project_ids = sorted(
+ hashlib.sha256(project_id.encode("utf-8")).hexdigest()
+ for project_id in project_ids
+ )
+ async for hit in elasticsearch.scan(
+ index=str(ESIndex.PROJECTS_BUND_TOPICS),
+ query={"terms": {"project_id": mapping_project_ids}},
+ source=["project_id", "keyword", "topic_matches"],
+ page_size=1000,
+ cluster=ESCluster.INSE,
+ ):
+ source = hit.get("_source", {})
+ project_id = str(source.get("project_id") or "")
+ if not project_id:
+ continue
+ keyword = str(source.get("keyword") or "").strip()
+ matched_project_ids.add(project_id)
+ for match in source.get("topic_matches", []):
+ topic_id = str(match.get("topic_id") or "")
+ if not topic_id:
+ continue
+ topic = topics.setdefault(
+ topic_id,
+ {
+ "id": topic_id,
+ "name": str(match.get("topic_display_name") or topic_id),
+ "subfield": match.get("subfield"),
+ "field": match.get("field"),
+ "domain": match.get("domain"),
+ "project_ids": set(),
+ "keywords": {},
+ },
+ )
+ topic["project_ids"].add(project_id)
+ if keyword:
+ topic["keywords"].setdefault(keyword, set()).add(project_id)
+
+ field_project_ids: dict[str, set[str]] = defaultdict(set)
+ subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
+ for topic in topics.values():
+ field_name = str(topic["field"] or "")
+ subfield_name = str(topic["subfield"] or "")
+ field_project_ids[field_name].update(topic["project_ids"])
+ subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
+
+ topic_list = [
+ DfgProjectTopic(
+ id=topic["id"],
+ name=topic["name"],
+ subfield=topic["subfield"],
+ field=topic["field"],
+ domain=topic["domain"],
+ project_count=len(topic["project_ids"]),
+ field_project_count=len(field_project_ids[str(topic["field"] or "")]),
+ subfield_project_count=len(
+ subfield_project_ids[
+ (str(topic["field"] or ""), str(topic["subfield"] or ""))
+ ]
+ ),
+ keywords=sorted(
+ [
+ DfgProjectKeyword(
+ name=keyword,
+ project_count=len(keyword_project_ids),
+ )
+ for keyword, keyword_project_ids in topic["keywords"].items()
+ ],
+ key=lambda entry: (-entry.project_count, entry.name),
+ ),
+ )
+ for topic in topics.values()
+ ]
+ topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
+ return BundProjectTopics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ project_count=len(project_ids),
+ matched_project_count=len(matched_project_ids),
+ topics=topic_list,
+ )
+
+
async def _get_dfg_project_ids_from_projects_service(
institution_id: str,
from_year: int | None = None,
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index effb15c5..4574fa80 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -1,4 +1,5 @@
from datetime import datetime
+import hashlib
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -15,8 +16,10 @@ from inse.dashboard.service import (
_reconcile_project_status_counts,
_top_news_authors,
get_dashboard_bmbf_projects,
+ get_dashboard_bund_topics,
get_dashboard_dfg_projects,
get_dashboard_eu_projects,
+ get_dashboard_eu_topics,
get_dashboard_organization,
get_dashboard_persons,
get_dashboard_publications,
@@ -31,6 +34,7 @@ from inse.models.openalex.meta import Meta
from inse.persons.model import CustomAuthorsListResponse
from inse.projects.model import (
BundProjectPage,
+ BundProjectSummary,
DfgProjectPage,
DfgProjectSummary,
EuCordisProjectSearchPage,
@@ -154,6 +158,155 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service():
assert first_call.kwargs["funding_end_years"][0] == "2020"
+@pytest.mark.anyio
+async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects():
+ scanned_indices: list[str] = []
+
+ async def scan(**kwargs):
+ scanned_indices.append(kwargs["index"])
+ if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING):
+ yield {
+ "_source": {
+ "project_id": "P1",
+ "keyword": "AI",
+ "topic_matches": [
+ {
+ "topic_id": "T1",
+ "topic_display_name": "Artificial Intelligence",
+ "field": "Computer Science",
+ "subfield": "AI",
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+ yield {
+ "_source": {
+ "project_id": "P1",
+ "keyword": "Robotics",
+ "topic_matches": [
+ {
+ "topic_id": "T2",
+ "topic_display_name": "Robotics",
+ "field": "Computer Science",
+ "subfield": "Robotics",
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+ if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS):
+ yield {
+ "_source": {
+ "project_id": "P2",
+ "keyword": "AI",
+ "topic_matches": [
+ {
+ "topic_id": "T1",
+ "topic_display_name": "Artificial Intelligence",
+ "field": "Computer Science",
+ "subfield": "AI",
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+
+ with patch(
+ "inse.dashboard.service._get_eu_project_ids_from_projects_service",
+ new=AsyncMock(return_value=["P1", "P2", "P3"]),
+ ), patch("inse.dashboard.service.elasticsearch.scan", new=scan):
+ result = await get_dashboard_eu_topics(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ from_year=2022,
+ to_year=2026,
+ )
+
+ assert scanned_indices == [
+ str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING),
+ str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS),
+ str(ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS),
+ ]
+ assert result.project_count == 3
+ assert result.matched_project_count == 2
+ assert result.topics[0].project_count == 2
+ assert result.topics[0].keywords[0].project_count == 2
+ assert {topic.field_project_count for topic in result.topics} == {2}
+ assert {topic.name: topic.subfield_project_count for topic in result.topics} == {
+ "Artificial Intelligence": 2,
+ "Robotics": 1,
+ }
+
+
+@pytest.mark.anyio
+async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts():
+ project_page = BundProjectPage(
+ elements=[
+ BundProjectSummary(funding_code="B1"),
+ BundProjectSummary(funding_code="B2"),
+ ],
+ total=2,
+ page=0,
+ size=1000,
+ )
+
+ async def scan(**kwargs):
+ assert kwargs["index"] == str(ESIndex.PROJECTS_BUND_TOPICS)
+ mapping_ids = {
+ funding_code: hashlib.sha256(funding_code.encode("utf-8")).hexdigest()
+ for funding_code in ("B1", "B2")
+ }
+ assert kwargs["query"] == {
+ "terms": {"project_id": sorted(mapping_ids.values())}
+ }
+ for project_id, topic_id, topic_name, subfield in (
+ (mapping_ids["B1"], "T1", "Artificial Intelligence", "AI"),
+ (mapping_ids["B1"], "T2", "Robotics", "Robotics"),
+ (mapping_ids["B2"], "T1", "Artificial Intelligence", "AI"),
+ ):
+ yield {
+ "_source": {
+ "project_id": project_id,
+ "keyword": topic_name,
+ "topic_matches": [
+ {
+ "topic_id": topic_id,
+ "topic_display_name": topic_name,
+ "field": "Computer Science",
+ "subfield": subfield,
+ "domain": "Physical Sciences",
+ }
+ ],
+ }
+ }
+
+ with patch(
+ "inse.dashboard.service.projects_service.search_bund_projects_with_filters",
+ new=AsyncMock(return_value=project_page),
+ ) as mocked_projects, patch(
+ "inse.dashboard.service.elasticsearch.scan",
+ new=scan,
+ ):
+ result = await get_dashboard_bund_topics(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ from_year=2022,
+ to_year=2026,
+ )
+
+ project_call = mocked_projects.await_args
+ assert project_call.kwargs["active_from_year"] == 2022
+ assert project_call.kwargs["active_to_year"] == 2026
+ assert result.project_count == 2
+ assert result.matched_project_count == 2
+ assert {topic.field_project_count for topic in result.topics} == {2}
+ assert {topic.name: topic.subfield_project_count for topic in result.topics} == {
+ "Artificial Intelligence": 2,
+ "Robotics": 1,
+ }
+
+
@pytest.mark.anyio
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts
index 6f406f0b..894da8a3 100644
--- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts
+++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts
@@ -59,6 +59,8 @@ export interface DfgProjectTopic {
field?: string | null;
domain?: string | null;
project_count: number;
+ field_project_count: number;
+ subfield_project_count: number;
keywords: DfgProjectKeyword[];
}
@@ -75,6 +77,9 @@ export interface DfgProjectTopics {
topics: DfgProjectTopic[];
}
+export interface EuProjectTopics extends DfgProjectTopics {}
+export interface BundProjectTopics extends DfgProjectTopics {}
+
export interface TopAuthor {
id?: string | null;
name: string;
@@ -202,6 +207,24 @@ export class DashboardStatisticsService {
);
}
+ getEuProjectTopics(
+ period: DashboardPeriodBounds = {},
+ ): Observable {
+ return this.httpClient.get(
+ `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`,
+ { params: this.periodParams(period) },
+ );
+ }
+
+ getBundProjectTopics(
+ period: DashboardPeriodBounds = {},
+ ): Observable {
+ return this.httpClient.get(
+ `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`,
+ { params: this.periodParams(period) },
+ );
+ }
+
getTopAuthors(
period: DashboardPeriodBounds = {},
): Observable {
diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html
index 7cf8b2bc..5b95c4a7 100644
--- a/webapp/src/app/modules/dashboard/dashboard.component.html
+++ b/webapp/src/app/modules/dashboard/dashboard.component.html
@@ -317,6 +317,92 @@
}
+ @if (euTopicsLoading || euTopicsError || euProjectTopics) {
+
+
+
+ @if (euTopicsLoading) {
+
+ } @else if (euTopicsError) {
+
+ Die EU-Topic-Treemap konnte nicht geladen werden.
+
+ } @else {
+
+
+ }
+
+ }
+
+ @if (bundTopicsLoading || bundTopicsError || bundProjectTopics) {
+
+
+
+ @if (bundTopicsLoading) {
+
+ } @else if (bundTopicsError) {
+
+ Die BUND-Topic-Treemap konnte nicht geladen werden.
+
+ } @else {
+
+
+ }
+
+ }
+
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
+
+
+