From 652ff8db154277c271a900731c7a3254836f1088 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 18:39:08 +0200 Subject: [PATCH 1/3] changed news trend search to use new index & added test for top 20 news search --- service/src/main/inse/model.py | 1 + .../test_trend_strategies.py | 13 ++ .../inse/university_ranking/trend_logic.py | 112 ++++++++++++++---- .../university_ranking/trend_strategies.py | 83 +++++++------ 4 files changed, 149 insertions(+), 60 deletions(-) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index f5a0f79e..039a1367 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -68,6 +68,7 @@ class ESIndex(StrEnum): AKTUELLES = "aktuell" AKTUELLES_POSTPROC = "aktuell_postproc" + AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" diff --git a/service/src/main/inse/university_ranking/test_trend_strategies.py b/service/src/main/inse/university_ranking/test_trend_strategies.py index e4c063ef..b8bd8f9d 100644 --- a/service/src/main/inse/university_ranking/test_trend_strategies.py +++ b/service/src/main/inse/university_ranking/test_trend_strategies.py @@ -170,6 +170,19 @@ async def test_get_top_topics_for_entity_projects(): assert "items" in res +@pytest.mark.anyio +async def test_get_top_topics_for_entity_news(): + res = await get_top_topics_for_entity( + entity_id="UDE", + entity_type="institution", + start_year=2018, + end_year=2024, + search_type="news", + ) + assert isinstance(res, dict) + assert "items" in res + + @pytest.mark.anyio async def test_get_trend_data_delegation(): res = await get_trend_data( diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 753fb4a7..585ba653 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -456,31 +456,99 @@ async def get_top_topics_for_entity( if search_type == "news": try: - res = await elasticsearch.search( - index=ESIndex.AKTUELLES_POSTPROC.value, - body={ - "query": {"match_all": {}}, - "size": 0, - "_source": False, - "aggs": { - "top_topics": { - "terms": { - "field": "topics.display_name.keyword", - "size": DEFAULT_TOP_TOPICS_SIZE, + date_filter = TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year) + news_ids = [] + try: + async for hit in elasticsearch.scan( + index=ESIndex.AKTUELLES.value, + query={"bool": {"filter": [date_filter]}}, + source=["news_id"], + cluster=ESCluster.INSE, + ): + nid = hit.get("_id") or hit.get("_source", {}).get("news_id") + if nid: + news_ids.append(str(nid)) + except Exception as e: + logger.warning("Failed scanning aktuell for news IDs in date range: %s", e) + + topic_counts: Dict[str, int] = {} + if news_ids: + msearch_queries = [] + for i in range(0, len(news_ids), 2000): + chunk = news_ids[i : i + 2000] + payload = { + "query": { + "bool": { + "should": [ + {"ids": {"values": chunk}}, + {"terms": {"news_id.keyword": chunk}}, + {"terms": {"news_id": chunk}}, + ], + "minimum_should_match": 1, } - } - }, - }, - cluster=ESCluster.INSE, - ) - buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) - items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets] - total_hits = res.get("hits", {}).get("total", {}) - total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0) - sum_top = sum(b["count"] for b in items) - other_count = max(0, total_val - sum_top) + }, + "size": 0, + "_source": False, + "aggs": { + "top_topics": { + "terms": { + "field": "topic_matches.topic_display_name.keyword", + "size": 100, + } + } + }, + } + msearch_queries.append((ESIndex.AKTUELLES_OPENALEX_TOPICS.value, payload)) + + if msearch_queries: + try: + responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE) + for res in responses: + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + for b in buckets: + t_name = b["key"] + cnt = b["doc_count"] + topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt + except Exception as e: + logger.warning("Failed to aggregate news top topics via msearch: %s", e) + else: + # If no year filter bounds active or scan returned no IDs, aggregate all topics directly from openalex_topics + try: + res = await elasticsearch.search( + index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, + body={ + "query": {"match_all": {}}, + "size": 0, + "_source": False, + "aggs": { + "top_topics": { + "terms": { + "field": "topic_matches.topic_display_name.keyword", + "size": 100, + } + } + }, + }, + cluster=ESCluster.INSE, + ) + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + for b in buckets: + t_name = b["key"] + cnt = b["doc_count"] + topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt + except Exception as e: + logger.warning("Failed to fallback query news top topics: %s", e) + + sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True) + top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE] + items = [{"name": name, "count": count} for name, count in top_slice] + + sum_top = sum(count for name, count in top_slice) + total_topics = sum(topic_counts.values()) + other_count = max(0, total_topics - sum_top) if other_count > 0: items.append({"name": "Andere Themen", "count": other_count}) + return {"items": items} except Exception as e: logger.error("Failed to query top news topics for entity: %s", e) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index d313d49b..e6277f34 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -1066,11 +1066,24 @@ class NewsTrendStrategy(TrendStrategy): STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} - # Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs + # Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]: + news_ids: Set[str] = set() if fuzzy: term = t_name - es_query = {"match": {"topics.display_name": term}} + es_query = {"term": {"topic_matches.topic_display_name.keyword": term}} + try: + async for hit in elasticsearch.scan( + index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, + query=es_query, + source=["news_id"], + cluster=ESCluster.INSE, + ): + nid = hit.get("_source", {}).get("news_id") or hit.get("_id") + if nid: + news_ids.add(str(nid)) + except Exception as e: + logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e) else: if keywords and idx < len(keywords) and keywords[idx]: raw_kw = keywords[idx] @@ -1079,43 +1092,28 @@ class NewsTrendStrategy(TrendStrategy): term = t_name else: term = t_name - es_query = {"match": {"keywords": term}} - news_ids: Set[str] = set() - try: - async for hit in elasticsearch.scan( - index=ESIndex.AKTUELLES_POSTPROC.value, - query=es_query, - source=["news_id"], - cluster=ESCluster.INSE, - ): - nid = hit.get("_source", {}).get("news_id") - if nid: - news_ids.add(nid) - except Exception as e: - logger.warning("Failed to scan UDE news postproc: %s", e) - - # If non-fuzzy keyword search, also search article content fields in 'aktuell' index - if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: - try: - content_query = { - "query_string": { - "query": term, - "fields": AKTUELLES_SEARCH_FIELDS, - "default_operator": "AND", + # If non-fuzzy keyword search, search article content fields in 'aktuell' index + if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + try: + content_query = { + "query_string": { + "query": term, + "fields": AKTUELLES_SEARCH_FIELDS, + "default_operator": "AND", + } } - } - async for hit in elasticsearch.scan( - index=ESIndex.AKTUELLES.value, - query=content_query, - source=["news_id"], - cluster=ESCluster.INSE, - ): - nid = hit.get("_id") or hit.get("_source", {}).get("news_id") - if nid: - news_ids.add(nid) - except Exception as e: - logger.warning("Failed to scan UDE news content in aktuell: %s", e) + async for hit in elasticsearch.scan( + index=ESIndex.AKTUELLES.value, + query=content_query, + source=["news_id"], + cluster=ESCluster.INSE, + ): + nid = hit.get("_id") or hit.get("_source", {}).get("news_id") + if nid: + news_ids.add(str(nid)) + except Exception as e: + logger.warning("Failed to scan UDE news content in aktuell: %s", e) return list(news_ids) @@ -1134,7 +1132,16 @@ class NewsTrendStrategy(TrendStrategy): "query": { "bool": { "filter": [ - {"ids": {"values": chunk}}, + { + "bool": { + "should": [ + {"ids": {"values": chunk}}, + {"terms": {"news_id.keyword": chunk}}, + {"terms": {"news_id": chunk}}, + ], + "minimum_should_match": 1, + } + }, TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year), ] } -- 2.56.1 From 127c32dce7c4c81abf0778e62356010d3565548f Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 20:05:00 +0200 Subject: [PATCH 2/3] patched missmatch inside news (openalex id vs name) --- .../search-results-state.service.ts | 26 +++++++++++++------ .../uni-trend-parent.component.ts | 19 ++++++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index f9f9dd2d..2401dc97 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -132,14 +132,24 @@ export class SearchResultsStateService { // without a resolvable keyword are skipped when building the lookup map // so they can never collide on an `undefined` key and shadow a real one. readonly topicsList = computed(() => { - const list = this.keywords().map((kw) => { - const entry = this.selectedKeywordEntries().find( - (e) => - e.llm_keyword?.keyword?.trim().toLowerCase() === - kw.trim().toLowerCase(), - ); - return entry?.topic_mapping?.topic?.display_name ?? kw; - }); + const list = this.keywords() + .map((kw) => { + const normalized = kw.trim().toLowerCase(); + const entry = this.selectedKeywordEntries().find( + (e) => + e.llm_keyword?.keyword?.trim().toLowerCase() === normalized || + e.topic_mapping?.topic?.id?.trim().toLowerCase() === normalized, + ); + const displayName = entry?.topic_mapping?.topic?.display_name; + if (displayName && !displayName.startsWith('http')) { + return displayName; + } + if (kw.startsWith('http') || kw.includes('openalex.org/topics')) { + return ''; + } + return kw; + }) + .filter((t) => t.length > 0); return Array.from(new Set(list)); }); diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index dc5a10fd..c14ace0a 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -666,6 +666,25 @@ export class UniTrendParentComponent implements OnInit { ); const resolveEntityName = (s: TrendSeries): string => { + let rawName = s.entity_name || ''; + if (rawName.startsWith('news_topic_')) { + rawName = rawName.slice('news_topic_'.length); + } + if ( + rawName.startsWith('http://') || + rawName.startsWith('https://') || + rawName.includes('openalex.org/topics/') + ) { + const mapped = this.getMappedTopic(rawName); + if (mapped && !mapped.startsWith('http')) { + return mapped; + } + const match = this.state?.topics()?.find((t) => t.id === rawName); + if (match?.display_name) { + return match.display_name; + } + } + const cId = cleanId(s.entity_id); if (s.entity_type === 'institution') { -- 2.56.1 From 7adf12912f564d430f4e5407d49364d0303befd6 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 21:50:02 +0200 Subject: [PATCH 3/3] added resolver preloading and child component state management. (If something breaks in behavior, revert to this point) --- .../uni-trend-parent.component.html | 14 +- .../uni-trend-parent.component.ts | 78 +++++++--- .../src/app/resolvers/uni-trend.resolver.ts | 139 ++++++++++++++++-- 3 files changed, 194 insertions(+), 37 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 5766c149..8bf6fe4c 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -175,15 +175,15 @@
- @if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) { - - } @else if (rawTrendResponse()) { + @if (rawTrendResponse()) {
+ @if (isTrendLoading() || isPageResolving()) { +
+ +

Daten werden geladen...

+
+ } @if (selectedTrendTopics().length > 0) {
@for (topic of selectedTrendTopics(); track topic) { diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index c14ace0a..91049ea7 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -530,14 +530,23 @@ export class UniTrendParentComponent implements OnInit { if (!res || !res.series || res.series.length === 0) return false; const startYr = this.startYear(); const endYr = this.endYear(); - const mapped = this.getMappedTopic(topic).toLowerCase().trim(); + const topicLower = topic.toLowerCase().trim(); + const mappedLower = this.getMappedTopic(topic).toLowerCase().trim(); return !res.series.some((s) => { - const yearlyList = - s.topic_data?.[topic] || - s.topic_data?.[mapped] || - Object.values(s.topic_data || {})[0]; - if (!yearlyList) return false; + if (!s.topic_data) return false; + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === topicLower || + kLower === mappedLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === topicLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; const total = yearlyList .filter((y) => y.year >= startYr && y.year <= endYr) .reduce((sum, item) => sum + (item.raw || 0), 0); @@ -545,6 +554,12 @@ export class UniTrendParentComponent implements OnInit { }); } + findFirstNonEmptyTopic(topics: string[]): string { + if (!topics || topics.length === 0) return ''; + const nonEmpties = topics.filter((t) => !this.isTopicEmpty(t)); + return nonEmpties.length > 0 ? nonEmpties[0] : topics[0] || ''; + } + isVisible(id: string): boolean { return this.entityVisibilityMap().get(id) !== false; } @@ -892,10 +907,10 @@ export class UniTrendParentComponent implements OnInit { if (resolved.topics && resolved.topics.length > 0) { this.selectedTrendTopics.set(resolved.topics); this.fetchedTopics.set([...resolved.topics]); - const firstNonEmpty = resolved.topics.find( - (t: string) => !this.isTopicEmpty(t), - ); - const targetTopic = firstNonEmpty || resolved.topics[0]; + const targetTopic = + resolved.initialActiveTopic || + resolved.topics.find((t: string) => !this.isTopicEmpty(t)) || + resolved.topics[0]; this.activeChartTopic.set(targetTopic); } else { this.fetchedTopics.set([...this.selectedTrendTopics()]); @@ -929,6 +944,14 @@ export class UniTrendParentComponent implements OnInit { this.fetchedAuthors.set([...this.comparisonAuthors()]); } + if (resolved.topSuggestions) { + this.topSuggestions.set(resolved.topSuggestions); + } + + if (resolved.recommendedAuthors) { + this.recommendedAuthors.set(resolved.recommendedAuthors); + } + if (resolved.treemapData) { this.topicTreemap.set(resolved.treemapData); } @@ -972,11 +995,20 @@ export class UniTrendParentComponent implements OnInit { this.selectedTrendTopics.set(topics); } - // Initialize active chart topic to the first selected topic if empty or invalid + // Initialize active chart topic to a valid non-empty topic const active = currentActive; const updatedSelections = untracked(() => this.selectedTrendTopics()); - if (!active || !updatedSelections.includes(active)) { - this.activeChartTopic.set(updatedSelections[0] || ''); + const mappedActive = this.getMappedTopic(active); + if ( + mappedActive && + updatedSelections.includes(mappedActive) && + !this.isTopicEmpty(mappedActive) + ) { + this.activeChartTopic.set(mappedActive); + } else { + this.activeChartTopic.set( + this.findFirstNonEmptyTopic(updatedSelections), + ); } // If comparison list is empty, initialize default institutions/authors dynamically @@ -1048,7 +1080,11 @@ export class UniTrendParentComponent implements OnInit { : a.id.toLowerCase(); return rawSeriesCleanIds.has(cleanA); }); - } else if (searchType === 'news' || searchType === 'all') { + } else if ( + searchType === 'news' || + searchType === 'all' || + searchType === 'patents' + ) { allEntitiesFetched = true; } else { // publications, patents, projects @@ -1399,7 +1435,11 @@ export class UniTrendParentComponent implements OnInit { if (kws.length === 0) return; const topics = this.state?.topicsList() ?? kws; - const topic = topics[0] || kws[0] || 'Artificial Intelligence'; + const topic = + this.findFirstNonEmptyTopic(topics) || + topics[0] || + kws[0] || + 'Artificial Intelligence'; this.personsApiService .searchPersonsList( @@ -1595,7 +1635,6 @@ export class UniTrendParentComponent implements OnInit { }); } this.isTrendLoading.set(false); - this.updateUrlParams(); }, error: () => { this.isTrendLoading.set(false); @@ -1695,8 +1734,8 @@ export class UniTrendParentComponent implements OnInit { this.selectedTrendTopics.set(updated); const active = this.activeChartTopic(); - if (!updated.includes(active)) { - this.activeChartTopic.set(updated[0] || ''); + if (!updated.includes(active) || this.isTopicEmpty(active)) { + this.activeChartTopic.set(this.findFirstNonEmptyTopic(updated)); } } @@ -1871,13 +1910,12 @@ export class UniTrendParentComponent implements OnInit { } } - // Topic tab toggle (data reuses instantly) + // Topic tab toggle (data reuses instantly, no router navigation to prevent chart flickering) updateActiveChartTopic(topic: string) { if (this.isTopicEmpty(topic)) { return; } this.activeChartTopic.set(topic); - this.updateUrlParams(); } // Autocomplete query changes for institutions diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index b61b49fa..9eef6b9e 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -1,8 +1,13 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { catchError, of, Observable, map } from 'rxjs'; -import { TrendResponse, UniversityRankingsService } from '../api'; +import { catchError, of, Observable, map, forkJoin } from 'rxjs'; +import { + TrendResponse, + UniversityRankingsService, + PersonsService, +} from '../api'; import { SearchResultsStateService } from '../modules/keywords-search/search-results/search-results-state.service'; +import { CredentialService } from '../shared/services/credential.service'; export interface CompareItem { id: string; @@ -19,6 +24,9 @@ export interface UniTrendResolvedData { countries: CompareItem[]; regions: CompareItem[]; authors: CompareItem[]; + initialActiveTopic?: string; + topSuggestions?: any[]; + recommendedAuthors?: any[]; treemapNode?: string | null; } @@ -28,11 +36,18 @@ export const uniTrendResolver: ResolveFn = ( ): Observable => { const params = route.queryParamMap; const searchState = inject(SearchResultsStateService, { optional: true }); + const credentialService = inject(CredentialService, { optional: true }); const searchType = params.get('search_type') || 'publications'; const fuzzy = params.get('fuzzy') !== 'false'; const treemapNode = params.get('treemapNode'); + // Primary institution from user token / credential service + const primaryInstId = + credentialService?.effectiveInstitutionId() || 'I62318514'; + const primaryInstName = + credentialService?.organizationName() || 'Universität Duisburg-Essen'; + // Extract keywords & topics let keywords = params.getAll('keyword'); if (keywords.length === 0) { @@ -79,9 +94,17 @@ export const uniTrendResolver: ResolveFn = ( const cleanId = parts[0].includes('/') ? parts[0].split('/').pop() || parts[0] : parts[0]; - return { id: cleanId, name: parts[1] || cleanId }; + const isPrimary = + cleanId.toLowerCase() === primaryInstId.toLowerCase() || + primaryInstId.toLowerCase().includes(cleanId.toLowerCase()); + const name = parts[1] || (isPrimary ? primaryInstName : parts[0]); + return { id: cleanId, name }; }); + if (parsedInstitutions.length === 0 && searchType !== 'authors') { + parsedInstitutions.push({ id: primaryInstId, name: primaryInstName }); + } + const countryParams = params.getAll('countries'); const parsedCountries: CompareItem[] = countryParams.map((c) => { const parts = c.split('|'); @@ -103,15 +126,22 @@ export const uniTrendResolver: ResolveFn = ( const instIds = parsedInstitutions.length > 0 ? parsedInstitutions.map((i) => i.id) - : ['I62318514']; + : [primaryInstId]; const countryIds = parsedCountries.length > 0 ? parsedCountries.map((c) => c.id) : ['DE']; const regionIds = parsedRegions.map((r) => r.id); const authorIds = parsedAuthors.map((a) => a.id); const apiService = inject(UniversityRankingsService); + const personsService = inject(PersonsService, { optional: true }); - return apiService + const primaryTopic = topics[0] || 'Artificial Intelligence'; + const countryFilter = + parsedCountries.length > 0 ? parsedCountries[0].id : undefined; + const regionFilter = + parsedRegions.length > 0 ? parsedRegions[0].id : undefined; + + const trendObs$ = apiService .getTrendApiInseServiceUniversityRankingsTrendGet( topics, keywords, @@ -122,9 +152,94 @@ export const uniTrendResolver: ResolveFn = ( authorIds, searchType as any, ) - .pipe( - catchError(() => of(null)), - map((trendResponse) => ({ + .pipe(catchError(() => of(null))); + + const topInstObs$ = + searchType !== 'authors' + ? apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + primaryTopic, + regionFilter, + countryFilter, + 6, + ) + .pipe(catchError(() => of([]))) + : of([]); + + const recAuthorsObs$ = + searchType === 'authors' && personsService + ? personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, + ) + .pipe( + map((res: any) => res.results || []), + catchError(() => of([])), + ) + : of([]); + + return forkJoin({ + trendResponse: trendObs$, + topSuggestions: topInstObs$, + recommendedAuthors: recAuthorsObs$, + }).pipe( + map(({ trendResponse, topSuggestions, recommendedAuthors }) => { + // Find the first topic with non-zero publication data + let initialActiveTopic = primaryTopic; + if ( + trendResponse?.series && + trendResponse.series.length > 0 && + topics.length > 0 + ) { + const nonEmptyTopic = topics.find((t) => + trendResponse.series.some((s) => { + if (!s.topic_data) return false; + const tLower = t.toLowerCase().trim(); + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === tLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === tLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; + const total = yearlyList.reduce( + (sum, item) => sum + (item.raw || 0), + 0, + ); + return total > 0; + }), + ); + if (nonEmptyTopic) { + initialActiveTopic = nonEmptyTopic; + } + } + + // If in author mode and no explicit authors were passed in URL, populate default top authors + if ( + searchType === 'authors' && + parsedAuthors.length === 0 && + recommendedAuthors?.length + ) { + recommendedAuthors.slice(0, 3).forEach((author: any) => { + parsedAuthors.push({ + id: author.id, + name: author.display_name || 'Unbekannt', + }); + }); + } + + return { trendResponse, searchType, topics, @@ -134,7 +249,11 @@ export const uniTrendResolver: ResolveFn = ( countries: parsedCountries, regions: parsedRegions, authors: parsedAuthors, + initialActiveTopic, + topSuggestions: topSuggestions as any[], + recommendedAuthors: recommendedAuthors as any[], treemapNode, - })), - ); + }; + }), + ); }; -- 2.56.1