From dfdc35ad81eafb68aeb5d272663bbb753aa2ba77 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 14 Jul 2026 13:09:45 +0200 Subject: [PATCH 1/6] fix treemap --- service/src/main/inse/dashboard/model.py | 29 +- service/src/main/inse/dashboard/router.py | 25 ++ service/src/main/inse/dashboard/service.py | 401 +++++++++++++----- .../src/main/inse/dashboard/test_service.py | 284 ++++++------- .../src/app/api/model/topAuthorStatistics.ts | 2 +- .../dashboard/dashboard-statistics.service.ts | 43 +- .../modules/dashboard/dashboard.component.ts | 5 + .../topic-heatmap.component.html | 6 +- .../topic-heatmap/topic-heatmap.component.ts | 62 ++- .../topic-wordcloud-dialog.component.html | 37 ++ .../topic-wordcloud-dialog.component.scss | 49 +++ .../topic-wordcloud-dialog.component.ts | 102 +++++ 12 files changed, 777 insertions(+), 268 deletions(-) create mode 100644 webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html create mode 100644 webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss create mode 100644 webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index c59f8028..426c1402 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -27,7 +27,7 @@ class TopAuthor(BaseModel): class TopAuthorStatistics(BaseModel): institution_id: str works: list[TopAuthor] - projects: list[TopAuthor] + eu_projects: list[TopAuthor] patents: list[TopAuthor] news: list[TopAuthor] @@ -38,11 +38,27 @@ class TopicHeatmapValue(BaseModel): share: float +class TopicHeatmapTopic(BaseModel): + id: str + name: str + total: int + values: list[TopicHeatmapValue] + + +class TopicHeatmapSubfield(BaseModel): + id: str + name: str + total: int + values: list[TopicHeatmapValue] + topics: list[TopicHeatmapTopic] + + class TopicHeatmapField(BaseModel): id: str name: str total: int values: list[TopicHeatmapValue] + subfields: list[TopicHeatmapSubfield] class TopicHeatmap(BaseModel): @@ -50,3 +66,14 @@ class TopicHeatmap(BaseModel): organization_name: str years: list[int] fields: list[TopicHeatmapField] + + +class TopicWordCloudWord(BaseModel): + id: str + name: str + count: int + + +class TopicWordCloud(BaseModel): + topic_id: str + words: list[TopicWordCloudWord] diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index 0012bff3..82377042 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -13,6 +13,7 @@ from .model import ( DashboardStatistics, TopAuthorStatistics, TopicHeatmap, + TopicWordCloud, ) from .service import ( get_dashboard_bmbf_projects, @@ -24,6 +25,7 @@ from .service import ( get_dashboard_statistics, get_top_authors, get_topic_heatmap, + get_topic_word_cloud, ) router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD]) @@ -166,3 +168,26 @@ async def dashboard_topic_heatmap( to_year=to_year, limit=limit, ) + + +@router.get( + "/topic-wordcloud", + operation_id="getDashboardTopicWordCloud", + response_model=TopicWordCloud, +) +async def dashboard_topic_word_cloud( + topic_id: str = Query(alias="topicId", min_length=1), + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + limit: int = Query(default=30, ge=1, le=100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopicWordCloud: + organization = get_dashboard_organization(session, access_token) + return await get_topic_word_cloud( + institution_id=organization.openalex_institution_id, + topic_id=topic_id, + from_year=from_year, + to_year=to_year, + limit=limit, + ) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 42f8a9b6..39bf6f91 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -20,11 +20,18 @@ from .model import ( TopAuthorStatistics, TopicHeatmap, TopicHeatmapField, + TopicHeatmapSubfield, + TopicHeatmapTopic, TopicHeatmapValue, + TopicWordCloud, + TopicWordCloudWord, ) TOP_AUTHOR_LIMIT = 10 TOPIC_HEATMAP_LIMIT = 25 +TOPIC_HEATMAP_SUBFIELD_LIMIT = 100 +TOPIC_HEATMAP_TOPIC_LIMIT = 100 +TOPIC_WORD_CLOUD_LIMIT = 30 TOPIC_HEATMAP_YEARS = 5 WorksPeriod = Literal["all_time", "last_5_years"] logger = logging.getLogger(__name__) @@ -112,14 +119,74 @@ async def get_dashboard_persons( organization_name: str, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) + + target_year = datetime.now().year - 1 + + recent_affiliation_query = { + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + { + "match_phrase": { + "affiliations.institution.id": normalized_id + } + }, + {"range": {"affiliations.years": {"gte": target_year}}}, + ] + } + }, + } + } + matching_last_known_institution_query = { + "nested": { + "path": "last_known_institutions", + "query": { + "match_phrase": { + "last_known_institutions.id": normalized_id + } + }, + } + } + missing_last_known_institutions_query = { + "bool": { + "must_not": [ + { + "nested": { + "path": "last_known_institutions", + "query": {"exists": {"field": "last_known_institutions.id"}}, + } + } + ] + } + } + search_query = { + "bool": { + "should": [ + { + "bool": { + "filter": [ + matching_last_known_institution_query, + recent_affiliation_query, + ] + } + }, + { + "bool": { + "filter": [ + missing_last_known_institutions_query, + recent_affiliation_query, + ] + } + }, + ], + "minimum_should_match": 1, + } + } response = await elasticsearch.search( index=ESIndex.OPENALEX_AUTHORS, - query={ - "nested": { - "path": "affiliations", - "query": {"term": {"affiliations.institution.id": normalized_id}}, - } - }, + query=search_query, size=0, track_total_hits=True, cluster=ESCluster.NES, @@ -266,10 +333,9 @@ async def get_top_authors( normalized_id = _normalize_institution_id(institution_id) authors = await _safe_institution_authors(normalized_id) works = _top_work_authors(authors, works_period) - aliases = await _safe_institution_aliases(normalized_id, organization_name) - projects = await _safe_top_authors( - "projects", - _top_project_authors(authors, aliases), + eu_projects = await _safe_top_authors( + "eu_projects", + _top_eu_project_publication_authors(), ) patents = await _safe_top_authors( "patents", @@ -282,7 +348,7 @@ async def get_top_authors( return TopAuthorStatistics( institution_id=normalized_id, works=works, - projects=projects, + eu_projects=eu_projects, patents=patents, news=news, ) @@ -363,7 +429,49 @@ async def get_topic_heatmap( } } }, - } + }, + "subfields": { + "terms": { + "field": "topics.subfield.id", + "size": TOPIC_HEATMAP_SUBFIELD_LIMIT, + "order": [ + {"works": "desc"}, + {"_key": "asc"}, + ], + }, + "aggs": { + "subfield_name": { + "terms": { + "field": "topics.subfield.display_name.keyword", + "size": 1, + } + }, + "works": { + "reverse_nested": {}, + }, + "topics": { + "terms": { + "field": "topics.id", + "size": TOPIC_HEATMAP_TOPIC_LIMIT, + "order": [ + {"works": "desc"}, + {"_key": "asc"}, + ], + }, + "aggs": { + "topic_name": { + "terms": { + "field": "topics.display_name.keyword", + "size": 1, + } + }, + "works": { + "reverse_nested": {}, + }, + }, + }, + }, + }, }, } }, @@ -393,6 +501,88 @@ async def get_topic_heatmap( ) +async def get_topic_word_cloud( + institution_id: str, + topic_id: str, + from_year: int | None = None, + to_year: int | None = None, + limit: int = TOPIC_WORD_CLOUD_LIMIT, +) -> TopicWordCloud: + normalized_institution_id = _normalize_institution_id(institution_id) + filters: list[dict[str, Any]] = [] + if from_year is not None or to_year is not None: + year_range: dict[str, int] = {} + if from_year is not None: + year_range["gte"] = from_year + if to_year is not None: + year_range["lte"] = to_year + filters.append({"range": {"publication_year": year_range}}) + + response = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body={ + "size": 0, + "query": { + "bool": { + "must": [ + _institution_works_query(normalized_institution_id), + { + "nested": { + "path": "topics", + "query": {"term": {"topics.id": topic_id}}, + } + }, + ], + "filter": filters, + } + }, + "aggs": { + "topics_nested": { + "nested": {"path": "topics"}, + "aggs": { + "topics": { + "terms": { + "field": "topics.id", + "size": limit + 1, + "order": [ + {"works": "desc"}, + {"_key": "asc"}, + ], + }, + "aggs": { + "topic_name": { + "terms": { + "field": "topics.display_name.keyword", + "size": 1, + } + }, + "works": {"reverse_nested": {}}, + }, + } + }, + } + }, + }, + cluster=ESCluster.NES, + ) + buckets = ( + response.get("aggregations", {}) + .get("topics_nested", {}) + .get("topics", {}) + .get("buckets", []) + ) + words = [ + TopicWordCloudWord( + id=str(bucket["key"]), + name=_aggregation_name(bucket, "topic_name", str(bucket["key"])), + count=int(bucket.get("works", {}).get("doc_count", 0)), + ) + for bucket in buckets + if bucket.get("key") and str(bucket["key"]) != topic_id + ][:limit] + return TopicWordCloud(topic_id=topic_id, words=words) + + async def _safe_top_authors( source: str, operation: Any ) -> list[TopAuthor]: @@ -489,11 +679,51 @@ def _topic_heatmap_field( name=_field_name(bucket, field_names.get(field_id, field_id)), total=int(bucket.get("works", {}).get("doc_count", 0)), values=values, + subfields=[ + _topic_heatmap_subfield(subfield) + for subfield in bucket.get("subfields", {}).get("buckets", []) + if subfield.get("key") + ], + ) + + +def _topic_heatmap_subfield( + bucket: dict[str, Any], +) -> TopicHeatmapSubfield: + subfield_id = str(bucket["key"]) + return TopicHeatmapSubfield( + id=subfield_id, + name=_aggregation_name(bucket, "subfield_name", subfield_id), + total=int(bucket.get("works", {}).get("doc_count", 0)), + values=[], + topics=[ + _topic_heatmap_topic(topic) + for topic in bucket.get("topics", {}).get("buckets", []) + if topic.get("key") + ], + ) + + +def _topic_heatmap_topic( + bucket: dict[str, Any], +) -> TopicHeatmapTopic: + topic_id = str(bucket["key"]) + return TopicHeatmapTopic( + id=topic_id, + name=_aggregation_name(bucket, "topic_name", topic_id), + total=int(bucket.get("works", {}).get("doc_count", 0)), + values=[], ) def _field_name(bucket: dict[str, Any], fallback: str) -> str: - name_buckets = bucket.get("field_name", {}).get("buckets", []) + return _aggregation_name(bucket, "field_name", fallback) + + +def _aggregation_name( + bucket: dict[str, Any], aggregation: str, fallback: str +) -> str: + name_buckets = bucket.get(aggregation, {}).get("buckets", []) if name_buckets and name_buckets[0].get("key"): return str(name_buckets[0]["key"]) return fallback @@ -553,17 +783,6 @@ async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]] return [] -async def _safe_institution_aliases( - institution_id: str, - organization_name: str, -) -> list[str]: - try: - return await _institution_aliases(institution_id, organization_name) - except Exception: - logger.exception("Could not load aliases for institution %s.", institution_id) - return [organization_name] - - async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: response = await elasticsearch.search( index=ESIndex.OPENALEX_AUTHORS, @@ -591,92 +810,6 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: ] -async def _top_project_authors( - authors: list[dict[str, Any]], - aliases: list[str], -) -> list[TopAuthor]: - if not aliases: - return [] - counts: dict[str, int] = {} - names: dict[str, str] = {} - for bucket in await _top_dfg_project_author_buckets(aliases): - key = str(bucket.get("key", "")).strip() - if key: - normalized_key = key.casefold() - names[normalized_key] = key - counts[normalized_key] = counts.get(normalized_key, 0) + int( - bucket.get("doc_count", 0) - ) - - institution_authors = {author["name"].casefold(): author for author in authors} - ranked = sorted( - ( - (name, count) - for name, count in counts.items() - if count > 0 - ), - key=lambda item: (-item[1], names[item[0]].casefold()), - ) - return [ - TopAuthor( - id=( - _short_author_id(institution_authors[name]["id"]) - if name in institution_authors - else None - ), - name=( - institution_authors[name]["name"] - if name in institution_authors - else names[name] - ), - count=count, - ) - for name, count in ranked[:TOP_AUTHOR_LIMIT] - ] - - -async def _top_dfg_project_author_buckets( - aliases: list[str], -) -> list[dict[str, Any]]: - response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_ALL, - body={ - "size": 0, - "query": _dfg_institution_query(aliases), - "aggs": { - "people": { - "terms": { - "script": { - "lang": "painless", - "source": _dfg_involved_persons_script(), - }, - "size": 10000, - } - } - }, - }, - cluster=ESCluster.INSE, - ) - return ( - response.get("aggregations", {}).get("people", {}).get("buckets", []) - ) - - -def _dfg_involved_persons_script() -> str: - return ( - "def names = new HashSet(); " - "def value = params['_source'].containsKey('Beteiligte Personen') " - " ? params['_source']['Beteiligte Personen'] : null; " - "if (value instanceof String && value.length() > 0) { " - " for (name in value.splitOnToken(';')) { " - " def trimmed = name.trim(); " - " if (trimmed.length() > 0) { names.add(trimmed); } " - " } " - "} " - "return new ArrayList(names);" - ) - - async def _top_patent_authors(institution_id: str) -> list[TopAuthor]: client = OrgPatentsSearchClient() authors = await client.top_authors_by_institution( @@ -693,6 +826,54 @@ async def _top_patent_authors(institution_id: str) -> list[TopAuthor]: ] +async def _top_eu_project_publication_authors() -> list[TopAuthor]: + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_FP7_PUBLICATIONS, + body={ + "size": 0, + "aggs": { + "authors": { + "terms": { + "script": { + "lang": "painless", + "source": _cordis_publication_authors_script(), + }, + "size": TOP_AUTHOR_LIMIT, + "order": {"_count": "desc"}, + } + } + }, + }, + cluster=ESCluster.INSE, + ) + return [ + TopAuthor( + name=str(bucket["key"]), + count=int(bucket.get("doc_count", 0)), + ) + for bucket in ( + response.get("aggregations", {}).get("authors", {}).get("buckets", []) + ) + if str(bucket.get("key", "")).strip() + ] + + +def _cordis_publication_authors_script() -> str: + return ( + "def names = new HashSet(); " + "def source = params['_source']; " + "def value = source.containsKey('authors') ? source['authors'] " + " : (source.containsKey('Authors') ? source['Authors'] : null); " + "if (value instanceof String && value.length() > 0) { " + " for (name in value.splitOnToken(';')) { " + " def trimmed = name.trim(); " + " if (trimmed.length() > 0) { names.add(trimmed); } " + " } " + "} " + "return new ArrayList(names);" + ) + + async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]: if not authors: return [] diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index ca3288b8..12c74d02 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 ( get_dashboard_statistics, get_top_authors, get_topic_heatmap, + get_topic_word_cloud, ) from inse.model import ESCluster, ESIndex @@ -98,7 +99,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): @pytest.mark.anyio -async def test_top_authors_maps_works_and_dfg_project_aggregations(): +async def test_top_authors_maps_works_patents_and_news_without_project_queries(): async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return { @@ -131,11 +132,14 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): } } } - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: + if kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS: return { "aggregations": { - "people": { - "buckets": [{"key": "Grace Example", "doc_count": 3}] + "authors": { + "buckets": [ + {"key": "Grace Example", "doc_count": 8}, + {"key": "Ada Example", "doc_count": 5}, + ] } } } @@ -145,9 +149,6 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search, patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock( return_value=[ @@ -162,16 +163,15 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): "name": "Ada Example", "count": 42, } - assert result.projects[0].model_dump() == { - "id": "A2", - "name": "Grace Example", - "count": 3, - } assert result.patents[0].model_dump() == { "id": "A1", "name": "Ada Example", "count": 4, } + assert [author.model_dump() for author in result.eu_projects] == [ + {"id": None, "name": "Grace Example", "count": 8}, + {"id": None, "name": "Ada Example", "count": 5}, + ] assert result.news[0].model_dump() == { "id": "A1", "name": "Ada Example", @@ -183,133 +183,16 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): if call.kwargs["index"] in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1} ] - assert len(project_calls) == 1 - assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL - assert project_calls[0].kwargs["body"]["query"]["bool"][ - "minimum_should_match" - ] == 1 - assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][ - "people" - ]["terms"]["script"]["source"] - - -@pytest.mark.anyio -async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): - async def search(**kwargs): - if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: - return {"hits": {"hits": []}} - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: - return { - "aggregations": { - "people": { - "buckets": [{"key": "Project Person", "doc_count": 9}] - } - } - } - return {"aggregations": {"people": {"buckets": []}}} - - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), - ): - result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") - - assert result.projects[0].model_dump() == { - "id": None, - "name": "Project Person", - "count": 9, - } - - -@pytest.mark.anyio -async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count(): - async def search(**kwargs): - if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: - return {"hits": {"hits": []}} - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: - return { - "aggregations": { - "people": { - "buckets": [ - {"key": f"Project Person {count}", "doc_count": count} - for count in range(1, 12) - ] - } - } - } - return {"aggregations": {"people": {"buckets": []}}} - - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), - ): - result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") - - assert [author.count for author in result.projects] == list(range(11, 1, -1)) - assert result.projects[0].name == "Project Person 11" - assert len(result.projects) == 10 - - -@pytest.mark.anyio -async def test_top_authors_combines_dfg_involved_people_case_insensitively(): - async def search(**kwargs): - if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: - return { - "hits": { - "hits": [ - { - "_source": { - "id": "https://openalex.org/A1", - "display_name": "Ada Example", - "works_count": 1, - "counts_by_year": [], - } - } - ] - } - } - if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL: - return { - "aggregations": { - "people": { - "buckets": [ - {"key": "Ada Example", "doc_count": 2}, - {"key": "ada example", "doc_count": 3}, - {"key": "DFG Person", "doc_count": 4}, - ] - } - } - } - return {"aggregations": {"authors": {"buckets": []}}} - - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), - ): - result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") - - assert [author.model_dump() for author in result.projects] == [ - {"id": "A1", "name": "Ada Example", "count": 5}, - {"id": None, "name": "DFG Person", "count": 4}, + assert project_calls == [] + eu_calls = [ + call + for call in mocked_search.await_args_list + if call.kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS ] + assert len(eu_calls) == 1 + terms = eu_calls[0].kwargs["body"]["aggs"]["authors"]["terms"] + assert terms["size"] == 10 + assert "splitOnToken(';')" in terms["script"]["source"] @pytest.mark.anyio @@ -335,9 +218,6 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): with patch( "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -345,7 +225,7 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") assert result.works[0].name == "Ada Example" - assert result.projects == [] + assert result.eu_projects == [] assert result.patents == [] assert result.news == [] @@ -448,6 +328,42 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): ] }, }, + "subfields": { + "buckets": [ + { + "key": "https://openalex.org/subfields/1702", + "subfield_name": { + "buckets": [ + { + "key": "Artificial Intelligence", + "doc_count": 7, + } + ] + }, + "works": { + "doc_count": 7, + }, + "topics": { + "buckets": [ + { + "key": "https://openalex.org/T100", + "topic_name": { + "buckets": [ + { + "key": "Machine learning", + "doc_count": 6, + } + ] + }, + "works": { + "doc_count": 6, + }, + } + ] + }, + } + ] + }, } ] } @@ -490,6 +406,22 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): {"year": 2023, "count": 4, "share": 0.4}, {"year": 2024, "count": 8, "share": 0.4}, ], + "subfields": [ + { + "id": "https://openalex.org/subfields/1702", + "name": "Artificial Intelligence", + "total": 7, + "values": [], + "topics": [ + { + "id": "https://openalex.org/T100", + "name": "Machine learning", + "total": 6, + "values": [], + } + ], + } + ], } body = mocked_search.await_args_list[0].kwargs["body"] assert body["query"]["bool"]["must"][0]["nested"]["query"]["term"] == { @@ -499,6 +431,22 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): body["aggs"]["topics_nested"]["aggs"]["fields"]["terms"]["field"] == "topics.field.id" ) + assert ( + body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"] + ["subfields"]["terms"]["field"] + == "topics.subfield.id" + ) + assert ( + body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"] + ["subfields"]["aggs"]["topics"]["terms"]["field"] + == "topics.id" + ) + subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"] + assert "aggs" not in subfield_aggs["subfields"]["aggs"]["works"] + assert ( + "aggs" + not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"] + ) @pytest.mark.anyio @@ -531,6 +479,58 @@ async def test_topic_heatmap_defaults_to_last_five_years(): } +@pytest.mark.anyio +async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic(): + response = { + "aggregations": { + "topics_nested": { + "topics": { + "buckets": [ + { + "key": "https://openalex.org/T100", + "topic_name": {"buckets": [{"key": "Selected topic"}]}, + "works": {"doc_count": 9}, + }, + { + "key": "https://openalex.org/T200", + "topic_name": {"buckets": [{"key": "Related topic"}]}, + "works": {"doc_count": 6}, + }, + ] + } + } + } + } + with patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as mocked_search: + result = await get_topic_word_cloud( + institution_id=ORG_INSTITUTION_ID, + topic_id="https://openalex.org/T100", + from_year=2023, + to_year=2024, + ) + + assert result.model_dump() == { + "topic_id": "https://openalex.org/T100", + "words": [ + { + "id": "https://openalex.org/T200", + "name": "Related topic", + "count": 6, + } + ], + } + body = mocked_search.await_args.kwargs["body"] + assert body["query"]["bool"]["must"][1]["nested"]["query"]["term"] == { + "topics.id": "https://openalex.org/T100" + } + assert body["query"]["bool"]["filter"] == [ + {"range": {"publication_year": {"gte": 2023, "lte": 2024}}} + ] + + def test_get_dashboard_organization_uses_effective_organization(): engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) SQLModel.metadata.create_all(engine) diff --git a/webapp/src/app/api/model/topAuthorStatistics.ts b/webapp/src/app/api/model/topAuthorStatistics.ts index 1c912edb..3d06243b 100644 --- a/webapp/src/app/api/model/topAuthorStatistics.ts +++ b/webapp/src/app/api/model/topAuthorStatistics.ts @@ -12,7 +12,7 @@ import { TopAuthor } from './topAuthor'; export interface TopAuthorStatistics { institution_id: string; works: Array; - projects: Array; + eu_projects: Array; patents: Array; news: Array; } diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 828fd7ee..aa23dd73 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -32,7 +32,7 @@ export interface TopAuthor { export interface TopAuthorStatistics { institution_id: string; works: TopAuthor[]; - projects: TopAuthor[]; + eu_projects: TopAuthor[]; patents: TopAuthor[]; news: TopAuthor[]; } @@ -48,6 +48,22 @@ export interface TopicHeatmapField { name: string; total: number; values: TopicHeatmapValue[]; + subfields: TopicHeatmapSubfield[]; +} + +export interface TopicHeatmapSubfield { + id: string; + name: string; + total: number; + values: TopicHeatmapValue[]; + topics: TopicHeatmapTopic[]; +} + +export interface TopicHeatmapTopic { + id: string; + name: string; + total: number; + values: TopicHeatmapValue[]; } export interface TopicHeatmap { @@ -57,6 +73,17 @@ export interface TopicHeatmap { fields: TopicHeatmapField[]; } +export interface TopicWordCloudWord { + id: string; + name: string; + count: number; +} + +export interface TopicWordCloud { + topic_id: string; + words: TopicWordCloudWord[]; +} + @Injectable({ providedIn: 'root' }) export class DashboardStatisticsService { private readonly httpClient = inject(HttpClient); @@ -122,4 +149,18 @@ export class DashboardStatisticsService { { params }, ); } + + getTopicWordCloud( + topicId: string, + fromYear?: number, + toYear?: number, + ): Observable { + const params: Record = { topicId }; + if (fromYear !== undefined) params['from_year'] = fromYear; + if (toYear !== undefined) params['to_year'] = toYear; + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-wordcloud`, + { params }, + ); + } } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index ea16ab26..b91ee6df 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -105,6 +105,11 @@ export class DashboardComponent implements OnInit { icon: 'menu_book', entries: this.topAuthors?.works ?? [], }, + { + title: 'EU-Projekte', + icon: 'public', + entries: this.topAuthors?.eu_projects ?? [], + }, { title: 'Patente', icon: 'description', diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html index d443e1a1..e4b99420 100644 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html +++ b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html @@ -1,5 +1,9 @@ @if (heatmap?.fields?.length) { -
+
} @else {

{{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }} diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts index d124c1d4..981236db 100644 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts +++ b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts @@ -1,8 +1,13 @@ -import { Component, Input, OnChanges } from '@angular/core'; +import { Component, Input, OnChanges, inject } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; import { TopicHeatmap } from '../dashboard-statistics.service'; +import { + TopicWordCloudDialogComponent, + TopicWordCloudDialogData, +} from '../topic-wordcloud-dialog/topic-wordcloud-dialog.component'; @Component({ selector: 'app-topic-heatmap', @@ -11,6 +16,7 @@ import { TopicHeatmap } from '../dashboard-statistics.service'; styleUrl: './topic-heatmap.component.scss', }) export class TopicHeatmapComponent implements OnChanges { + private readonly dialog = inject(MatDialog); @Input() heatmap?: TopicHeatmap; @Input() loading = false; @@ -32,6 +38,26 @@ export class TopicHeatmapComponent implements OnChanges { this.options = this.buildOptions(); } + onChartClick(event: any): void { + const data = event?.data; + if (!data?.id || !data?.subfieldName || data?.children?.length) return; + this.dialog.open( + TopicWordCloudDialogComponent, + { + width: '85vw', + maxWidth: '92vw', + data: { + topicId: data.id, + topicName: data.name, + fieldName: data.fieldName, + subfieldName: data.subfieldName, + fromYear: this.heatmap?.years.at(0), + toYear: this.heatmap?.years.at(-1), + }, + }, + ); + } + private buildOptions(): EChartsOption { const fields = this.heatmap?.fields ?? []; const data = fields.map((field) => ({ @@ -47,12 +73,22 @@ export class TopicHeatmapComponent implements OnChanges { lineHeight: 18, overflow: 'truncate' as const, }, - children: field.values - .filter((value) => value.count > 0) - .map((value) => ({ - name: String(value.year), - value: value.count, - share: value.share, + children: (field.subfields ?? []) + .filter((subfield) => subfield.total > 0) + .map((subfield) => ({ + id: subfield.id, + name: subfield.name, + value: subfield.total, + fieldName: field.name, + children: (subfield.topics ?? []) + .filter((topic) => topic.total > 0) + .map((topic) => ({ + id: topic.id, + name: topic.name, + value: topic.total, + fieldName: field.name, + subfieldName: subfield.name, + })), })), })); @@ -60,11 +96,13 @@ export class TopicHeatmapComponent implements OnChanges { tooltip: { formatter: (params: any) => { const count = Number(params.value ?? 0); - const share = - typeof params.data?.share === 'number' - ? `
Anteil im Jahr: ${(params.data.share * 100).toFixed(1)}%` - : ''; - return `${params.name}
${count} Publikationen${share}`; + const field = params.data?.fieldName + ? `
Field: ${params.data.fieldName}` + : ''; + const subfield = params.data?.subfieldName + ? `
Subfield: ${params.data.subfieldName}` + : ''; + return `${params.name}${field}${subfield}
${count} Publikationen`; }, }, series: [ diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html new file mode 100644 index 00000000..23304379 --- /dev/null +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html @@ -0,0 +1,37 @@ +

+
+

{{ data.topicName }}

+

+ {{ data.fieldName }} + @if (data.subfieldName) { + · {{ data.subfieldName }} + } +

+
+ +
+ + + @if (loading) { +
Verwandte Themen werden geladen ...
+ } @else if (loadFailed) { +
Wordcloud konnte nicht geladen werden.
+ } @else if (words.length) { +
+ @for (word of words; track word.id) { + + {{ word.name }} + + } +
+ } @else { +
Keine verwandten Themen gefunden.
+ } +
diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss new file mode 100644 index 00000000..ad055bd2 --- /dev/null +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss @@ -0,0 +1,49 @@ +.dialog-title { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + + h2 { + margin: 0; + } + + p { + margin: 4px 0 0; + color: #64748b; + font-size: 0.875rem; + } +} + +mat-dialog-content { + min-height: 330px; +} + +.word-cloud-chart { + min-height: 300px; + display: flex; + flex-wrap: wrap; + align-content: center; + align-items: baseline; + justify-content: center; + gap: 12px 18px; + padding: 24px; + border-radius: 12px; + background: linear-gradient(145deg, #f8fafc, #ffffff); +} + +.word-cloud-word { + line-height: 1.1; + text-align: center; +} + +.word-cloud-state { + min-height: 300px; + display: grid; + place-items: center; + color: #64748b; + + &.error { + color: #b91c1c; + } +} diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts new file mode 100644 index 00000000..0ce09141 --- /dev/null +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts @@ -0,0 +1,102 @@ +import { CommonModule } from '@angular/common'; +import { Component, DestroyRef, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { + MAT_DIALOG_DATA, + MatDialogModule, +} from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; + +import { + DashboardStatisticsService, + TopicWordCloudWord, +} from '../dashboard-statistics.service'; + +export interface TopicWordCloudDialogData { + topicId: string; + topicName: string; + fieldName?: string; + subfieldName?: string; + fromYear?: number; + toYear?: number; +} + +interface DisplayWord extends TopicWordCloudWord { + color: string; + fontSize: number; + fontWeight: number; +} + +@Component({ + selector: 'app-topic-wordcloud-dialog', + standalone: true, + imports: [CommonModule, MatButtonModule, MatDialogModule, MatIconModule], + templateUrl: './topic-wordcloud-dialog.component.html', + styleUrl: './topic-wordcloud-dialog.component.scss', +}) +export class TopicWordCloudDialogComponent { + readonly data = inject(MAT_DIALOG_DATA); + private readonly statisticsService = inject(DashboardStatisticsService); + private readonly destroyRef = inject(DestroyRef); + + words: DisplayWord[] = []; + loading = true; + loadFailed = false; + + private readonly colors = [ + '#2563eb', + '#059669', + '#d97706', + '#dc2626', + '#7c3aed', + '#0284c7', + '#ea580c', + '#4f46e5', + '#0f766e', + '#be123c', + ]; + + constructor() { + this.statisticsService + .getTopicWordCloud( + this.data.topicId, + this.data.fromYear, + this.data.toYear, + ) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (response) => { + this.words = this.buildWords(response.words); + this.loading = false; + }, + error: () => { + this.loading = false; + this.loadFailed = true; + }, + }); + } + + private buildWords(words: TopicWordCloudWord[]): DisplayWord[] { + if (!words.length) return []; + const values = words.map((word) => word.count); + const minimum = Math.min(...values); + const maximum = Math.max(...values); + const scaled = words.map((word, index) => { + const intensity = + maximum === minimum ? 1 : (word.count - minimum) / (maximum - minimum); + return { + ...word, + color: this.colors[index % this.colors.length], + fontSize: Math.round(14 + intensity * 24), + fontWeight: intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400, + }; + }); + const centred: DisplayWord[] = []; + scaled.forEach((word, index) => { + if (index % 2 === 0) centred.push(word); + else centred.unshift(word); + }); + return centred; + } +} -- 2.56.1 From db3d984125295c0acdb1cfb51cacdae245cf3dc7 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Mon, 20 Jul 2026 17:33:09 +0200 Subject: [PATCH 2/6] fix ui of treemap --- service/src/main/inse/dashboard/service.py | 52 +++- .../src/main/inse/dashboard/test_service.py | 46 +-- .../main/inse/integrations/elasticsearch.py | 1 + service/src/main/inse/model.py | 1 + .../topic-heatmap/topic-heatmap.component.ts | 185 +++++++---- .../topic-wordcloud-dialog.component.html | 115 +++++-- .../topic-wordcloud-dialog.component.scss | 293 +++++++++++++++++- .../ui/topic-chip/topic-chip.component.ts | 7 +- 8 files changed, 566 insertions(+), 134 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 39bf6f91..5df7eb3e 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -36,18 +36,6 @@ TOPIC_HEATMAP_YEARS = 5 WorksPeriod = Literal["all_time", "last_5_years"] logger = logging.getLogger(__name__) -DFG_INSTITUTION_FIELDS = [ - "Antragstellende Institution", - "Mitantragstellende Institution", - "Beteiligte Einrichtung", - "Beteiligte Hochschule", - "Beteiligte Institution", - "IGK-Partnerinstitution", - "Partnerorganisation", - "Unternehmen", -] - - def _total(response: dict[str, Any]) -> int: total = response.get("hits", {}).get("total", 0) if isinstance(total, dict): @@ -249,7 +237,7 @@ async def get_dashboard_dfg_projects( normalized_id = _normalize_institution_id(institution_id) aliases = await _institution_aliases(normalized_id, organization_name) response = await elasticsearch.search( - index=ESIndex.PROJECTS_DFG_ALL, + index=ESIndex.DFG_PROJECTS_V2, query=_dfg_institution_query(aliases), size=0, track_total_hits=True, @@ -317,8 +305,42 @@ def _dfg_institution_query(aliases: list[str]) -> dict[str, Any]: return { "bool": { "should": [ - _alias_match_query(field, aliases) - for field in DFG_INSTITUTION_FIELDS + { + "nested": { + "path": "institutions", + "query": { + "bool": { + "should": [ + _alias_match_query( + "institutions.institute_name_de", aliases + ), + _alias_match_query( + "institutions.institute_name_en", aliases + ), + ], + "minimum_should_match": 1, + } + }, + } + }, + { + "nested": { + "path": "persons", + "query": { + "bool": { + "should": [ + _alias_match_query( + "persons.affiliation_de", aliases + ), + _alias_match_query( + "persons.affiliation_en", aliases + ), + ], + "minimum_should_match": 1, + } + }, + } + }, ], "minimum_should_match": 1, } diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 12c74d02..cec617e8 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -58,20 +58,25 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } calls = mocked_search.await_args_list - assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index - assert calls[0].kwargs["query"]["nested"]["query"]["term"] == { + calls_by_index = {call.kwargs["index"]: call for call in calls} + works_call = calls_by_index[config.settings.openalex_works_search_index] + authors_call = calls_by_index[ESIndex.OPENALEX_AUTHORS] + eu_call = calls_by_index[ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD] + bmbf_call = calls_by_index[ESIndex.PROJECTS_BUND_V1] + dfg_call = calls_by_index[ESIndex.DFG_PROJECTS_V2] + assert works_call.kwargs["query"]["nested"]["query"]["term"] == { "authorships.institutions.id": ORG_INSTITUTION_ID } - assert calls[1].kwargs["query"]["nested"]["query"]["term"] == { - "affiliations.institution.id": ORG_INSTITUTION_ID + assert authors_call.kwargs["query"]["bool"]["should"][0]["bool"]["filter"][ + 0 + ]["nested"]["query"]["match_phrase"] == { + "last_known_institutions.id": ORG_INSTITUTION_ID } - assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:]) - assert [call.kwargs["index"] for call in calls[2:]] == [ - ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, - ESIndex.PROJECTS_BUND_V1, - ESIndex.PROJECTS_DFG_ALL, - ] - assert calls[2].kwargs["body"]["query"] == { + assert all( + call.kwargs["cluster"] == ESCluster.INSE + for call in [eu_call, bmbf_call, dfg_call] + ) + assert eu_call.kwargs["body"]["query"] == { "terms": { "name.keyword": [ "EXAMPLE ORG", @@ -80,22 +85,25 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): ] } } - assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1 - assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == { + assert bmbf_call.kwargs["query"]["bool"]["minimum_should_match"] == 1 + assert bmbf_call.kwargs["query"]["bool"]["should"][0]["match"] == { "Zuwendungsempfänger": { "query": "Example Org", "operator": "and", } } - assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1 - assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][ - "match" - ] == { - "Antragstellende Institution": { + dfg_query = dfg_call.kwargs["query"] + assert dfg_query["bool"]["minimum_should_match"] == 1 + assert dfg_query["bool"]["should"][0]["nested"]["path"] == "institutions" + assert dfg_query["bool"]["should"][0]["nested"]["query"]["bool"]["should"][ + 0 + ]["bool"]["should"][0]["match"] == { + "institutions.institute_name_de": { "query": "Example Org", "operator": "and", } } + assert dfg_query["bool"]["should"][1]["nested"]["path"] == "persons" @pytest.mark.anyio @@ -181,7 +189,7 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries() call for call in mocked_search.await_args_list if call.kwargs["index"] - in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1} + in {ESIndex.DFG_PROJECTS_V2, ESIndex.PROJECTS_BUND_V1} ] assert project_calls == [] eu_calls = [ diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index b58065cf..77afd124 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -101,6 +101,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, ESIndex.PROJECTS_BUND_V1, ESIndex.PROJECTS_DFG_ALL, + ESIndex.DFG_PROJECTS_V2, }: return ESCluster.INSE else: diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index a417cb81..5265720b 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -61,6 +61,7 @@ class ESIndex(StrEnum): PROJECTS_BUND_V1 = "projects_bund_v1" PROJECTS_DFG_ALL = "projects_dfg_all" + DFG_PROJECTS_V2 = "dfg_projects_2.0" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts index 981236db..34317472 100644 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts +++ b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts @@ -3,6 +3,7 @@ import { MatDialog } from '@angular/material/dialog'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { TopicHeatmap } from '../dashboard-statistics.service'; import { TopicWordCloudDialogComponent, @@ -17,22 +18,11 @@ import { }) export class TopicHeatmapComponent implements OnChanges { private readonly dialog = inject(MatDialog); + private readonly fieldColorOpacity = 0.78; @Input() heatmap?: TopicHeatmap; @Input() loading = false; options: EChartsOption = {}; - private readonly colors = [ - '#2563eb', - '#059669', - '#d97706', - '#dc2626', - '#7c3aed', - '#0284c7', - '#ea580c', - '#4f46e5', - '#0f766e', - '#be123c', - ]; ngOnChanges(): void { this.options = this.buildOptions(); @@ -60,49 +50,118 @@ export class TopicHeatmapComponent implements OnChanges { private buildOptions(): EChartsOption { const fields = this.heatmap?.fields ?? []; - const data = fields.map((field) => ({ - id: field.id, - name: field.name, - value: field.total || this.totalCount(field.values), - label: { - show: true, - formatter: (params: any) => - `${params.name}\n${this.formatCount(params.value)}`, - color: '#ffffff', - fontWeight: 700, - lineHeight: 18, - overflow: 'truncate' as const, - }, - children: (field.subfields ?? []) - .filter((subfield) => subfield.total > 0) - .map((subfield) => ({ - id: subfield.id, - name: subfield.name, - value: subfield.total, - fieldName: field.name, - children: (subfield.topics ?? []) - .filter((topic) => topic.total > 0) - .map((topic) => ({ - id: topic.id, - name: topic.name, - value: topic.total, - fieldName: field.name, - subfieldName: subfield.name, - })), - })), - })); + const data = fields.map((field) => { + const fieldColor = topicHierarchyColor({ + field_id: field.id, + field_name: field.name, + }); + + return { + id: field.id, + name: field.name, + value: field.total || this.totalCount(field.values), + itemStyle: { + color: fieldColor, + opacity: this.fieldColorOpacity, + }, + emphasis: { + itemStyle: { + color: fieldColor, + opacity: this.fieldColorOpacity, + }, + }, + label: { + show: true, + formatter: (params: any) => + `${params.name}\n${this.formatCount(params.value)}`, + color: '#ffffff', + fontWeight: 700, + lineHeight: 18, + overflow: 'truncate' as const, + }, + children: (field.subfields ?? []) + .filter((subfield) => subfield.total > 0) + .map((subfield) => ({ + id: subfield.id, + name: subfield.name, + value: subfield.total, + fieldName: field.name, + itemStyle: { + color: fieldColor, + opacity: this.fieldColorOpacity, + }, + emphasis: { + itemStyle: { + color: fieldColor, + opacity: this.fieldColorOpacity, + }, + }, + children: (subfield.topics ?? []) + .filter((topic) => topic.total > 0) + .map((topic) => ({ + id: topic.id, + name: topic.name, + value: topic.total, + fieldName: field.name, + subfieldName: subfield.name, + itemStyle: { + color: fieldColor, + opacity: this.fieldColorOpacity, + }, + emphasis: { + itemStyle: { + color: fieldColor, + opacity: this.fieldColorOpacity, + }, + }, + })), + })), + }; + }); return { tooltip: { + trigger: 'item', + confine: true, + backgroundColor: '#ffffff', + borderColor: '#d8cafe', + borderWidth: 1, + padding: 0, + extraCssText: + 'max-width: 360px; border-radius: 12px; box-shadow: 0 14px 36px rgba(16, 26, 61, 0.18);', formatter: (params: any) => { const count = Number(params.value ?? 0); - const field = params.data?.fieldName - ? `
Field: ${params.data.fieldName}` + const name = this.escapeHtml(String(params.name ?? '')); + const fieldName = params.data?.fieldName + ? this.escapeHtml(String(params.data.fieldName)) : ''; - const subfield = params.data?.subfieldName - ? `
Subfield: ${params.data.subfieldName}` + const subfieldName = params.data?.subfieldName + ? this.escapeHtml(String(params.data.subfieldName)) : ''; - return `${params.name}${field}${subfield}
${count} Publikationen`; + const hierarchy = [fieldName, subfieldName] + .filter(Boolean) + .map( + (item) => + `${item}`, + ) + .join('›'); + + return ` +
+ ${ + hierarchy + ? `
${hierarchy}
` + : '' + } +
${name}
+
+ ${this.formatCount(count)} + Publikationen +
+
+ Klicken, um diesen Bereich zu vergrößern +
+
`; }, }, series: [ @@ -141,8 +200,6 @@ export class TopicHeatmapComponent implements OnChanges { }, }, }, - color: this.colors, - colorMappingBy: 'id', label: { show: true, formatter: (params: any) => @@ -166,7 +223,6 @@ export class TopicHeatmapComponent implements OnChanges { }, levels: [ { - color: this.colors, label: { show: true, position: 'inside', @@ -181,7 +237,6 @@ export class TopicHeatmapComponent implements OnChanges { }, }, { - color: this.colors, label: { show: true, position: 'inside', @@ -196,7 +251,6 @@ export class TopicHeatmapComponent implements OnChanges { }, }, { - colorSaturation: [0.45, 0.78], label: { show: true, formatter: (params: any) => @@ -224,9 +278,18 @@ export class TopicHeatmapComponent implements OnChanges { left: 8, animationDurationUpdate: 450, emphasis: { - focus: 'self', label: { color: '#ffffff', + fontSize: 15, + fontWeight: 800, + textShadowBlur: 4, + textShadowColor: 'rgba(15, 23, 42, 0.45)', + }, + itemStyle: { + borderColor: '#ffffff', + borderWidth: 5, + shadowBlur: 18, + shadowColor: 'rgba(15, 23, 42, 0.35)', }, }, itemStyle: { @@ -247,4 +310,18 @@ export class TopicHeatmapComponent implements OnChanges { private formatCount(value: unknown): string { return Number(value ?? 0).toLocaleString('de-DE'); } + + private escapeHtml(value: string): string { + return value.replace( + /[&<>'"]/g, + (character) => + ({ + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"', + })[character] ?? character, + ); + } } diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html index 23304379..8351d069 100644 --- a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.html @@ -1,37 +1,98 @@
-
-

{{ data.topicName }}

-

- {{ data.fieldName }} - @if (data.subfieldName) { - · {{ data.subfieldName }} - } -

+
+
+ Topic Insights +

Keyword Wordcloud

+

Die wichtigsten Begriffe zum ausgewählten Forschungsthema

+
-
- @if (loading) { -
Verwandte Themen werden geladen ...
- } @else if (loadFailed) { -
Wordcloud konnte nicht geladen werden.
- } @else if (words.length) { -
- @for (word of words; track word.id) { - - {{ word.name }} - +
+
+ + + Field + {{ data.fieldName || '–' }} + +
+ +
+ + + Subfield + {{ data.subfieldName || '–' }} + +
+ +
+ + + Topic + {{ data.topicName }} + +
+
+ +
+
+
+

Top Keywords

+

Die Schriftgröße entspricht der Anzahl der Publikationen.

+
+ @if (!loading && !loadFailed && words.length) { + {{ words.length }} Begriffe }
- } @else { -
Keine verwandten Themen gefunden.
- } + + @if (loading) { +
+ + Wordcloud wird erstellt + Die wichtigsten Keywords werden geladen … +
+ } @else if (loadFailed) { +
+ + Wordcloud nicht verfügbar + Die Keywords konnten nicht geladen werden. +
+ } @else if (words.length) { +
+ @for (word of words; track word.id) { + + {{ word.name }} + + } +
+ } @else { +
+ + Keine Keywords gefunden + Für dieses Topic sind im gewählten Zeitraum keine Daten vorhanden. +
+ } +
diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss index ad055bd2..1b66b75b 100644 --- a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.scss @@ -2,48 +2,307 @@ display: flex; align-items: flex-start; justify-content: space-between; - gap: 16px; + gap: 24px; + padding: 24px 28px 20px; + border-bottom: 1px solid var(--sg-border, #dde5f2); + background: linear-gradient(135deg, #ffffff 52%, #f6f0ff 100%); h2 { - margin: 0; + margin: 1px 0 3px; + color: var(--sg-text, #101a3d); + font-family: 'Montserrat', sans-serif; + font-size: 1.375rem; + font-weight: 700; + line-height: 1.25; } p { - margin: 4px 0 0; - color: #64748b; - font-size: 0.875rem; + margin: 0; + color: var(--sg-text-muted, #64708f); + font-size: 0.8125rem; + font-weight: 400; + } +} + +.dialog-heading { + display: flex; + align-items: center; +} + +.dialog-eyebrow { + display: block; + color: #7255d9; + font-size: 0.6875rem; + font-weight: 700; + letter-spacing: 0.08em; + line-height: 1.2; + text-transform: uppercase; +} + +.dialog-close { + flex: 0 0 auto; + color: var(--sg-text-muted, #64708f); + + &:hover { + background: #f1f3f7; + color: var(--sg-text, #101a3d); } } mat-dialog-content { - min-height: 330px; + min-height: 410px; + padding: 20px 28px 28px !important; + background: #ffffff; +} + +.topic-context-card { + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + gap: 12px; + margin-bottom: 18px; + padding: 12px; + border: 1px solid var(--sg-border, #dde5f2); + border-radius: 12px; + background: var(--sg-surface-muted, #f7f9ff); +} + +.topic-context-item { + display: flex; + min-width: 0; + align-items: center; + gap: 10px; + padding: 5px 6px; +} + +.topic-context-icon { + display: grid; + width: 34px; + height: 34px; + flex: 0 0 34px; + place-items: center; + border-radius: 9px; + + mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } +} + +.topic-context-icon--field { + border: 1px solid #bdd4ff; + background: #f0f6ff; + color: #0b63ce; +} + +.topic-context-icon--subfield { + border: 1px solid #bdebcf; + background: #effaf3; + color: #24834f; +} + +.topic-context-icon--topic { + border: 1px solid #d8cafe; + background: #f6f0ff; + color: #7255d9; +} + +.topic-context-copy { + display: flex; + min-width: 0; + flex-direction: column; + gap: 2px; + + strong { + overflow: hidden; + color: #334155; + font-size: 0.8125rem; + font-weight: 600; + line-height: 1.35; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +.topic-context-item--topic strong { + color: #7255d9; +} + +.topic-context-label { + color: var(--sg-text-soft, #8a95b3); + font-size: 0.625rem; + font-weight: 700; + letter-spacing: 0.07em; + line-height: 1.2; + text-transform: uppercase; +} + +.topic-context-arrow { + width: 18px; + height: 18px; + color: #a8b2c8; + font-size: 18px; +} + +.word-cloud-panel { + overflow: hidden; + border: 1px solid var(--sg-border, #dde5f2); + border-radius: 16px; + background: #ffffff; + box-shadow: var(--sg-shadow-sm); +} + +.word-cloud-panel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 14px 18px; + border-bottom: 1px solid #e8edf5; + + h3 { + margin: 0 0 2px; + color: var(--sg-text, #101a3d); + font-family: 'Montserrat', sans-serif; + font-size: 0.9375rem; + font-weight: 700; + } + + p { + margin: 0; + color: var(--sg-text-muted, #64708f); + font-size: 0.75rem; + } +} + +.word-count { + flex: 0 0 auto; + padding: 5px 9px; + border: 1px solid #d8cafe; + border-radius: 999px; + background: #f6f0ff; + color: #7255d9; + font-size: 0.6875rem; + font-weight: 700; } .word-cloud-chart { - min-height: 300px; display: flex; + min-height: 280px; flex-wrap: wrap; align-content: center; align-items: baseline; justify-content: center; - gap: 12px 18px; - padding: 24px; - border-radius: 12px; - background: linear-gradient(145deg, #f8fafc, #ffffff); + gap: 14px 20px; + padding: 30px 34px; + background: + radial-gradient(circle at 15% 20%, rgba(114, 85, 217, 0.06), transparent 28%), + radial-gradient(circle at 85% 75%, rgba(11, 99, 206, 0.05), transparent 30%), + #ffffff; } .word-cloud-word { + padding: 3px 5px; + border-radius: 6px; + cursor: help; line-height: 1.1; text-align: center; + transition: + transform 150ms ease, + background-color 150ms ease; + + &:hover { + background: rgba(241, 243, 247, 0.9); + transform: translateY(-2px); + } } .word-cloud-state { - min-height: 300px; - display: grid; - place-items: center; - color: #64748b; + display: flex; + min-height: 280px; + align-items: center; + justify-content: center; + flex-direction: column; + gap: 6px; + padding: 24px; + color: var(--sg-text-muted, #64708f); + text-align: center; - &.error { - color: #b91c1c; + strong { + margin-top: 4px; + color: var(--sg-text, #101a3d); + font-size: 0.9375rem; + } + + > span:last-child { + font-size: 0.8125rem; + } +} + +.state-icon { + display: grid; + width: 46px; + height: 46px; + place-items: center; + border-radius: 50%; + background: #f1f3f7; + color: #64708f; +} + +.state-icon--loading { + background: #f6f0ff; + color: #7255d9; + animation: state-pulse 1.4s ease-in-out infinite; +} + +.word-cloud-state--error .state-icon { + background: #fff1f5; + color: #d12f61; +} + +@keyframes state-pulse { + 50% { + box-shadow: 0 0 0 8px rgba(114, 85, 217, 0.08); + transform: scale(1.04); + } +} + +@media (max-width: 700px) { + .dialog-title { + padding: 20px; + } + + mat-dialog-content { + padding: 16px 20px 20px !important; + } + + .topic-context-card { + grid-template-columns: 1fr; + gap: 4px; + } + + .topic-context-arrow { + display: none; + } + + .topic-context-copy strong { + white-space: normal; + } + + .word-cloud-chart { + min-height: 240px; + gap: 10px 14px; + padding: 24px 18px; + } +} + +@media (prefers-reduced-motion: reduce) { + .state-icon--loading { + animation: none; + } + + .word-cloud-word { + transition: none; } } diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts index 54f5060c..896b0aca 100644 --- a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts @@ -22,13 +22,16 @@ export type TopicChipColor = TopicChipPaletteColor | string; export type TopicChipSize = 'normal' | 'mini'; export type TopicChipTooltipTarget = 'label' | 'button'; -interface TopicChipColorTokens { +export interface TopicChipColorTokens { border: string; background: string; color: string; } -const TOPIC_CHIP_COLORS: Record = { +export const TOPIC_CHIP_COLORS: Record< + TopicChipPaletteColor, + TopicChipColorTokens +> = { purple: { border: '#d8cafe', background: '#f6f0ff', -- 2.56.1 From 697dacea81624be48e6107858efc8659c51c0f49 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 21 Jul 2026 13:51:52 +0200 Subject: [PATCH 3/6] Replace treemap period options with year slider --- .../dashboard/dashboard.component.html | 52 +++------------ .../dashboard/dashboard.component.scss | 64 +------------------ .../modules/dashboard/dashboard.component.ts | 59 ++++++----------- 3 files changed, 31 insertions(+), 144 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 4b827cb2..73a495ca 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -115,49 +115,15 @@

Field Treemap

Publikationen Ihrer Organisation nach Field.

-
-
- - - -
- - +
+ +
diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 565fa58f..66b3f245 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -129,68 +129,8 @@ } } - .topic-treemap-period-controls { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 0.65rem; - - label { - display: inline-flex; - align-items: center; - gap: 0.35rem; - color: #475569; - font-size: 0.9rem; - font-weight: 600; - } - - input { - width: 5.5rem; - padding: 0.45rem 0.55rem; - border: 1px solid #cbd5e1; - border-radius: 6px; - color: #0f172a; - font: inherit; - - &:focus { - border-color: #93c5fd; - outline: 3px solid #bfdbfe; - outline-offset: 0; - } - } - } - - .topic-treemap-period-toggle { - display: inline-flex; - overflow: hidden; - border: 1px solid #cbd5e1; - border-radius: 6px; - background: #fff; - - button { - padding: 0.5rem 0.7rem; - border: 0; - border-right: 1px solid #cbd5e1; - background: transparent; - color: #334155; - cursor: pointer; - font: inherit; - font-weight: 600; - - &:last-child { - border-right: 0; - } - - &.active { - background: #1d4ed8; - color: #fff; - } - - &:focus-visible { - outline: 3px solid #93c5fd; - outline-offset: -3px; - } - } + .topic-treemap-year-slider { + width: min(100%, 34rem); } .top-authors-header { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index b91ee6df..52e2765f 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -4,6 +4,7 @@ import { MatIconModule } from '@angular/material/icon'; import { Observable, finalize } from 'rxjs'; import { RouterLink } from '@angular/router'; import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component'; +import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; import { DashboardStatisticValue, DashboardStatistics, @@ -19,15 +20,15 @@ type DashboardStatisticKey = | 'eu_projects' | 'bmbf_projects' | 'dfg_projects'; -type TopicTreemapPeriod = - | 'last_5_years' - | 'last_10_years' - | 'all_time' - | 'custom'; - @Component({ selector: 'dashboard', - imports: [DecimalPipe, MatIconModule, RouterLink, TopicHeatmapComponent], + imports: [ + DecimalPipe, + MatIconModule, + RouterLink, + TopicHeatmapComponent, + YearRangeSliderComponent, + ], templateUrl: './dashboard.component.html', styleUrl: './dashboard.component.scss', }) @@ -57,9 +58,11 @@ export class DashboardComponent implements OnInit { topicHeatmap?: TopicHeatmap; topicHeatmapLoading = false; topicHeatmapError = false; - topicTreemapPeriod: TopicTreemapPeriod = 'last_5_years'; - topicTreemapFromYear = new Date().getFullYear() - 4; - topicTreemapToYear = new Date().getFullYear(); + readonly topicTreemapMinYear = 1900; + readonly topicTreemapMaxYear = new Date().getFullYear(); + topicTreemapFromYear = this.topicTreemapMaxYear - 4; + topicTreemapToYear = this.topicTreemapMaxYear; + private topicTreemapReloadQueued = false; constructor(private statisticsService: DashboardStatisticsService) {} @@ -166,35 +169,13 @@ export class DashboardComponent implements OnInit { ); } - setTopicTreemapPeriod(period: TopicTreemapPeriod): void { - if (period === this.topicTreemapPeriod && period !== 'custom') return; - - const currentYear = new Date().getFullYear(); - this.topicTreemapPeriod = period; - if (period === 'last_5_years') { - this.topicTreemapFromYear = currentYear - 4; - this.topicTreemapToYear = currentYear; - } else if (period === 'last_10_years') { - this.topicTreemapFromYear = currentYear - 9; - this.topicTreemapToYear = currentYear; - } else if (period === 'all_time') { - this.topicTreemapFromYear = 1900; - this.topicTreemapToYear = currentYear; - } - this.loadTopicHeatmap(); - } - - onTopicTreemapYearChange(field: 'from' | 'to', value: string): void { - const year = Number(value); - if (!Number.isInteger(year)) return; - - if (field === 'from') { - this.topicTreemapFromYear = year; - } else { - this.topicTreemapToYear = year; - } - this.topicTreemapPeriod = 'custom'; - this.loadTopicHeatmap(); + onTopicTreemapRangeChange(): void { + if (this.topicTreemapReloadQueued) return; + this.topicTreemapReloadQueued = true; + queueMicrotask(() => { + this.topicTreemapReloadQueued = false; + this.loadTopicHeatmap(); + }); } private loadStatistic( -- 2.56.1 From 908e28c7312bf45abcc174ae22c1b1ee765eac01 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 21 Jul 2026 19:04:28 +0200 Subject: [PATCH 4/6] implement dfg topics donutchart --- .../main/inse/dashboard/institute_helper.py | 29 +++ service/src/main/inse/dashboard/model.py | 17 ++ service/src/main/inse/dashboard/router.py | 35 +++ service/src/main/inse/dashboard/service.py | 213 ++++++++++++++---- .../inse/dashboard/test_institute_helper.py | 40 ++++ .../src/main/inse/dashboard/test_service.py | 195 +++++++++++++++- .../main/inse/integrations/elasticsearch.py | 2 + service/src/main/inse/model.py | 2 + .../dashboard/dashboard-statistics.service.ts | 30 +++ .../dashboard/dashboard.component.html | 71 +++++- .../dashboard/dashboard.component.scss | 17 ++ .../modules/dashboard/dashboard.component.ts | 111 ++++++++- .../dfg-topic-donut.component.html | 5 + .../dfg-topic-donut.component.scss | 12 + .../dfg-topic-donut.component.ts | 113 ++++++++++ .../topic-heatmap.component.html | 15 ++ .../topic-heatmap.component.scss | 24 ++ .../topic-heatmap/topic-heatmap.component.ts | 128 ++++++++++- 18 files changed, 991 insertions(+), 68 deletions(-) create mode 100644 service/src/main/inse/dashboard/institute_helper.py create mode 100644 service/src/main/inse/dashboard/test_institute_helper.py create mode 100644 webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.html create mode 100644 webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss create mode 100644 webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts diff --git a/service/src/main/inse/dashboard/institute_helper.py b/service/src/main/inse/dashboard/institute_helper.py new file mode 100644 index 00000000..87c63d3d --- /dev/null +++ b/service/src/main/inse/dashboard/institute_helper.py @@ -0,0 +1,29 @@ +from inse.exceptions import NotFoundException +from inse.integrations import elasticsearch +from inse.model import ESIndex +from inse.models.openalex.institution import Institution + + +async def get_openalex_institution(institution_id: str) -> Institution: + """Load an institution from OpenAlex using the user's institution ID.""" + raw_institution_id = institution_id.strip().removeprefix( + "https://openalex.org/" + ) + normalized_id = f"https://openalex.org/{raw_institution_id.upper()}" + response = await elasticsearch.search( + index=ESIndex.OPENALEX_INSTITUTIONS, + query={"term": {"id": normalized_id}}, + size=1, + ) + hits = response.get("hits", {}).get("hits", []) + if not hits: + raise NotFoundException( + f"Institution with ID '{raw_institution_id}' not found." + ) + + institution = Institution.from_dict(hits[0].get("_source", {})) + if institution is None: + raise NotFoundException( + f"Institution with ID '{raw_institution_id}' could not be parsed." + ) + return institution diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index 426c1402..7a996055 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -18,6 +18,23 @@ class DashboardStatisticValue(BaseModel): value: int +class DfgProjectTopic(BaseModel): + id: str + name: str + subfield: str | None = None + field: str | None = None + domain: str | None = None + project_count: int + + +class DfgProjectTopics(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 82377042..62eaa152 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -11,6 +11,7 @@ from inse.tags import Tags from .model import ( DashboardStatisticValue, DashboardStatistics, + DfgProjectTopics, TopAuthorStatistics, TopicHeatmap, TopicWordCloud, @@ -18,8 +19,10 @@ from .model import ( from .service import ( get_dashboard_bmbf_projects, get_dashboard_dfg_projects, + get_dashboard_dfg_topics, get_dashboard_eu_projects, get_dashboard_organization, + get_dashboard_patents, get_dashboard_persons, get_dashboard_publications, get_dashboard_statistics, @@ -79,6 +82,22 @@ async def dashboard_persons( ) +@router.get( + "/statistics/patents", + operation_id="getDashboardPatents", + response_model=DashboardStatisticValue, +) +async def dashboard_patents( + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> DashboardStatisticValue: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_patents( + organization.openalex_institution_id, + organization.name, + ) + + @router.get( "/statistics/projects/eu", operation_id="getDashboardEuProjects", @@ -127,6 +146,22 @@ async def dashboard_dfg_projects( ) +@router.get( + "/projects/dfg/topics", + operation_id="getDashboardDfgProjectTopics", + response_model=DfgProjectTopics, +) +async def dashboard_dfg_project_topics( + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> DfgProjectTopics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_dfg_topics( + organization.openalex_institution_id, + organization.name, + ) + + @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 5df7eb3e..c9467023 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -13,9 +13,12 @@ from inse.institutions.institutions_search_client import InstitutionsSearchClien from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from .institute_helper import get_openalex_institution from .model import ( DashboardStatisticValue, DashboardStatistics, + DfgProjectTopic, + DfgProjectTopics, TopAuthor, TopAuthorStatistics, TopicHeatmap, @@ -182,6 +185,23 @@ async def get_dashboard_persons( return _dashboard_statistic_value(normalized_id, organization_name, response) +async def get_dashboard_patents( + institution_id: str, + organization_name: str, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + _, total = await OrgPatentsSearchClient().search_by_institution( + normalized_id, + page=0, + size=0, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=total, + ) + + async def get_dashboard_eu_projects( institution_id: str, organization_name: str, @@ -235,15 +255,144 @@ async def get_dashboard_dfg_projects( organization_name: str, ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - response = await elasticsearch.search( - index=ESIndex.DFG_PROJECTS_V2, - query=_dfg_institution_query(aliases), - size=0, - track_total_hits=True, + project_ids = await _get_dfg_project_ids_for_institution(normalized_id) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=len(project_ids), + ) + + +async def get_dashboard_dfg_topics( + institution_id: str, + organization_name: str, +) -> DfgProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + project_ids = await _get_dfg_project_ids_for_institution(normalized_id) + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + + if project_ids: + async for hit in elasticsearch.scan( + index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS), + query={"terms": {"project_id": project_ids}}, + source=["project_id", "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 + 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(), + }, + ) + topic["project_ids"].add(project_id) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return DfgProjectTopics( + 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_for_institution( + institution_id: str, +) -> list[str]: + institution = await get_openalex_institution(institution_id) + institution_names = _openalex_institution_names(institution) + + institutes_response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "query": _dfg_institute_name_query(institution_names), + "aggs": { + "institute_ids": { + "terms": {"field": "institute_id", "size": 1000} + } + }, + }, cluster=ESCluster.INSE, ) - return _dashboard_statistic_value(normalized_id, organization_name, response) + institute_ids = [ + bucket["key"] + for bucket in ( + institutes_response.get("aggregations", {}) + .get("institute_ids", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] + if not institute_ids: + return [] + + projects_response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "query": {"terms": {"institute_id": institute_ids}}, + "aggs": { + "projects_nested": { + "nested": {"path": "projects"}, + "aggs": { + "project_ids": { + "filter": { + "terms": {"projects.institute_ref_id": institute_ids} + }, + "aggs": { + "values": { + "terms": { + "field": "projects.project_id", + "size": 10000, + } + } + }, + } + }, + } + }, + }, + cluster=ESCluster.INSE, + ) + return [ + str(bucket["key"]) + for bucket in ( + projects_response.get("aggregations", {}) + .get("projects_nested", {}) + .get("project_ids", {}) + .get("values", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] def _dashboard_statistic_value( @@ -301,44 +450,32 @@ def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]: } -def _dfg_institution_query(aliases: list[str]) -> dict[str, Any]: +def _openalex_institution_names(institution: Any) -> list[str]: + return sorted( + { + name.strip() + for name in [ + institution.display_name, + *(institution.display_name_alternatives or []), + *(institution.display_name_acronyms or []), + ] + if name and name.strip() + } + ) + + +def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]: return { "bool": { "should": [ { - "nested": { - "path": "institutions", - "query": { - "bool": { - "should": [ - _alias_match_query( - "institutions.institute_name_de", aliases - ), - _alias_match_query( - "institutions.institute_name_en", aliases - ), - ], - "minimum_should_match": 1, - } - }, + "terms": { + "institute_name_de.keyword": institution_names, } }, { - "nested": { - "path": "persons", - "query": { - "bool": { - "should": [ - _alias_match_query( - "persons.affiliation_de", aliases - ), - _alias_match_query( - "persons.affiliation_en", aliases - ), - ], - "minimum_should_match": 1, - } - }, + "terms": { + "institute_name_en.keyword": institution_names, } }, ], diff --git a/service/src/main/inse/dashboard/test_institute_helper.py b/service/src/main/inse/dashboard/test_institute_helper.py new file mode 100644 index 00000000..24fb4fea --- /dev/null +++ b/service/src/main/inse/dashboard/test_institute_helper.py @@ -0,0 +1,40 @@ +from unittest.mock import AsyncMock, patch + +import pytest + +from inse.dashboard.institute_helper import get_openalex_institution +from inse.models.openalex.institution import Institution + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "institution_id", + ["I62318514", "https://openalex.org/I62318514"], +) +async def test_get_openalex_institution_accepts_short_and_full_id( + institution_id: str, +): + institution = Institution( + id="https://openalex.org/I62318514", + display_name="University of Duisburg-Essen", + display_name_alternatives=["Universität Duisburg-Essen"], + ) + with patch( + "inse.dashboard.institute_helper.elasticsearch.search", + new=AsyncMock( + return_value={"hits": {"hits": [{"_source": institution.to_dict()}]}} + ), + ) as search: + result = await get_openalex_institution(institution_id) + + assert result == institution + search.assert_awaited_once_with( + index="openalex-institutions", + query={"term": {"id": "https://openalex.org/I62318514"}}, + size=1, + ) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index cec617e8..cc9e5084 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,12 +9,15 @@ from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( get_dashboard_organization, + get_dashboard_dfg_topics, + get_dashboard_patents, get_dashboard_statistics, get_top_authors, get_topic_heatmap, get_topic_word_cloud, ) from inse.model import ESCluster, ESIndex +from inse.models.openalex.institution import Institution ORG_INSTITUTION_ID = "https://openalex.org/I123" @@ -24,6 +27,22 @@ def anyio_backend(): return "asyncio" +@pytest.mark.anyio +async def test_dashboard_patents_uses_org_patent_total(): + with patch( + "inse.dashboard.service.OrgPatentsSearchClient.search_by_institution", + new=AsyncMock(return_value=([], 42)), + ) as search: + result = await get_dashboard_patents(ORG_INSTITUTION_ID, "Example Org") + + assert result.model_dump() == { + "institution_id": ORG_INSTITUTION_ID, + "organization_name": "Example Org", + "value": 42, + } + search.assert_awaited_once_with(ORG_INSTITUTION_ID, page=0, size=0) + + @pytest.mark.anyio async def test_dashboard_statistics_counts_organization_data_and_all_projects(): async def search(**kwargs): @@ -36,6 +55,28 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): return {"aggregations": {"projects": {"value": 10}}} if index == ESIndex.PROJECTS_BUND_V1: return {"hits": {"total": {"value": 5}}} + if index == ESIndex.DFG_INSTITUTES_V2: + if "institute_ids" in kwargs["body"].get("aggs", {}): + return { + "aggregations": { + "institute_ids": {"buckets": [{"key": 10210}]} + } + } + return { + "aggregations": { + "projects_nested": { + "project_ids": { + "values": { + "buckets": [ + {"key": 101}, + {"key": 102}, + {"key": 103}, + ] + } + } + } + } + } return {"hits": {"total": {"value": 3}}} with patch( @@ -44,6 +85,15 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): ) as mocked_search, patch( "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", new=AsyncMock(return_value=["Example University", "Example Uni"]), + ), patch( + "inse.dashboard.service.get_openalex_institution", + new=AsyncMock( + return_value=Institution( + id=ORG_INSTITUTION_ID, + display_name="Example University", + display_name_alternatives=["Example Universität"], + ) + ), ): result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org") @@ -58,12 +108,21 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } calls = mocked_search.await_args_list - calls_by_index = {call.kwargs["index"]: call for call in calls} + calls_by_index = { + call.kwargs["index"]: call + for call in calls + if call.kwargs["index"] != ESIndex.DFG_INSTITUTES_V2 + } works_call = calls_by_index[config.settings.openalex_works_search_index] authors_call = calls_by_index[ESIndex.OPENALEX_AUTHORS] eu_call = calls_by_index[ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD] bmbf_call = calls_by_index[ESIndex.PROJECTS_BUND_V1] - dfg_call = calls_by_index[ESIndex.DFG_PROJECTS_V2] + dfg_calls = [ + call + for call in calls + if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2 + ] + dfg_institutes_call, dfg_projects_call = dfg_calls assert works_call.kwargs["query"]["nested"]["query"]["term"] == { "authorships.institutions.id": ORG_INSTITUTION_ID } @@ -74,7 +133,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): } assert all( call.kwargs["cluster"] == ESCluster.INSE - for call in [eu_call, bmbf_call, dfg_call] + for call in [eu_call, bmbf_call, *dfg_calls] ) assert eu_call.kwargs["body"]["query"] == { "terms": { @@ -92,18 +151,130 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "operator": "and", } } - dfg_query = dfg_call.kwargs["query"] + dfg_query = dfg_institutes_call.kwargs["body"]["query"] assert dfg_query["bool"]["minimum_should_match"] == 1 - assert dfg_query["bool"]["should"][0]["nested"]["path"] == "institutions" - assert dfg_query["bool"]["should"][0]["nested"]["query"]["bool"]["should"][ - 0 - ]["bool"]["should"][0]["match"] == { - "institutions.institute_name_de": { - "query": "Example Org", - "operator": "and", + assert dfg_query["bool"]["should"] == [ + { + "terms": { + "institute_name_de.keyword": [ + "Example University", + "Example Universität", + ] + } + }, + { + "terms": { + "institute_name_en.keyword": [ + "Example University", + "Example Universität", + ] + } + }, + ] + assert dfg_projects_call.kwargs["body"]["query"] == { + "terms": {"institute_id": [10210]} + } + assert dfg_projects_call.kwargs["body"]["aggs"] == { + "projects_nested": { + "nested": {"path": "projects"}, + "aggs": { + "project_ids": { + "filter": { + "terms": {"projects.institute_ref_id": [10210]} + }, + "aggs": { + "values": { + "terms": { + "field": "projects.project_id", + "size": 10000, + } + } + }, + } + }, } } - assert dfg_query["bool"]["should"][1]["nested"]["path"] == "persons" + + +@pytest.mark.anyio +async def test_dashboard_dfg_topics_returns_deduplicated_topics(): + async def scan(**kwargs): + assert kwargs == { + "index": "projects_dfg_openalex_topics", + "query": {"terms": {"project_id": ["101", "102"]}}, + "source": ["project_id", "topic_matches"], + "page_size": 1000, + "cluster": ESCluster.INSE, + } + yield { + "_source": { + "project_id": "101", + "topic_matches": [ + { + "topic_id": "https://openalex.org/T1", + "topic_display_name": "Topic One", + "subfield": "Subfield One", + "field": "Field One", + "domain": "Domain One", + } + ], + } + } + yield { + "_source": { + "project_id": "102", + "topic_matches": [ + { + "topic_id": "https://openalex.org/T1", + "topic_display_name": "Topic One", + "subfield": "Subfield One", + "field": "Field One", + "domain": "Domain One", + }, + { + "topic_id": "https://openalex.org/T2", + "topic_display_name": "Topic Two", + "subfield": "Subfield Two", + "field": "Field Two", + "domain": "Domain Two", + }, + ], + } + } + + with patch( + "inse.dashboard.service._get_dfg_project_ids_for_institution", + new=AsyncMock(return_value=["101", "102"]), + ), patch("inse.dashboard.service.elasticsearch.scan", new=scan): + result = await get_dashboard_dfg_topics( + ORG_INSTITUTION_ID, + "Example Org", + ) + + assert result.model_dump() == { + "institution_id": ORG_INSTITUTION_ID, + "organization_name": "Example Org", + "project_count": 2, + "matched_project_count": 2, + "topics": [ + { + "id": "https://openalex.org/T1", + "name": "Topic One", + "subfield": "Subfield One", + "field": "Field One", + "domain": "Domain One", + "project_count": 2, + }, + { + "id": "https://openalex.org/T2", + "name": "Topic Two", + "subfield": "Subfield Two", + "field": "Field Two", + "domain": "Domain Two", + "project_count": 1, + }, + ], + } @pytest.mark.anyio diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 77afd124..f63de9a4 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -102,6 +102,8 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: ESIndex.PROJECTS_BUND_V1, ESIndex.PROJECTS_DFG_ALL, ESIndex.DFG_PROJECTS_V2, + ESIndex.DFG_INSTITUTES_V2, + ESIndex.PROJECTS_DFG_OPENALEX_TOPICS, }: return ESCluster.INSE else: diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 5265720b..5ad2766a 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -62,6 +62,8 @@ class ESIndex(StrEnum): PROJECTS_BUND_V1 = "projects_bund_v1" PROJECTS_DFG_ALL = "projects_dfg_all" DFG_PROJECTS_V2 = "dfg_projects_2.0" + DFG_INSTITUTES_V2 = "dfg_institutes_2.0" + PROJECTS_DFG_OPENALEX_TOPICS = "projects_dfg_openalex_topics" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index aa23dd73..adeee036 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -11,6 +11,7 @@ export interface DashboardStatistics { organization_name: string; publications: number; persons: number; + patents: number; projects: number; dfg_projects: number; eu_projects: number; @@ -23,6 +24,23 @@ export interface DashboardStatisticValue { value: number; } +export interface DfgProjectTopic { + id: string; + name: string; + subfield?: string | null; + field?: string | null; + domain?: string | null; + project_count: number; +} + +export interface DfgProjectTopics { + institution_id: string; + organization_name: string; + project_count: number; + matched_project_count: number; + topics: DfgProjectTopic[]; +} + export interface TopAuthor { id?: string | null; name: string; @@ -107,6 +125,12 @@ export class DashboardStatisticsService { ); } + getPatentCount(): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`, + ); + } + getEuProjectCount(): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`, @@ -125,6 +149,12 @@ export class DashboardStatisticsService { ); } + getDfgProjectTopics(): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`, + ); + } + getTopAuthors( worksPeriod: TopAuthorsWorksPeriod = 'all_time', ): Observable { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 73a495ca..bd994ccf 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -23,6 +23,27 @@
+ +
+ description +
+
+ Patente + + {{ + isStatisticLoading('patents') + ? '…' + : ((statistics?.patents | number) ?? '–') + }} + +
+
+ - @if (topicHeatmapError) { + @if (topicHeatmapLoading) { +
+ +
+ } @else if (topicHeatmapError) {

Die Field-Treemap konnte nicht geladen werden.

} @else { + [selectedNodeId]="selectedTopicTreemapNode" + (selectedNodeIdChange)="onTopicTreemapNodeChange($event)"> + + } + + } + + @if (dfgTopicsLoading || dfgTopicsError || dfgProjectTopics) { +
+
+
+

DFG-Projekt-Topics

+

+ Verteilung der gematchten Topics aus den DFG-Projekten Ihrer Organisation. +

+
+ @if (dfgProjectTopics) { +

+ {{ dfgProjectTopics.matched_project_count | number }} von + {{ dfgProjectTopics.project_count | number }} Projekten gematcht +

+ } +
+ + @if (dfgTopicsLoading) { +
+ +
+ } @else if (dfgTopicsError) { +

+ Das DFG-Topic-Diagramm konnte nicht geladen werden. +

+ } @else { + }
} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 66b3f245..1d6d7718 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -73,6 +73,11 @@ color: #15803d; } + &--patents { + background: #fee2e2; + color: #b91c1c; + } + &--eu-projects { background: #e0f2fe; color: #0369a1; @@ -133,6 +138,18 @@ width: min(100%, 34rem); } + .topic-heatmap-loading { + min-height: 25rem; + display: grid; + place-items: center; + } + + .dfg-topic-summary { + flex: 0 0 auto; + color: #475569; + font-weight: 600; + } + .top-authors-header { display: flex; align-items: flex-end; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 52e2765f..c7268ecd 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -2,13 +2,16 @@ import { Component, OnInit } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { MatIconModule } from '@angular/material/icon'; import { Observable, finalize } from 'rxjs'; -import { RouterLink } from '@angular/router'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component'; +import { DfgTopicDonutComponent } from './dfg-topic-donut/dfg-topic-donut.component'; import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { DashboardStatisticValue, DashboardStatistics, DashboardStatisticsService, + DfgProjectTopics, TopAuthor, TopAuthorStatistics, TopAuthorsWorksPeriod, @@ -17,6 +20,7 @@ import { type DashboardStatisticKey = | 'publications' | 'persons' + | 'patents' | 'eu_projects' | 'bmbf_projects' | 'dfg_projects'; @@ -26,6 +30,8 @@ type DashboardStatisticKey = DecimalPipe, MatIconModule, RouterLink, + LoadingComponent, + DfgTopicDonutComponent, TopicHeatmapComponent, YearRangeSliderComponent, ], @@ -39,6 +45,7 @@ export class DashboardComponent implements OnInit { statisticLoading: Record = { publications: false, persons: false, + patents: false, eu_projects: false, bmbf_projects: false, dfg_projects: false, @@ -46,6 +53,7 @@ export class DashboardComponent implements OnInit { statisticErrors: Record = { publications: false, persons: false, + patents: false, eu_projects: false, bmbf_projects: false, dfg_projects: false, @@ -58,18 +66,29 @@ export class DashboardComponent implements OnInit { topicHeatmap?: TopicHeatmap; topicHeatmapLoading = false; topicHeatmapError = false; + dfgProjectTopics?: DfgProjectTopics; + dfgTopicsLoading = false; + dfgTopicsError = false; readonly topicTreemapMinYear = 1900; readonly topicTreemapMaxYear = new Date().getFullYear(); topicTreemapFromYear = this.topicTreemapMaxYear - 4; topicTreemapToYear = this.topicTreemapMaxYear; + selectedTopicTreemapNode?: string; private topicTreemapReloadQueued = false; + private topicHeatmapRequestId = 0; - constructor(private statisticsService: DashboardStatisticsService) {} + constructor( + private statisticsService: DashboardStatisticsService, + private route: ActivatedRoute, + private router: Router, + ) {} ngOnInit() { + this.restoreTopicTreemapState(); this.loadStatistics(); this.loadTopAuthors(); this.loadTopicHeatmap(); + this.loadDfgProjectTopics(); } private loadStatistics(): void { @@ -79,6 +98,7 @@ export class DashboardComponent implements OnInit { this.statisticsService.getPublicationCount(), ); this.loadStatistic('persons', this.statisticsService.getPersonCount()); + this.loadStatistic('patents', this.statisticsService.getPatentCount()); this.loadStatistic( 'eu_projects', this.statisticsService.getEuProjectCount(), @@ -146,6 +166,10 @@ export class DashboardComponent implements OnInit { ); } + hasDfgTopicData(): boolean { + return (this.dfgProjectTopics?.topics.length ?? 0) > 0; + } + setTopAuthorsWorksPeriod(period: TopAuthorsWorksPeriod): void { if (period === this.topAuthorsWorksPeriod) return; this.topAuthorsWorksPeriod = period; @@ -170,14 +194,61 @@ export class DashboardComponent implements OnInit { } onTopicTreemapRangeChange(): void { + this.topicHeatmapLoading = true; + this.topicHeatmapError = false; + this.topicHeatmapRequestId += 1; + this.updateTopicTreemapUrl(); if (this.topicTreemapReloadQueued) return; this.topicTreemapReloadQueued = true; - queueMicrotask(() => { + setTimeout(() => { this.topicTreemapReloadQueued = false; this.loadTopicHeatmap(); }); } + onTopicTreemapNodeChange(nodeId: string | undefined): void { + this.selectedTopicTreemapNode = nodeId; + this.updateTopicTreemapUrl(); + } + + private restoreTopicTreemapState(): void { + const params = this.route.snapshot.queryParamMap; + this.topicTreemapFromYear = this.parseTreemapYear( + params.get('treemapFrom'), + this.topicTreemapFromYear, + ); + this.topicTreemapToYear = this.parseTreemapYear( + params.get('treemapTo'), + this.topicTreemapToYear, + ); + if (this.topicTreemapFromYear > this.topicTreemapToYear) { + this.topicTreemapFromYear = this.topicTreemapToYear; + } + this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined; + } + + private updateTopicTreemapUrl(): void { + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { + treemapFrom: this.topicTreemapFromYear, + treemapTo: this.topicTreemapToYear, + treemapNode: this.selectedTopicTreemapNode ?? null, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + private parseTreemapYear(value: string | null, fallback: number): number { + const year = Number(value); + return Number.isInteger(year) && + year >= this.topicTreemapMinYear && + year <= this.topicTreemapMaxYear + ? year + : fallback; + } + private loadStatistic( key: DashboardStatisticKey, request: Observable, @@ -239,23 +310,51 @@ export class DashboardComponent implements OnInit { }); } + private loadDfgProjectTopics(): void { + this.dfgTopicsLoading = true; + this.dfgTopicsError = false; + this.statisticsService + .getDfgProjectTopics() + .pipe(finalize(() => (this.dfgTopicsLoading = false))) + .subscribe({ + next: (topics) => { + this.dfgProjectTopics = topics; + }, + error: () => { + this.dfgTopicsError = true; + }, + }); + } + private loadTopicHeatmap(): void { if (this.topicTreemapFromYear > this.topicTreemapToYear) { + this.topicHeatmapLoading = false; this.topicHeatmapError = true; return; } + const requestId = ++this.topicHeatmapRequestId; this.topicHeatmapLoading = true; this.topicHeatmapError = false; this.statisticsService .getTopicHeatmap(this.topicTreemapFromYear, this.topicTreemapToYear) - .pipe(finalize(() => (this.topicHeatmapLoading = false))) + .pipe( + finalize(() => { + if (requestId === this.topicHeatmapRequestId) { + this.topicHeatmapLoading = false; + } + }), + ) .subscribe({ next: (heatmap) => { - this.topicHeatmap = heatmap; + if (requestId === this.topicHeatmapRequestId) { + this.topicHeatmap = heatmap; + } }, error: () => { - this.topicHeatmapError = true; + if (requestId === this.topicHeatmapRequestId) { + this.topicHeatmapError = true; + } }, }); } diff --git a/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.html b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.html new file mode 100644 index 00000000..78f76cd3 --- /dev/null +++ b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.html @@ -0,0 +1,5 @@ +@if (topics.length) { +
+} @else { +

Keine gematchten DFG-Topics vorhanden.

+} diff --git a/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss new file mode 100644 index 00000000..73da71f3 --- /dev/null +++ b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss @@ -0,0 +1,12 @@ +.dfg-topic-donut-chart { + width: 100%; + height: 440px; +} + +.dfg-topic-donut-empty { + display: grid; + min-height: 260px; + margin: 0; + place-items: center; + color: #64748b; +} diff --git a/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts new file mode 100644 index 00000000..09e88311 --- /dev/null +++ b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts @@ -0,0 +1,113 @@ +import { Component, Input, OnChanges } from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +import { DfgProjectTopic } from '../dashboard-statistics.service'; + +@Component({ + selector: 'app-dfg-topic-donut', + imports: [NgxEchartsDirective], + templateUrl: './dfg-topic-donut.component.html', + styleUrl: './dfg-topic-donut.component.scss', +}) +export class DfgTopicDonutComponent implements OnChanges { + @Input() topics: DfgProjectTopic[] = []; + + options: EChartsOption = {}; + + ngOnChanges(): void { + this.options = { + color: [ + '#7255d9', + '#2563eb', + '#0891b2', + '#059669', + '#65a30d', + '#ca8a04', + '#ea580c', + '#dc2626', + '#db2777', + '#9333ea', + ], + tooltip: { + trigger: 'item', + confine: true, + formatter: (params: any) => + `${this.escapeHtml(String(params.name ?? ''))}
${Number(params.value ?? 0).toLocaleString('de-DE')} DFG-Projekte`, + }, + legend: { + type: 'scroll', + orient: 'vertical', + top: 'middle', + right: 12, + width: '38%', + textStyle: { color: '#334155' }, + formatter: (name: string) => this.truncate(name, 42), + }, + graphic: [ + { + type: 'text', + left: '30%', + top: '46%', + style: { + text: `${this.topics.length}\nTopics`, + align: 'center', + fill: '#0f172a', + fontSize: 18, + fontWeight: 700, + lineHeight: 25, + }, + }, + ], + series: [ + { + name: 'DFG-Topics', + type: 'pie', + radius: ['42%', '72%'], + center: ['32%', '50%'], + avoidLabelOverlap: true, + minAngle: 3, + itemStyle: { + borderColor: '#ffffff', + borderWidth: 3, + borderRadius: 5, + }, + label: { show: false }, + emphasis: { + scaleSize: 8, + label: { + show: true, + formatter: '{b}\n{c} Projekte', + fontWeight: 700, + }, + }, + data: this.topics.map((topic) => ({ + id: topic.id, + name: topic.name, + value: topic.project_count, + })), + }, + ], + }; + } + + private truncate(value: string, maximum: number): string { + return value.length > maximum + ? `${value.slice(0, maximum - 1)}…` + : value; + } + + private escapeHtml(value: string): string { + return value.replace( + /[&<>'"]/g, + (character) => + ({ + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"', + })[character] ?? character, + ); + } +} diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html index e4b99420..132e8773 100644 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html +++ b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html @@ -1,4 +1,19 @@ @if (heatmap?.fields?.length) { + @if (selectedNodeId) { + + }
(); options: EChartsOption = {}; - ngOnChanges(): void { - this.options = this.buildOptions(); + ngOnChanges(changes: SimpleChanges): void { + if (changes['heatmap'] || changes['selectedNodeId']) { + this.options = this.buildOptions(); + } } onChartClick(event: any): void { const data = event?.data; + const selectedNodeId = data?.nodeId ?? this.nodeIdFromTreePath(event); + this.selectedNodeIdChange.emit(selectedNodeId); + if (!data?.id || !data?.subfieldName || data?.children?.length) return; this.dialog.open( TopicWordCloudDialogComponent, @@ -37,7 +57,7 @@ export class TopicHeatmapComponent implements OnChanges { width: '85vw', maxWidth: '92vw', data: { - topicId: data.id, + topicId: data.entityId, topicName: data.name, fieldName: data.fieldName, subfieldName: data.subfieldName, @@ -48,16 +68,51 @@ export class TopicHeatmapComponent implements OnChanges { ); } + breadcrumbs(): TreemapBreadcrumb[] { + const result: TreemapBreadcrumb[] = [{ label: 'Fields' }]; + if (!this.selectedNodeId || !this.heatmap) return result; + + for (const field of this.heatmap.fields) { + const fieldNodeId = `field:${field.id}`; + if (this.selectedNodeId === fieldNodeId) { + return [...result, { label: field.name, nodeId: fieldNodeId }]; + } + for (const subfield of field.subfields) { + const subfieldNodeId = `subfield:${subfield.id}`; + const topic = subfield.topics.find( + (entry) => `topic:${entry.id}` === this.selectedNodeId, + ); + if (this.selectedNodeId === subfieldNodeId || topic) { + return [ + ...result, + { label: field.name, nodeId: fieldNodeId }, + { label: subfield.name, nodeId: subfieldNodeId }, + ...(topic + ? [{ label: topic.name, nodeId: `topic:${topic.id}` }] + : []), + ]; + } + } + } + return result; + } + + selectBreadcrumb(nodeId?: string): void { + this.selectedNodeIdChange.emit(nodeId); + } + private buildOptions(): EChartsOption { const fields = this.heatmap?.fields ?? []; - const data = fields.map((field) => { + const hierarchyData = fields.map((field) => { const fieldColor = topicHierarchyColor({ field_id: field.id, field_name: field.name, }); return { - id: field.id, + id: `field:${field.id}`, + entityId: field.id, + nodeId: `field:${field.id}`, name: field.name, value: field.total || this.totalCount(field.values), itemStyle: { @@ -82,7 +137,9 @@ export class TopicHeatmapComponent implements OnChanges { children: (field.subfields ?? []) .filter((subfield) => subfield.total > 0) .map((subfield) => ({ - id: subfield.id, + id: `subfield:${subfield.id}`, + entityId: subfield.id, + nodeId: `subfield:${subfield.id}`, name: subfield.name, value: subfield.total, fieldName: field.name, @@ -99,7 +156,9 @@ export class TopicHeatmapComponent implements OnChanges { children: (subfield.topics ?? []) .filter((topic) => topic.total > 0) .map((topic) => ({ - id: topic.id, + id: `topic:${topic.id}`, + entityId: topic.id, + nodeId: `topic:${topic.id}`, name: topic.name, value: topic.total, fieldName: field.name, @@ -118,6 +177,7 @@ export class TopicHeatmapComponent implements OnChanges { })), }; }); + const data = this.visibleData(hierarchyData); return { tooltip: { @@ -170,11 +230,11 @@ export class TopicHeatmapComponent implements OnChanges { type: 'treemap', data, roam: false, - nodeClick: 'zoomToNode', + nodeClick: false, sort: 'desc', drillDownIcon: '', breadcrumb: { - show: true, + show: false, bottom: 0, height: 24, left: 8, @@ -303,6 +363,54 @@ export class TopicHeatmapComponent implements OnChanges { }; } + private visibleData(hierarchyData: any[]): any[] { + if (!this.selectedNodeId) return hierarchyData; + + if (this.selectedNodeId.startsWith('field:')) { + const field = hierarchyData.find( + (entry) => entry.nodeId === this.selectedNodeId, + ); + return field?.children ?? hierarchyData; + } + + const subfieldNodeId = this.selectedNodeId.startsWith('subfield:') + ? this.selectedNodeId + : this.subfieldNodeIdForTopic(this.selectedNodeId); + for (const field of hierarchyData) { + const subfield = field.children?.find( + (entry: any) => entry.nodeId === subfieldNodeId, + ); + if (subfield) return subfield.children ?? []; + } + return hierarchyData; + } + + private subfieldNodeIdForTopic(topicNodeId: string): string | undefined { + if (!topicNodeId.startsWith('topic:') || !this.heatmap) return undefined; + const topicId = topicNodeId.slice('topic:'.length); + for (const field of this.heatmap.fields) { + const subfield = field.subfields.find((entry) => + entry.topics.some((topic) => topic.id === topicId), + ); + if (subfield) return `subfield:${subfield.id}`; + } + return undefined; + } + + private nodeIdFromTreePath(event: any): string | undefined { + const path = (event?.treePathInfo ?? []) + .map((entry: { name?: string }) => entry.name) + .filter(Boolean); + if (path.length <= 1 || !this.heatmap) return undefined; + + const field = this.heatmap.fields.find((entry) => entry.name === path[1]); + if (!field) return undefined; + const subfield = field.subfields.find((entry) => entry.name === path[2]); + if (!subfield) return `field:${field.id}`; + const topic = subfield.topics.find((entry) => entry.name === path[3]); + return topic ? `topic:${topic.id}` : `subfield:${subfield.id}`; + } + private totalCount(values: Array<{ count: number }>): number { return values.reduce((sum, value) => sum + value.count, 0); } -- 2.56.1 From 4d1f2e64d1ef631321f7eaefcf85b5d7e2b1b694 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Thu, 23 Jul 2026 17:54:09 +0200 Subject: [PATCH 5/6] add new analysis --- service/src/main/inse/dashboard/model.py | 16 +++ service/src/main/inse/dashboard/router.py | 36 +++++ service/src/main/inse/dashboard/service.py | 133 ++++++++++++++++++ .../src/main/inse/dashboard/test_service.py | 105 ++++++++++++++ .../dashboard/dashboard-statistics.service.ts | 28 ++++ .../dashboard/dashboard.component.html | 57 ++++++++ .../dashboard/dashboard.component.scss | 21 +++ .../modules/dashboard/dashboard.component.ts | 44 ++++++ .../eu-project-status-chart.component.html | 6 + .../eu-project-status-chart.component.scss | 4 + .../eu-project-status-chart.component.ts | 108 ++++++++++++++ 11 files changed, 558 insertions(+) create mode 100644 webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.html create mode 100644 webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.scss create mode 100644 webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.ts diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index 7a996055..74cbff0c 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -18,6 +18,22 @@ class DashboardStatisticValue(BaseModel): value: int +class EuProjectStatusStatistics(BaseModel): + institution_id: str + organization_name: str + ongoing: int + upcoming: int + completed: int + + +class BmbfProjectStatusStatistics(BaseModel): + institution_id: str + organization_name: str + ongoing: int + upcoming: int + completed: int + + class DfgProjectTopic(BaseModel): id: str name: str diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index 62eaa152..403bcb9d 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -9,18 +9,22 @@ from inse.database import get_session from inse.tags import Tags from .model import ( + BmbfProjectStatusStatistics, DashboardStatisticValue, DashboardStatistics, DfgProjectTopics, + EuProjectStatusStatistics, TopAuthorStatistics, TopicHeatmap, TopicWordCloud, ) from .service import ( + get_dashboard_bmbf_project_statuses, get_dashboard_bmbf_projects, get_dashboard_dfg_projects, get_dashboard_dfg_topics, get_dashboard_eu_projects, + get_dashboard_eu_project_statuses, get_dashboard_organization, get_dashboard_patents, get_dashboard_persons, @@ -114,6 +118,22 @@ async def dashboard_eu_projects( ) +@router.get( + "/projects/eu/status", + operation_id="getDashboardEuProjectStatuses", + response_model=EuProjectStatusStatistics, +) +async def dashboard_eu_project_statuses( + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> EuProjectStatusStatistics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_eu_project_statuses( + organization.openalex_institution_id, + organization.name, + ) + + @router.get( "/statistics/projects/bmbf", operation_id="getDashboardBmbfProjects", @@ -130,6 +150,22 @@ async def dashboard_bmbf_projects( ) +@router.get( + "/projects/bmbf/status", + operation_id="getDashboardBmbfProjectStatuses", + response_model=BmbfProjectStatusStatistics, +) +async def dashboard_bmbf_project_statuses( + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> BmbfProjectStatusStatistics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_bmbf_project_statuses( + organization.openalex_institution_id, + organization.name, + ) + + @router.get( "/statistics/projects/dfg", operation_id="getDashboardDfgProjects", diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index c9467023..04788962 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -15,10 +15,12 @@ from inse.patents.org.elastic_search_client import OrgPatentsSearchClient from .institute_helper import get_openalex_institution from .model import ( + BmbfProjectStatusStatistics, DashboardStatisticValue, DashboardStatistics, DfgProjectTopic, DfgProjectTopics, + EuProjectStatusStatistics, TopAuthor, TopAuthorStatistics, TopicHeatmap, @@ -234,6 +236,86 @@ async def get_dashboard_eu_projects( ) +async def get_dashboard_eu_project_statuses( + institution_id: str, + organization_name: str, +) -> EuProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + aliases = await _institution_aliases(normalized_id, organization_name) + project_ids: set[str] = set() + + async for hit in elasticsearch.scan( + index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), + query=_eu_organization_query(aliases), + source=["projectID"], + page_size=1000, + cluster=ESCluster.INSE, + ): + project_id = hit.get("_source", {}).get("projectID") + if project_id is not None: + project_ids.add(str(project_id)) + + if not project_ids: + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + + today = datetime.now().date().isoformat() + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + body={ + "size": 0, + "query": {"terms": {"id": sorted(project_ids)}}, + "aggs": { + "ongoing": { + "filter": { + "bool": { + "filter": [ + {"range": {"startDate": {"lte": today}}}, + {"range": {"endDate": {"gte": today}}}, + ] + } + }, + "aggs": { + "projects": {"cardinality": {"field": "id"}} + }, + }, + "upcoming": { + "filter": {"range": {"startDate": {"gt": today}}}, + "aggs": { + "projects": {"cardinality": {"field": "id"}} + }, + }, + "completed": { + "filter": {"range": {"endDate": {"lt": today}}}, + "aggs": { + "projects": {"cardinality": {"field": "id"}} + }, + }, + }, + }, + cluster=ESCluster.INSE, + ) + aggregations = response.get("aggregations", {}) + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=_project_status_count(aggregations, "ongoing"), + upcoming=_project_status_count(aggregations, "upcoming"), + completed=_project_status_count(aggregations, "completed"), + ) + + +def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int: + return int( + aggregations.get(status_name, {}).get("projects", {}).get("value", 0) + ) + + async def get_dashboard_bmbf_projects( institution_id: str, organization_name: str, @@ -250,6 +332,57 @@ async def get_dashboard_bmbf_projects( return _dashboard_statistic_value(normalized_id, organization_name, response) +async def get_dashboard_bmbf_project_statuses( + institution_id: str, + organization_name: str, +) -> BmbfProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + aliases = await _institution_aliases(normalized_id, organization_name) + today = datetime.now().strftime("%d.%m.%Y") + response = await elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + body={ + "size": 0, + "query": _alias_match_query("Zuwendungsempfänger", aliases), + "aggs": _project_status_filter_aggregations( + start_field="funding_start", + end_field="funding_end", + today=today, + ), + }, + cluster=ESCluster.INSE, + ) + aggregations = response.get("aggregations", {}) + return BmbfProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)), + upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)), + completed=int(aggregations.get("completed", {}).get("doc_count", 0)), + ) + + +def _project_status_filter_aggregations( + start_field: str, + end_field: str, + today: str, +) -> dict[str, Any]: + return { + "ongoing": { + "filter": { + "bool": { + "filter": [ + {"range": {start_field: {"lte": today}}}, + {"range": {end_field: {"gte": today}}}, + ] + } + } + }, + "upcoming": {"filter": {"range": {start_field: {"gt": today}}}}, + "completed": {"filter": {"range": {end_field: {"lt": today}}}}, + } + + async def get_dashboard_dfg_projects( institution_id: str, organization_name: str, diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index cc9e5084..03615c1d 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -8,8 +8,10 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( + get_dashboard_bmbf_project_statuses, get_dashboard_organization, get_dashboard_dfg_topics, + get_dashboard_eu_project_statuses, get_dashboard_patents, get_dashboard_statistics, get_top_authors, @@ -43,6 +45,109 @@ async def test_dashboard_patents_uses_org_patent_total(): search.assert_awaited_once_with(ORG_INSTITUTION_ID, page=0, size=0) +@pytest.mark.anyio +async def test_dashboard_eu_project_statuses_deduplicates_projects(): + async def scan(**kwargs): + assert kwargs["index"] == str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD) + assert kwargs["source"] == ["projectID"] + yield {"_source": {"projectID": "P2"}} + yield {"_source": {"projectID": "P1"}} + yield {"_source": {"projectID": "P1"}} + + response = { + "aggregations": { + "ongoing": {"projects": {"value": 2}}, + "upcoming": {"projects": {"value": 1}}, + "completed": {"projects": {"value": 7}}, + } + } + with patch( + "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as search: + result = await get_dashboard_eu_project_statuses( + ORG_INSTITUTION_ID, + "Example Org", + ) + + assert result.model_dump() == { + "institution_id": ORG_INSTITUTION_ID, + "organization_name": "Example Org", + "ongoing": 2, + "upcoming": 1, + "completed": 7, + } + call = search.await_args + assert call.kwargs["index"] == ESIndex.CORDIS_EU_PROJECTS_WILDCARD + assert call.kwargs["body"]["query"] == { + "terms": {"id": ["P1", "P2"]} + } + today = datetime.now().date().isoformat() + aggregations = call.kwargs["body"]["aggs"] + assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [ + {"range": {"startDate": {"lte": today}}}, + {"range": {"endDate": {"gte": today}}}, + ] + assert aggregations["upcoming"]["filter"] == { + "range": {"startDate": {"gt": today}} + } + assert aggregations["completed"]["filter"] == { + "range": {"endDate": {"lt": today}} + } + assert all( + aggregation["aggs"]["projects"]["cardinality"]["field"] == "id" + for aggregation in aggregations.values() + ) + + +@pytest.mark.anyio +async def test_dashboard_bmbf_project_statuses_uses_funding_dates(): + response = { + "aggregations": { + "ongoing": {"doc_count": 4}, + "upcoming": {"doc_count": 2}, + "completed": {"doc_count": 19}, + } + } + with patch( + "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as search: + result = await get_dashboard_bmbf_project_statuses( + ORG_INSTITUTION_ID, + "Example Org", + ) + + assert result.model_dump() == { + "institution_id": ORG_INSTITUTION_ID, + "organization_name": "Example Org", + "ongoing": 4, + "upcoming": 2, + "completed": 19, + } + call = search.await_args + assert call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1 + assert call.kwargs["body"]["query"]["bool"]["minimum_should_match"] == 1 + today = datetime.now().strftime("%d.%m.%Y") + aggregations = call.kwargs["body"]["aggs"] + assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [ + {"range": {"funding_start": {"lte": today}}}, + {"range": {"funding_end": {"gte": today}}}, + ] + assert aggregations["upcoming"]["filter"] == { + "range": {"funding_start": {"gt": today}} + } + assert aggregations["completed"]["filter"] == { + "range": {"funding_end": {"lt": today}} + } + + @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 adeee036..7fc1aaa1 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -24,6 +24,22 @@ export interface DashboardStatisticValue { value: number; } +export interface EuProjectStatusStatistics { + institution_id: string; + organization_name: string; + ongoing: number; + upcoming: number; + completed: number; +} + +export interface BmbfProjectStatusStatistics { + institution_id: string; + organization_name: string; + ongoing: number; + upcoming: number; + completed: number; +} + export interface DfgProjectTopic { id: string; name: string; @@ -137,6 +153,18 @@ export class DashboardStatisticsService { ); } + getEuProjectStatuses(): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`, + ); + } + + getBmbfProjectStatuses(): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`, + ); + } + getBmbfProjectCount(): Observable { return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`, diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index bd994ccf..7d0909bb 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -129,6 +129,63 @@

Die Kennzahlen konnten nicht geladen werden.

} + @if ( + euProjectStatusesLoading || + bmbfProjectStatusesLoading || + euProjectStatusesError || + bmbfProjectStatusesError || + (euProjectStatuses && bmbfProjectStatuses) + ) { +
+
+
+

Projektstatus nach Fördergeber

+

+ Laufende, kommende und abgeschlossene EU- und Bund-Projekte Ihrer Organisation. +

+
+ @if (euProjectStatuses && bmbfProjectStatuses) { +
+ + EU: + {{ + euProjectStatuses.ongoing + + euProjectStatuses.upcoming + + euProjectStatuses.completed | number + }} + + + Bund: + {{ + bmbfProjectStatuses.ongoing + + bmbfProjectStatuses.upcoming + + bmbfProjectStatuses.completed | number + }} + +
+ } +
+ + @if (euProjectStatusesLoading || bmbfProjectStatusesLoading) { +
+ +
+ } @else if (euProjectStatusesError || bmbfProjectStatusesError) { +

+ Der Status der EU- und Bund-Projekte konnte nicht geladen werden. +

+ } @else if (euProjectStatuses && bmbfProjectStatuses) { + + } +
+ } + @if (topicHeatmapLoading || topicHeatmapError || hasTopicHeatmapData()) {
diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 1d6d7718..45b1b471 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -144,6 +144,27 @@ place-items: center; } + .project-status-loading { + min-height: 15rem; + display: grid; + place-items: center; + } + + .project-status-summary { + display: flex; + flex: 0 0 auto; + gap: 0.5rem; + + span { + padding: 0.35rem 0.65rem; + border-radius: 999px; + background: #f1f5f9; + color: #475569; + font-size: 0.9rem; + font-weight: 600; + } + } + .dfg-topic-summary { flex: 0 0 auto; color: #475569; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index c7268ecd..0326f80f 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -5,13 +5,16 @@ import { Observable, finalize } from 'rxjs'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component'; import { DfgTopicDonutComponent } from './dfg-topic-donut/dfg-topic-donut.component'; +import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component'; import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { + BmbfProjectStatusStatistics, DashboardStatisticValue, DashboardStatistics, DashboardStatisticsService, DfgProjectTopics, + EuProjectStatusStatistics, TopAuthor, TopAuthorStatistics, TopAuthorsWorksPeriod, @@ -32,6 +35,7 @@ type DashboardStatisticKey = RouterLink, LoadingComponent, DfgTopicDonutComponent, + EuProjectStatusChartComponent, TopicHeatmapComponent, YearRangeSliderComponent, ], @@ -69,6 +73,12 @@ export class DashboardComponent implements OnInit { dfgProjectTopics?: DfgProjectTopics; dfgTopicsLoading = false; dfgTopicsError = false; + euProjectStatuses?: EuProjectStatusStatistics; + euProjectStatusesLoading = false; + euProjectStatusesError = false; + bmbfProjectStatuses?: BmbfProjectStatusStatistics; + bmbfProjectStatusesLoading = false; + bmbfProjectStatusesError = false; readonly topicTreemapMinYear = 1900; readonly topicTreemapMaxYear = new Date().getFullYear(); topicTreemapFromYear = this.topicTreemapMaxYear - 4; @@ -89,6 +99,8 @@ export class DashboardComponent implements OnInit { this.loadTopAuthors(); this.loadTopicHeatmap(); this.loadDfgProjectTopics(); + this.loadEuProjectStatuses(); + this.loadBmbfProjectStatuses(); } private loadStatistics(): void { @@ -326,6 +338,38 @@ export class DashboardComponent implements OnInit { }); } + private loadEuProjectStatuses(): void { + this.euProjectStatusesLoading = true; + this.euProjectStatusesError = false; + this.statisticsService + .getEuProjectStatuses() + .pipe(finalize(() => (this.euProjectStatusesLoading = false))) + .subscribe({ + next: (statuses) => { + this.euProjectStatuses = statuses; + }, + error: () => { + this.euProjectStatusesError = true; + }, + }); + } + + private loadBmbfProjectStatuses(): void { + this.bmbfProjectStatusesLoading = true; + this.bmbfProjectStatusesError = false; + this.statisticsService + .getBmbfProjectStatuses() + .pipe(finalize(() => (this.bmbfProjectStatusesLoading = false))) + .subscribe({ + next: (statuses) => { + this.bmbfProjectStatuses = statuses; + }, + error: () => { + this.bmbfProjectStatusesError = true; + }, + }); + } + private loadTopicHeatmap(): void { if (this.topicTreemapFromYear > this.topicTreemapToYear) { this.topicHeatmapLoading = false; diff --git a/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.html b/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.html new file mode 100644 index 00000000..0b9a9078 --- /dev/null +++ b/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.html @@ -0,0 +1,6 @@ + diff --git a/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.scss b/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.scss new file mode 100644 index 00000000..814f435c --- /dev/null +++ b/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.scss @@ -0,0 +1,4 @@ +.eu-project-status-chart { + width: 100%; + height: 300px; +} diff --git a/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.ts b/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.ts new file mode 100644 index 00000000..8211ea67 --- /dev/null +++ b/webapp/src/app/modules/dashboard/eu-project-status-chart/eu-project-status-chart.component.ts @@ -0,0 +1,108 @@ +import { Component, Input, OnChanges } from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +import { + BmbfProjectStatusStatistics, + EuProjectStatusStatistics, +} from '../dashboard-statistics.service'; + +@Component({ + selector: 'app-eu-project-status-chart', + imports: [NgxEchartsDirective], + templateUrl: './eu-project-status-chart.component.html', + styleUrl: './eu-project-status-chart.component.scss', +}) +export class EuProjectStatusChartComponent implements OnChanges { + @Input({ required: true }) statuses!: EuProjectStatusStatistics; + @Input({ required: true }) bmbfStatuses!: BmbfProjectStatusStatistics; + + options: EChartsOption = {}; + + ngOnChanges(): void { + const values = [ + { + name: 'Laufend', + data: [ + this.statuses?.ongoing ?? 0, + this.bmbfStatuses?.ongoing ?? 0, + ], + color: '#2563eb', + }, + { + name: 'Kommend', + data: [ + this.statuses?.upcoming ?? 0, + this.bmbfStatuses?.upcoming ?? 0, + ], + color: '#f59e0b', + }, + { + name: 'Abgeschlossen', + data: [ + this.statuses?.completed ?? 0, + this.bmbfStatuses?.completed ?? 0, + ], + color: '#64748b', + }, + ]; + + this.options = { + color: values.map((item) => item.color), + animationDuration: 500, + tooltip: { + trigger: 'axis', + axisPointer: { type: 'shadow' }, + confine: true, + valueFormatter: (value) => + `${Number(value ?? 0).toLocaleString('de-DE')} Projekte`, + }, + legend: { + top: 0, + left: 'center', + data: values.map((item) => item.name), + textStyle: { color: '#334155' }, + }, + grid: { top: 56, right: 24, bottom: 30, left: 24, containLabel: true }, + xAxis: { + type: 'value', + minInterval: 1, + name: 'Anzahl Projekte', + nameLocation: 'middle', + nameGap: 28, + axisLabel: { color: '#64748b' }, + splitLine: { lineStyle: { color: '#e2e8f0' } }, + }, + yAxis: { + type: 'category', + data: ['EU-Projekte', 'Bund-Projekte'], + axisTick: { show: false }, + axisLine: { show: false }, + axisLabel: { color: '#334155', fontWeight: 600 }, + }, + series: values.map((item, index) => ({ + name: item.name, + type: 'bar', + stack: 'status', + barWidth: 54, + data: item.data, + label: { + show: true, + position: 'inside', + formatter: (params) => + Number(params.value ?? 0) > 0 ? String(params.value) : '', + color: '#ffffff', + fontWeight: 700, + }, + itemStyle: { + borderRadius: + index === 0 + ? [6, 0, 0, 6] + : index === values.length - 1 + ? [0, 6, 6, 0] + : 0, + }, + })), + }; + } +} -- 2.56.1 From 537ab7adb5545f858786a9cf17419e6fbdf67095 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Fri, 24 Jul 2026 20:56:01 +0200 Subject: [PATCH 6/6] fix components --- .../dashboard/dashboard-statistics.service.ts | 43 +--------- .../dashboard/dashboard.component.html | 15 ++-- .../modules/dashboard/dashboard.component.ts | 78 ++++++++++++------- .../topic-treemap.component.html} | 2 +- .../topic-treemap.component.scss} | 0 .../topic-treemap/topic-treemap.component.ts} | 69 ++++++++-------- .../ui/topic-treemap/topic-treemap.models.ts | 44 +++++++++++ 7 files changed, 141 insertions(+), 110 deletions(-) rename webapp/src/app/{modules/dashboard/topic-heatmap/topic-heatmap.component.html => shared/ui/topic-treemap/topic-treemap.component.html} (95%) rename webapp/src/app/{modules/dashboard/topic-heatmap/topic-heatmap.component.scss => shared/ui/topic-treemap/topic-treemap.component.scss} (100%) rename webapp/src/app/{modules/dashboard/topic-heatmap/topic-heatmap.component.ts => shared/ui/topic-treemap/topic-treemap.component.ts} (89%) create mode 100644 webapp/src/app/shared/ui/topic-treemap/topic-treemap.models.ts diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 7fc1aaa1..7a38b2a9 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -3,6 +3,7 @@ import { Injectable, inject } from '@angular/core'; import { Observable } from 'rxjs'; import { Configuration } from '../../api'; +import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models'; export type TopAuthorsWorksPeriod = 'all_time' | 'last_5_years'; @@ -71,42 +72,6 @@ export interface TopAuthorStatistics { news: TopAuthor[]; } -export interface TopicHeatmapValue { - year: number; - count: number; - share: number; -} - -export interface TopicHeatmapField { - id: string; - name: string; - total: number; - values: TopicHeatmapValue[]; - subfields: TopicHeatmapSubfield[]; -} - -export interface TopicHeatmapSubfield { - id: string; - name: string; - total: number; - values: TopicHeatmapValue[]; - topics: TopicHeatmapTopic[]; -} - -export interface TopicHeatmapTopic { - id: string; - name: string; - total: number; - values: TopicHeatmapValue[]; -} - -export interface TopicHeatmap { - institution_id: string; - organization_name: string; - years: number[]; - fields: TopicHeatmapField[]; -} - export interface TopicWordCloudWord { id: string; name: string; @@ -194,15 +159,15 @@ export class DashboardStatisticsService { ); } - getTopicHeatmap( + getTopicTreemap( fromYear?: number, toYear?: number, - ): Observable { + ): Observable { const params: Record = {}; if (fromYear !== undefined) params['from_year'] = fromYear; if (toYear !== undefined) params['to_year'] = toYear; - return this.httpClient.get( + return this.httpClient.get( `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-heatmap`, { params }, ); diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 7d0909bb..ea290b7a 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -186,7 +186,7 @@
} - @if (topicHeatmapLoading || topicHeatmapError || hasTopicHeatmapData()) { + @if (topicTreemapLoading || topicTreemapError || hasTopicTreemapData()) {
@@ -205,7 +205,7 @@
- @if (topicHeatmapLoading) { + @if (topicTreemapLoading) {
- } @else if (topicHeatmapError) { + } @else if (topicTreemapError) {

Die Field-Treemap konnte nicht geladen werden.

} @else { - - + (selectedNodeIdChange)="onTopicTreemapNodeChange($event)" + (topicSelect)="onTopicTreemapTopicSelect($event)"> + }
} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 0326f80f..f6e3d6f2 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -3,11 +3,22 @@ import { DecimalPipe } from '@angular/common'; import { MatIconModule } from '@angular/material/icon'; import { Observable, finalize } from 'rxjs'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; -import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component'; +import { MatDialog } from '@angular/material/dialog'; import { DfgTopicDonutComponent } from './dfg-topic-donut/dfg-topic-donut.component'; import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component'; import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; +import { + TopicTreemapComponent, +} from '../../shared/ui/topic-treemap/topic-treemap.component'; +import { + TopicTreemapData, + TopicTreemapTopicSelect, +} from '../../shared/ui/topic-treemap/topic-treemap.models'; +import { + TopicWordCloudDialogComponent, + TopicWordCloudDialogData, +} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component'; import { BmbfProjectStatusStatistics, DashboardStatisticValue, @@ -18,7 +29,6 @@ import { TopAuthor, TopAuthorStatistics, TopAuthorsWorksPeriod, - TopicHeatmap, } from './dashboard-statistics.service'; type DashboardStatisticKey = | 'publications' @@ -36,7 +46,7 @@ type DashboardStatisticKey = LoadingComponent, DfgTopicDonutComponent, EuProjectStatusChartComponent, - TopicHeatmapComponent, + TopicTreemapComponent, YearRangeSliderComponent, ], templateUrl: './dashboard.component.html', @@ -67,9 +77,9 @@ export class DashboardComponent implements OnInit { topAuthorsLoading = false; topAuthorsError = false; topAuthorsWorksPeriod: TopAuthorsWorksPeriod = 'all_time'; - topicHeatmap?: TopicHeatmap; - topicHeatmapLoading = false; - topicHeatmapError = false; + topicTreemap?: TopicTreemapData; + topicTreemapLoading = false; + topicTreemapError = false; dfgProjectTopics?: DfgProjectTopics; dfgTopicsLoading = false; dfgTopicsError = false; @@ -85,19 +95,20 @@ export class DashboardComponent implements OnInit { topicTreemapToYear = this.topicTreemapMaxYear; selectedTopicTreemapNode?: string; private topicTreemapReloadQueued = false; - private topicHeatmapRequestId = 0; + private topicTreemapRequestId = 0; constructor( private statisticsService: DashboardStatisticsService, private route: ActivatedRoute, private router: Router, + private dialog: MatDialog, ) {} ngOnInit() { this.restoreTopicTreemapState(); this.loadStatistics(); this.loadTopAuthors(); - this.loadTopicHeatmap(); + this.loadTopicTreemap(); this.loadDfgProjectTopics(); this.loadEuProjectStatuses(); this.loadBmbfProjectStatuses(); @@ -171,8 +182,8 @@ export class DashboardComponent implements OnInit { ); } - hasTopicHeatmapData(): boolean { - return (this.topicHeatmap?.fields ?? []).some( + hasTopicTreemapData(): boolean { + return (this.topicTreemap?.fields ?? []).some( (field) => field.total > 0 || field.values.some((value) => value.count > 0), ); @@ -206,15 +217,15 @@ export class DashboardComponent implements OnInit { } onTopicTreemapRangeChange(): void { - this.topicHeatmapLoading = true; - this.topicHeatmapError = false; - this.topicHeatmapRequestId += 1; + this.topicTreemapLoading = true; + this.topicTreemapError = false; + this.topicTreemapRequestId += 1; this.updateTopicTreemapUrl(); if (this.topicTreemapReloadQueued) return; this.topicTreemapReloadQueued = true; setTimeout(() => { this.topicTreemapReloadQueued = false; - this.loadTopicHeatmap(); + this.loadTopicTreemap(); }); } @@ -223,6 +234,17 @@ export class DashboardComponent implements OnInit { this.updateTopicTreemapUrl(); } + onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { + this.dialog.open( + TopicWordCloudDialogComponent, + { + width: '85vw', + maxWidth: '92vw', + data: topic, + }, + ); + } + private restoreTopicTreemapState(): void { const params = this.route.snapshot.queryParamMap; this.topicTreemapFromYear = this.parseTreemapYear( @@ -370,34 +392,34 @@ export class DashboardComponent implements OnInit { }); } - private loadTopicHeatmap(): void { + private loadTopicTreemap(): void { if (this.topicTreemapFromYear > this.topicTreemapToYear) { - this.topicHeatmapLoading = false; - this.topicHeatmapError = true; + this.topicTreemapLoading = false; + this.topicTreemapError = true; return; } - const requestId = ++this.topicHeatmapRequestId; - this.topicHeatmapLoading = true; - this.topicHeatmapError = false; + const requestId = ++this.topicTreemapRequestId; + this.topicTreemapLoading = true; + this.topicTreemapError = false; this.statisticsService - .getTopicHeatmap(this.topicTreemapFromYear, this.topicTreemapToYear) + .getTopicTreemap(this.topicTreemapFromYear, this.topicTreemapToYear) .pipe( finalize(() => { - if (requestId === this.topicHeatmapRequestId) { - this.topicHeatmapLoading = false; + if (requestId === this.topicTreemapRequestId) { + this.topicTreemapLoading = false; } }), ) .subscribe({ - next: (heatmap) => { - if (requestId === this.topicHeatmapRequestId) { - this.topicHeatmap = heatmap; + next: (treemap) => { + if (requestId === this.topicTreemapRequestId) { + this.topicTreemap = treemap; } }, error: () => { - if (requestId === this.topicHeatmapRequestId) { - this.topicHeatmapError = true; + if (requestId === this.topicTreemapRequestId) { + this.topicTreemapError = true; } }, }); diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.html similarity index 95% rename from webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html rename to webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.html index 132e8773..16bea6b6 100644 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.html +++ b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.html @@ -1,4 +1,4 @@ -@if (heatmap?.fields?.length) { +@if (data?.fields?.length) { @if (selectedNodeId) {