From fa9def349c05754b2838efa93e32f93ec94219cd Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 31 Jul 2026 13:22:29 +0200 Subject: [PATCH 1/7] fuzzy search does not work --- .../inse/university_ranking/trend_logic.py | 21 +- .../university_ranking/trend_query_builder.py | 78 +- .../university_ranking/trend_strategies.py | 23 +- .../university-ranking/models/trend.models.ts | 61 + .../services/trend-data.service.ts | 212 +++ .../uni-pie-chart/uni-pie-chart.component.ts | 19 +- .../uni-trend-chart.component.ts | 25 +- .../uni-trend-parent.component.html | 16 +- .../uni-trend-parent.component.ts | 1152 +++-------------- .../university-ranking/utils/trend.utils.ts | 108 ++ .../src/app/resolvers/uni-trend.resolver.ts | 84 +- 11 files changed, 781 insertions(+), 1018 deletions(-) create mode 100644 webapp/src/app/modules/university-ranking/models/trend.models.ts create mode 100644 webapp/src/app/modules/university-ranking/services/trend-data.service.ts create mode 100644 webapp/src/app/modules/university-ranking/utils/trend.utils.ts diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 585ba653..733760ca 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -128,12 +128,23 @@ async def get_top_institutions_by_region( meta_top = await TrendMetadataResolver.resolve_all(topics=[topic]) topic_id = meta_top.get("resolved_topic_ids", {}).get(topic) + topic_display_name = meta_top.get("resolved_topic_names", {}).get(topic, topic) - topic_filter = ( - {"term": {"topics.id.keyword": topic_id}} - if topic_id - else {"match_phrase": {"topics.display_name": topic}} - ) + if not topic_id and (topic.startswith("https://openalex.org/") or (topic.startswith("T") and topic[1:].isdigit())): + topic_id = topic if topic.startswith("https://openalex.org/") else f"https://openalex.org/{topic}" + + if topic_id: + topic_filter = { + "bool": { + "should": [ + {"term": {"topics.id.keyword": topic_id}}, + {"term": {"topics.id": topic_id}}, + ], + "minimum_should_match": 1, + } + } + else: + topic_filter = {"match_phrase": {"topics.display_name": topic_display_name}} must_clauses: List[Dict[str, Any]] = [ {"term": {"type": "education"}}, diff --git a/service/src/main/inse/university_ranking/trend_query_builder.py b/service/src/main/inse/university_ranking/trend_query_builder.py index 573c72e7..cb93db74 100644 --- a/service/src/main/inse/university_ranking/trend_query_builder.py +++ b/service/src/main/inse/university_ranking/trend_query_builder.py @@ -12,15 +12,18 @@ DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" def clean_inst_id(id_str: str) -> str: - """Extracts short OpenAlex ID from full URL or returns as-is.""" + """Extracts short OpenAlex ID from full URL or returns as-is, ensuring uppercase prefix.""" if not id_str: return "" s = id_str.strip() - return s.split("/")[-1] if "/" in s else s + raw_id = s.split("/")[-1] if "/" in s else s + if len(raw_id) > 1 and raw_id[0].isalpha(): + return raw_id[0].upper() + raw_id[1:] + return raw_id.upper() def to_full_inst_url(id_str: str) -> str: - """Ensures institution ID is formatted as a full OpenAlex URL.""" + """Ensures institution ID is formatted as a full OpenAlex URL with proper capitalization.""" cleaned = clean_inst_id(id_str) return f"https://openalex.org/{cleaned}" if cleaned else id_str @@ -85,8 +88,9 @@ class TrendMetadataResolver: alias_results = await asyncio.gather(*(get_alias(i) for i in inst_full_ids)) for short_id, alias_list in alias_results: - aliases_map[short_id] = alias_list - aliases_map[f"https://openalex.org/{short_id}"] = alias_list + s_upper = clean_inst_id(short_id) + aliases_map[s_upper] = alias_list + aliases_map[f"https://openalex.org/{s_upper}"] = alias_list except Exception as e: logger.warning("Failed to resolve institutions from ES: %s", e) @@ -142,31 +146,65 @@ class TrendMetadataResolver: async def fetch_topics(): topic_ids: Dict[str, str] = {} + topic_display_names: Dict[str, str] = {} if not topic_names: - return topic_ids + return topic_ids, topic_display_names + + should_clauses = [] + for t in topic_names: + if not t: + continue + clean_id = clean_inst_id(t) + canonical_id = f"https://openalex.org/{clean_id}" if clean_id.startswith("T") else t + if t.startswith("https://openalex.org/") or (clean_id.startswith("T") and clean_id[1:].isdigit()): + should_clauses.extend([ + {"term": {"id": canonical_id}}, + {"term": {"id.keyword": canonical_id}}, + {"term": {"id": clean_id}}, + {"term": {"id.keyword": clean_id}}, + ]) + else: + should_clauses.append({"match_phrase": {"display_name": t}}) try: res = await elasticsearch.search( index=ESIndex.OPENALEX_TOPICS.value, - query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}}, - size=len(topic_names) * 2, + query={"bool": {"should": should_clauses, "minimum_should_match": 1}}, + size=max(10, len(topic_names) * 3), source=["id", "display_name"], cluster="nes", ) for hit in res.get("hits", {}).get("hits", []): src = hit["_source"] + full_id = src.get("id", "") + short_id = clean_inst_id(full_id) + canonical_id = f"https://openalex.org/{short_id}" if short_id.startswith("T") else full_id d_name = src.get("display_name", "") for t in topic_names: - if t.lower() in d_name.lower(): - topic_ids[t] = src["id"] + t_clean = clean_inst_id(t) + t_canonical = f"https://openalex.org/{t_clean}" if t_clean.startswith("T") else t + if ( + t == full_id + or t == short_id + or t == canonical_id + or t_canonical == canonical_id + or t_clean == short_id + or t.lower() in d_name.lower() + or d_name.lower() in t.lower() + ): + topic_ids[t] = canonical_id + topic_display_names[t] = d_name + topic_display_names[canonical_id] = d_name + topic_display_names[short_id] = d_name + topic_display_names[full_id] = d_name except Exception as e: logger.warning("Failed to resolve topic IDs from ES: %s", e) - return topic_ids + return topic_ids, topic_display_names ( (inst_names, inst_country_codes, inst_aliases), country_names, (continent_names, continent_country_codes), - resolved_topic_ids, + (resolved_topic_ids, resolved_topic_names), ) = await asyncio.gather( fetch_institutions(), fetch_countries(), @@ -182,6 +220,7 @@ class TrendMetadataResolver: "continent_names": continent_names, "continent_country_codes": continent_country_codes, "resolved_topic_ids": resolved_topic_ids, + "resolved_topic_names": resolved_topic_names, } @@ -196,6 +235,12 @@ class TrendQueryBuilder: fuzzy: bool = True, ) -> Dict[str, Any]: """Builds a topic or keyword matching clause.""" + target_id = resolved_topic_id + if not target_id and topic_display_name: + c_id = clean_inst_id(topic_display_name) + if c_id.startswith("T") and c_id[1:].isdigit(): + target_id = f"https://openalex.org/{c_id}" + if not fuzzy and keyword: return { "bool": { @@ -208,12 +253,15 @@ class TrendQueryBuilder: "minimum_should_match": 1, } } - elif resolved_topic_id: + elif target_id: + c_id = clean_inst_id(target_id) + canonical_id = f"https://openalex.org/{c_id}" if c_id.startswith("T") else target_id + target_ids = list(dict.fromkeys([canonical_id, target_id, c_id])) return { "bool": { "should": [ - {"nested": {"path": "topics", "query": {"term": {"topics.id": resolved_topic_id}}}}, - {"term": {"primary_topic.id": resolved_topic_id}}, + {"nested": {"path": "topics", "query": {"terms": {"topics.id": target_ids}}}}, + {"terms": {"primary_topic.id": target_ids}}, ], "minimum_should_match": 1, } diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index e6277f34..21ad15c4 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -316,7 +316,7 @@ class AuthorsTrendStrategy(TrendStrategy): if not query_authors: return TrendResponse(series=[], years=years_range) - query_authors_clean = [clean_inst_id(a).upper() for a in query_authors if a] + query_authors_clean = [clean_inst_id(a) for a in query_authors if a] # Resolve author display names resolved_names: Dict[str, str] = {} @@ -329,7 +329,7 @@ class AuthorsTrendStrategy(TrendStrategy): cluster=ESCluster.NES, ) for hit in res.get("hits", {}).get("hits", []): - short_id = hit["_id"] + short_id = clean_inst_id(hit["_id"]) full_id = f"https://openalex.org/{short_id}" display_name = hit["_source"].get("display_name", short_id) resolved_names[short_id] = display_name @@ -340,14 +340,12 @@ class AuthorsTrendStrategy(TrendStrategy): meta = await TrendMetadataResolver.resolve_all(topics=topics) resolved_topic_ids = meta["resolved_topic_ids"] - query_authors_full = [ - a if a.startswith("https://openalex.org/") else f"https://openalex.org/{clean_inst_id(a).upper()}" - for a in query_authors - ] + query_authors_full = [to_full_inst_url(a) for a in query_authors if a] filters_map: Dict[str, Dict[str, Any]] = {} for auth_id, auth_url in zip(query_authors, query_authors_full): - filters_map[f"author_{auth_id}"] = { + clean_id = clean_inst_id(auth_id) + filters_map[f"author_{clean_id}"] = { "nested": { "path": "authorships", "query": {"term": {"authorships.author.id": auth_url}}, @@ -508,16 +506,17 @@ class PatentsTrendStrategy(TrendStrategy): def matches_patent(patent, topic: str, keyword: Optional[str], is_fuzzy: bool) -> bool: if matches_topic(patent, topic): return True - if not is_fuzzy and keyword: + t_lower = topic.lower() + if patent.title and t_lower in patent.title.lower(): + return True + if patent.abstract and t_lower in patent.abstract.lower(): + return True + if keyword: kw_lower = keyword.lower() if patent.title and kw_lower in patent.title.lower(): return True if patent.abstract and kw_lower in patent.abstract.lower(): return True - if patent.openalex_topics: - for ot in patent.openalex_topics: - if ot.topic_display_name and kw_lower in ot.topic_display_name.lower(): - return True return False accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { diff --git a/webapp/src/app/modules/university-ranking/models/trend.models.ts b/webapp/src/app/modules/university-ranking/models/trend.models.ts new file mode 100644 index 00000000..9e049604 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/models/trend.models.ts @@ -0,0 +1,61 @@ +import { TrendSeries } from '../../../api'; + +export interface CompareItem { + id: string; + name: string; +} + +export interface TrendStrategyConfig { + showInstitutionSelector: boolean; + showLocationSelector: boolean; + showAuthorSelector: boolean; + yAxisLabel: string; + chartTitle: string; +} + +export type TrendSeriesWithVisibility = TrendSeries & { visible?: boolean }; + +export const TREND_CONFIGS: Record = { + publications: { + showInstitutionSelector: true, + showLocationSelector: true, + showAuthorSelector: false, + yAxisLabel: 'Publikationen', + chartTitle: 'Publikationstrends', + }, + authors: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: true, + yAxisLabel: 'Publikationen von Autoren', + chartTitle: 'Autorentrends', + }, + patents: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Patentanmeldungen', + chartTitle: 'Patentrecherche-Trends', + }, + projects: { + showInstitutionSelector: true, + showLocationSelector: true, + showAuthorSelector: false, + yAxisLabel: 'Projektförderung (Anz)', + chartTitle: 'Drittmittelförderung-Trends', + }, + news: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Pressemitteilungen', + chartTitle: 'Nachrichtentrends', + }, + all: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Aktivitäts-Index', + chartTitle: 'Cross-Domain-Themenlebenszyklus (UDE)', + }, +}; diff --git a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts new file mode 100644 index 00000000..106bf141 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts @@ -0,0 +1,212 @@ +import { Injectable, inject, signal } from '@angular/core'; +import { + UniversityRankingsService, + PersonsService, + TrendResponse, + TopInstitutionItem, + Author, +} from '../../../api'; +import { cleanEntityId } from '../utils/trend.utils'; + +export interface TrendRequestParams { + topics: string[]; + keywords?: string[]; + fuzzy: boolean; + institutions?: string[]; + countries?: string[]; + regions?: string[]; + authors?: string[]; + searchType: string; +} + +@Injectable({ + providedIn: 'root', +}) +export class TrendDataService { + private readonly apiService = inject(UniversityRankingsService); + private readonly personsApiService = inject(PersonsService); + + // Soft cache signals + readonly cachedResponse = signal(null); + readonly cachedParams = signal(null); + + // Secondary data signals + readonly topSuggestions = signal([]); + readonly recommendedAuthors = signal([]); + readonly topTopicsData = signal<{ value: number; name: string }[]>([]); + + // Loading signals + readonly isSuggestionsLoading = signal(false); + readonly isTopTopicsLoading = signal(false); + readonly topTopicsError = signal(false); + + /** + * Updates soft cache with response and params from resolver or component. + */ + updateCache(response: TrendResponse, params: TrendRequestParams): void { + this.cachedResponse.set(response); + this.cachedParams.set(params); + } + + /** + * Checks if requested params can be satisfied by cached response. + */ + canReuseCache(newParams: TrendRequestParams): boolean { + const currentResp = this.cachedResponse(); + const currentParams = this.cachedParams(); + if (!currentResp || !currentParams) return false; + + if (currentParams.searchType !== newParams.searchType) return false; + if (currentParams.fuzzy !== newParams.fuzzy) return false; + + // Topics check + const currentTopics = [...currentParams.topics].sort().join(','); + const targetTopics = [...newParams.topics].sort().join(','); + if (currentTopics !== targetTopics) return false; + + // Check if new entities are a subset of cached entities + const currentInsts = new Set( + (currentParams.institutions || []).map(cleanEntityId), + ); + const targetInsts = (newParams.institutions || []).map(cleanEntityId); + if (!targetInsts.every((id) => currentInsts.has(id))) return false; + + const currentAuthors = new Set( + (currentParams.authors || []).map(cleanEntityId), + ); + const targetAuthors = (newParams.authors || []).map(cleanEntityId); + if (!targetAuthors.every((id) => currentAuthors.has(id))) return false; + + return true; + } + + /** + * Loads top 10 research topics for a selected pie entity. + */ + loadTopTopicsForEntity( + entityId: string, + entityType: string, + startYear: number, + endYear: number, + searchType: string, + ): void { + if (!entityId || searchType === 'all') { + this.topTopicsData.set([]); + return; + } + + this.isTopTopicsLoading.set(true); + this.topTopicsError.set(false); + + const cleanId = cleanEntityId(entityId); + + this.apiService + .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + cleanId, + entityType, + startYear, + endYear, + searchType, + ) + .subscribe({ + next: (res) => { + const mapped = (res.items || []).map((item) => ({ + value: item.count, + name: item.name, + })); + this.topTopicsData.set(mapped); + this.isTopTopicsLoading.set(false); + }, + error: (err) => { + console.error('Failed to load top topics:', err); + this.topTopicsError.set(true); + this.isTopTopicsLoading.set(false); + this.topTopicsData.set([]); + }, + }); + } + + /** + * Loads top institution suggestions based on topic/country/region. + */ + loadInstitutionSuggestions( + topic: string, + countryFilter?: string, + regionFilter?: string, + ): void { + this.isSuggestionsLoading.set(true); + + this.apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic, + regionFilter, + countryFilter, + 6, + ) + .subscribe({ + next: (res: any) => { + this.topSuggestions.set(res || []); + this.isSuggestionsLoading.set(false); + }, + error: () => { + this.topSuggestions.set([]); + this.isSuggestionsLoading.set(false); + }, + }); + } + + /** + * Loads recommended authors for selected topic and institution. + */ + loadRecommendedAuthors(topic: string, primaryInstId: string): void { + this.isSuggestionsLoading.set(true); + const cleanInst = cleanEntityId(primaryInstId) || 'I62318514'; + + this.personsApiService + .searchPersonsList( + undefined, + cleanInst, + 'cited_by_count', + 'desc', + [topic], + 1, + 6, + undefined, + ) + .subscribe({ + next: (res) => { + if (res.results && res.results.length > 0) { + this.recommendedAuthors.set(res.results); + this.isSuggestionsLoading.set(false); + } else { + // Global fallback search across all institutions + this.personsApiService + .searchPersonsList( + undefined, + undefined, + 'cited_by_count', + 'desc', + [topic], + 1, + 6, + undefined, + ) + .subscribe({ + next: (globalRes) => { + this.recommendedAuthors.set(globalRes.results || []); + this.isSuggestionsLoading.set(false); + }, + error: () => { + this.recommendedAuthors.set([]); + this.isSuggestionsLoading.set(false); + }, + }); + } + }, + error: () => { + this.recommendedAuthors.set([]); + this.isSuggestionsLoading.set(false); + }, + }); + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts index 5af1bc32..c7b4b8cb 100644 --- a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts @@ -143,7 +143,24 @@ export class UniPieChartComponent { }; } - Object.entries(series.topic_data).forEach(([topicName, yearlyItems]) => { + const seenTopics = new Set(); + const entries = Object.entries(series.topic_data); + const hasDisplayNameKeys = entries.some( + ([name]) => !name.startsWith('http') && !/^T\d+$/i.test(name), + ); + + entries.forEach(([topicName, yearlyItems]) => { + const isRawId = + topicName.startsWith('http') || /^T\d+$/i.test(topicName); + if (hasDisplayNameKeys && isRawId) { + return; + } + const normKey = topicName.toLowerCase().trim(); + if (seenTopics.has(normKey)) { + return; + } + seenTopics.add(normKey); + const filtered = (yearlyItems || []).filter( (y) => y.year >= startYr && y.year <= endYr, ); diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 3893029d..a52682a3 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -38,19 +38,30 @@ export class UniTrendChartComponent { const years = trendData.years.filter((y) => y >= startYr && y <= endYr); const xAxisData = years.map(String); - // Resolve the active topic to compare one at a time to prevent line overlaps const availableKeys = Object.keys(trendData.series[0].topic_data || {}); const displayNameKeys = availableKeys.filter( (k) => !/^T\d+$/i.test(k) && !k.startsWith('http'), ); const topics = displayNameKeys.length > 0 ? displayNameKeys : availableKeys; const active = this.activeTopic(); - const selectedTopic = - active && (availableKeys.includes(active) || topics.includes(active)) - ? active - : topics.length > 0 - ? topics[0] - : null; + + let selectedTopic: string | null = null; + if (active) { + if (availableKeys.includes(active)) { + selectedTopic = active; + } else { + const foundKey = availableKeys.find( + (k) => k.toLowerCase().trim() === active.toLowerCase().trim(), + ); + if (foundKey) { + selectedTopic = foundKey; + } + } + } + + if (!selectedTopic) { + selectedTopic = topics.length > 0 ? topics[0] : availableKeys[0] || null; + } if (!selectedTopic) { return {}; 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 8bf6fe4c..82362c53 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 @@ -136,7 +136,7 @@ [primaryInstitutionName]="primaryInstitutionName()" [topSuggestions]="topSuggestions()" [isSuggestionsLoading]="isSuggestionsLoading()" - [activeChartTopic]="activeChartTopic()" + [activeChartTopic]="mappedActiveChartTopic()" [searchQuery]="searchQuery()" [searchResults]="searchResults()" [getEntityColor]="boundGetEntityColor" @@ -158,7 +158,7 @@ [comparisonAuthors]="comparisonAuthors()" [topSuggestions]="recommendedAuthors()" [isSuggestionsLoading]="isSuggestionsLoading()" - [activeChartTopic]="activeChartTopic()" + [activeChartTopic]="mappedActiveChartTopic()" [searchQuery]="authorSearchQuery()" [searchResults]="authorSearchResults()" [getEntityColor]="boundGetEntityColor" @@ -189,20 +189,20 @@ @for (topic of selectedTrendTopics(); track topic) { @if (selectedSearchType() === 'news') { - } @else if (selectedTrendTopics().length > 1) { + } @else { } @@ -212,7 +212,7 @@ 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 a78965e4..d912b14d 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 @@ -8,7 +8,6 @@ import { untracked, inject, OnInit, - DestroyRef, } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { CommonModule } from '@angular/common'; @@ -67,67 +66,17 @@ import { } from '../../../shared/ui/topic-treemap/topic-treemap.models'; import { TopicsService } from '../../../api/api/topics.service'; -export interface CompareItem { - id: string; - name: string; -} - -export interface TrendStrategyConfig { - showInstitutionSelector: boolean; - showLocationSelector: boolean; - showAuthorSelector: boolean; - yAxisLabel: string; - chartTitle: string; -} - -export const TREND_CONFIGS: Record = { - publications: { - showInstitutionSelector: true, - showLocationSelector: true, - showAuthorSelector: false, - yAxisLabel: 'Publikationen', - chartTitle: 'Publikationstrends', - }, - authors: { - showInstitutionSelector: false, - showLocationSelector: false, - showAuthorSelector: true, - yAxisLabel: 'Publikationen von Autoren', - chartTitle: 'Autorentrends', - }, - patents: { - showInstitutionSelector: false, - showLocationSelector: false, - showAuthorSelector: false, - yAxisLabel: 'Patentanmeldungen', - chartTitle: 'Patentrecherche-Trends', - }, - projects: { - showInstitutionSelector: true, - showLocationSelector: true, - showAuthorSelector: false, - yAxisLabel: 'Projektförderung (Anz)', - chartTitle: 'Drittmittelförderung-Trends', - }, - news: { - showInstitutionSelector: false, - showLocationSelector: false, - showAuthorSelector: false, - yAxisLabel: 'Pressemitteilungen', - chartTitle: 'Nachrichtentrends', - }, - all: { - showInstitutionSelector: false, - showLocationSelector: false, - showAuthorSelector: false, - yAxisLabel: 'Aktivitäts-Index', - chartTitle: 'Cross-Domain-Themenlebenszyklus (UDE)', - }, -}; +import { CompareItem, TREND_CONFIGS } from '../models/trend.models'; +import { + cleanEntityId, + isTopicEmptyForSeries, + findFirstNonEmptyTopic, + buildEntityColorIndex, +} from '../utils/trend.utils'; +import { TrendDataService } from '../services/trend-data.service'; @Component({ selector: 'app-uni-trend-parent', - standalone: true, imports: [ CommonModule, FormsModule, @@ -156,6 +105,7 @@ export class UniTrendParentComponent implements OnInit { private readonly topicsService = inject(TopicsService); private readonly institutionsApiService = inject(InstitutionsService); private readonly personsApiService = inject(PersonsService); + private readonly trendDataService = inject(TrendDataService); private readonly organizationService = inject(OrganizationService, { optional: true, }); @@ -164,18 +114,13 @@ export class UniTrendParentComponent implements OnInit { }); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); - - // Inject SearchResultsStateService optionally if loaded in keywords search private readonly state = inject(SearchResultsStateService, { optional: true, }); readonly topTopicsSize = signal(20); - - // Input containing extracted/selected keywords from parent readonly keywordsInput = input([], { alias: 'keywords' }); - // Read keywords dynamically from SearchResultsStateService if available, otherwise from input. readonly keywords = computed(() => { const fromState = this.state?.keywords(); if (fromState && fromState.length > 0) { @@ -196,8 +141,9 @@ export class UniTrendParentComponent implements OnInit { readonly isUde = computed(() => { const p = this.primaryInstitution() || 'I62318514'; - return p.includes('I62318514') || p === 'I62318514'; + return p.includes('I62318514') || p.toUpperCase() === 'I62318514'; }); + readonly comparisonInstitutions = signal([]); readonly comparisonCountries = signal([ { id: 'DE', name: 'Deutschland' }, @@ -218,30 +164,26 @@ export class UniTrendParentComponent implements OnInit { type: 'institution' | 'author' | 'country' | 'region'; } | null>(null); - // Config mapper for active strategy UI representation readonly activeConfig = computed( () => TREND_CONFIGS[this.selectedSearchType()], ); - // Cached parameters of the last active search request to track "isDirty" - readonly fetchedSearchType = signal(null); - readonly fetchedTopics = signal([]); - readonly fetchedInstitutions = signal([]); - readonly fetchedCountries = signal([]); - readonly fetchedRegions = signal([]); - readonly fetchedAuthors = signal([]); - readonly fetchedFuzzy = signal(null); + readonly mappedActiveChartTopic = computed(() => { + return this.getMappedTopic(this.activeChartTopic()); + }); // Results & Loading signals readonly isPageResolving = signal(false); readonly rawTrendResponse = signal(null); readonly isTrendLoading = signal(false); - readonly topSuggestions = signal([]); - readonly recommendedAuthors = signal([]); - readonly isSuggestionsLoading = signal(false); - readonly topTopicsData = signal<{ value: number; name: string }[]>([]); - readonly isTopTopicsLoading = signal(false); - readonly topTopicsError = signal(false); + + // Delegate secondary signals to service + readonly topSuggestions = this.trendDataService.topSuggestions; + readonly recommendedAuthors = this.trendDataService.recommendedAuthors; + readonly isSuggestionsLoading = this.trendDataService.isSuggestionsLoading; + readonly topTopicsData = this.trendDataService.topTopicsData; + readonly isTopTopicsLoading = this.trendDataService.isTopTopicsLoading; + readonly topTopicsError = this.trendDataService.topTopicsError; // Topic Treemap signals readonly isFuzzy = computed(() => this.state?.fuzzySearch() ?? true); @@ -249,15 +191,71 @@ export class UniTrendParentComponent implements OnInit { readonly isTreemapLoading = signal(false); readonly selectedTopicTreemapNode = signal(undefined); + // Autocomplete UI state + readonly searchQuery = signal(''); + readonly searchResults = signal([]); + readonly locationQuery = signal(''); + readonly locationSearchResults = signal([]); + readonly authorSearchQuery = signal(''); + readonly authorSearchResults = signal([]); + readonly authorInstSearchQuery = signal(''); + readonly authorInstSearchResults = signal( + [], + ); + + readonly availableYears: number[] = []; + readonly entityVisibilityMap = signal>(new Map()); + + cleanEntityId(id: string | null | undefined): string { + return cleanEntityId(id); + } + getMappedTopic(topicOrKeyword: string): string { + if (!topicOrKeyword) return ''; + + const cleanId = cleanEntityId(topicOrKeyword); + const isTopicId = + topicOrKeyword.includes('openalex.org') || + /^T\d+$/i.test(topicOrKeyword) || + (cleanId.startsWith('T') && /^T\d+$/i.test(cleanId)); + + if (isTopicId) { + const matchTopic = this.state + ?.topics() + ?.find((t) => cleanEntityId(t.id) === cleanId); + if (matchTopic?.display_name) return matchTopic.display_name; + + const matchEntry = this.state + ?.selectedKeywordEntries() + ?.find((e) => cleanEntityId(e.topic_mapping?.topic?.id) === cleanId); + if (matchEntry?.topic_mapping?.topic?.display_name) { + return matchEntry.topic_mapping.topic.display_name; + } + } + const kws = this.keywords(); const topics = this.state?.topicsList() ?? kws; const idx = kws.findIndex( - (k) => k.toLowerCase() === topicOrKeyword.toLowerCase(), + (k) => + k.toLowerCase().trim() === topicOrKeyword.toLowerCase().trim() || + (cleanId.startsWith('T') && cleanEntityId(k) === cleanId), ); if (idx !== -1 && topics[idx]) { return topics[idx]; } + + const topicObj = this.state + ?.topics() + ?.find( + (t) => + t.display_name?.toLowerCase().trim() === + topicOrKeyword.toLowerCase().trim() || + (cleanId.startsWith('T') && cleanEntityId(t.id) === cleanId), + ); + if (topicObj?.display_name) { + return topicObj.display_name; + } + return topicOrKeyword; } @@ -343,13 +341,6 @@ export class UniTrendParentComponent implements OnInit { }); }); - cleanEntityId(id: string | null | undefined): string { - if (!id) return ''; - const lower = id.toLowerCase().trim(); - return lower.includes('/') ? lower.split('/').pop()! : lower; - } - - // Dynamic Treemap Data for Selected Entity (Institution or Author or Region/Country) readonly activeTreemapData = computed(() => { const data = this.trendResponse(); const searchType = this.selectedSearchType(); @@ -374,16 +365,14 @@ export class UniTrendParentComponent implements OnInit { } } - const cleanTargetId = targetEntityId - ? this.cleanEntityId(targetEntityId) - : ''; + const cleanTargetId = targetEntityId ? cleanEntityId(targetEntityId) : ''; let matchingSeries: TrendSeries[] = []; if (searchType === 'news') { matchingSeries = data.series; } else { matchingSeries = data.series.filter( - (s) => this.cleanEntityId(s.entity_id) === cleanTargetId, + (s) => cleanEntityId(s.entity_id) === cleanTargetId, ); if (matchingSeries.length === 0 && data.series.length > 0) { matchingSeries = data.series; @@ -534,65 +523,54 @@ export class UniTrendParentComponent implements OnInit { }; }); - // Autocomplete UI state - readonly searchQuery = signal(''); - readonly searchResults = signal([]); - readonly locationQuery = signal(''); - readonly locationSearchResults = signal([]); - readonly authorSearchQuery = signal(''); - readonly authorSearchResults = signal([]); - readonly authorInstSearchQuery = signal(''); - readonly authorInstSearchResults = signal( - [], - ); - - // Years array for selects - readonly availableYears: number[] = []; - - readonly entityVisibilityMap = signal>(new Map()); - isTopicEmpty(topic: string): boolean { - const res = this.rawTrendResponse(); - if (!res || !res.series || res.series.length === 0) return false; + const series = this.rawTrendResponse()?.series || []; + if (!series || series.length === 0) return true; + + const mapped = this.getMappedTopic(topic); const startYr = this.startYear(); const endYr = this.endYear(); - const topicLower = topic.toLowerCase().trim(); - const mappedLower = this.getMappedTopic(topic).toLowerCase().trim(); + const cId = cleanEntityId(topic); - return !res.series.some((s) => { - 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); - return total > 0; - }); + for (const s of series) { + if (!s.topic_data) continue; + const keys = [ + topic, + mapped, + cId ? `https://openalex.org/${cId}` : '', + cId, + ].filter(Boolean); + + for (const k of keys) { + const topicItems = s.topic_data[k]; + if (topicItems && topicItems.length > 0) { + const sumRaw = topicItems + .filter((y) => y.year >= startYr && y.year <= endYr) + .reduce((acc, curr) => acc + (curr.raw || 0), 0); + if (sumRaw > 0) return false; + } + } + } + return true; } 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] || ''; + for (const t of topics) { + if (!this.isTopicEmpty(t)) { + return t; + } + } + return topics[0]; } isVisible(id: string): boolean { - const clean = this.cleanEntityId(id); + const clean = cleanEntityId(id); return this.entityVisibilityMap().get(clean) !== false; } toggleVisibility(id: string): void { - const clean = this.cleanEntityId(id); + const clean = cleanEntityId(id); this.entityVisibilityMap.update((map) => { const newMap = new Map(map); const current = newMap.get(clean) !== false; @@ -608,75 +586,14 @@ export class UniTrendParentComponent implements OnInit { : entityId; return this.getTopicColor(topicName); } - - if (this.selectedSearchType() === 'all') { - const cleanTarget = this.cleanEntityId(entityId).toLowerCase(); - const allColors: Record = { - publications: '#3b82f6', - works: '#3b82f6', - patents: '#10b981', - projects: '#f59e0b', - news: '#ec4899', - }; - if (allColors[cleanTarget]) { - return allColors[cleanTarget]; - } - const seriesList = this.rawTrendResponse()?.series || []; - const seriesIdx = seriesList.findIndex( - (s) => this.cleanEntityId(s.entity_id).toLowerCase() === cleanTarget, - ); - const fixedColors = ['#3b82f6', '#10b981', '#f59e0b', '#ec4899']; - if (seriesIdx !== -1) { - return fixedColors[seriesIdx % fixedColors.length]; - } - return '#3b82f6'; - } - - const cleanId = (id: string | null | undefined): string => { - if (!id) return ''; - const lower = id.toLowerCase().trim(); - return lower.includes('/') ? lower.split('/').pop()! : lower; - }; - - const defaultInstId = 'https://openalex.org/I62318514'; - const primaryId = cleanId(this.primaryInstitution() || defaultInstId); - const insts = this.comparisonInstitutions().map((i) => cleanId(i.id)); - const countries = this.comparisonCountries().map((c) => cleanId(c.id)); - const regions = this.comparisonRegions().map((r) => cleanId(r.id)); - const authors = this.comparisonAuthors().map((a) => cleanId(a.id)); - - const orderedIds = [ - primaryId, - ...insts, - ...countries, - ...regions, - ...authors, - ]; - - const targetCleanId = cleanId(entityId); - const idx = orderedIds.indexOf(targetCleanId); - if (idx === -1) return '#9ca3af'; - - const entityColors = [ - '#3b82f6', - '#10b981', - '#f59e0b', - '#ec4899', - '#8b5cf6', - '#06b6d4', - '#6366f1', - '#ef4444', - '#14b8a6', - '#f97316', - '#d946ef', - '#84cc16', - '#22c55e', - '#a855f7', - '#eab308', - '#f43f5e', - ]; - - return entityColors[idx % entityColors.length]; + const colorFn = buildEntityColorIndex( + this.primaryInstitution(), + this.comparisonInstitutions(), + this.comparisonCountries(), + this.comparisonRegions(), + this.comparisonAuthors(), + ); + return colorFn(entityId); } onSelectPieEntity(event: { @@ -690,21 +607,13 @@ export class UniTrendParentComponent implements OnInit { readonly boundGetEntityColor = (id: string) => this.getEntityColor(id); readonly boundIsVisible = (id: string) => this.isVisible(id); - // Computed: filters out items locally if they were removed from list and normalizes topic_data keys & entity names readonly trendResponse = computed(() => { const raw = this.rawTrendResponse(); if (!raw || !raw.series) return null; const topics = this.selectedTrendTopics(); const type = this.selectedSearchType(); - - const cleanId = (id: string | null | undefined): string => { - if (!id) return ''; - const lower = id.toLowerCase().trim(); - return lower.includes('/') ? lower.split('/').pop()! : lower; - }; - - const primaryInstCleanId = cleanId( + const primaryInstCleanId = cleanEntityId( this.primaryInstitution() || 'I62318514', ); @@ -728,7 +637,7 @@ export class UniTrendParentComponent implements OnInit { } } - const cId = cleanId(s.entity_id); + const cId = cleanEntityId(s.entity_id); if (s.entity_type === 'institution') { if (cId === primaryInstCleanId) { @@ -739,14 +648,14 @@ export class UniTrendParentComponent implements OnInit { ); } const foundInst = this.comparisonInstitutions().find( - (i) => cleanId(i.id) === cId, + (i) => cleanEntityId(i.id) === cId, ); if (foundInst && foundInst.name && foundInst.name !== foundInst.id) { return foundInst.name; } } else if (s.entity_type === 'country') { const foundCountry = this.comparisonCountries().find( - (c) => cleanId(c.id) === cId, + (c) => cleanEntityId(c.id) === cId, ); if ( foundCountry && @@ -757,7 +666,7 @@ export class UniTrendParentComponent implements OnInit { } } else if (s.entity_type === 'region') { const foundRegion = this.comparisonRegions().find( - (r) => cleanId(r.id) === cId, + (r) => cleanEntityId(r.id) === cId, ); if ( foundRegion && @@ -768,7 +677,7 @@ export class UniTrendParentComponent implements OnInit { } } else if (s.entity_type === 'author') { const foundAuthor = this.comparisonAuthors().find( - (a) => cleanId(a.id) === cId, + (a) => cleanEntityId(a.id) === cId, ); if ( foundAuthor && @@ -786,55 +695,19 @@ export class UniTrendParentComponent implements OnInit { : s.entity_name || cId; }; - // Map series topic_data keys to display names so they match selectedTrendTopics const normalizeTopicData = (s: TrendSeries): TrendSeries => { const nameResolved = resolveEntityName(s); if (!s.topic_data) return { ...s, entity_name: nameResolved }; - const rawTopicKeys = Object.keys(s.topic_data); - if (rawTopicKeys.length === 0) return { ...s, entity_name: nameResolved }; const newTopicData: Record = {}; - - topics.forEach((topicName, idx) => { - const mappedName = this.getMappedTopic(topicName); - const topicLower = topicName.toLowerCase().trim(); - const mappedLower = mappedName.toLowerCase().trim(); - - let matchKey = rawTopicKeys.find((rk) => { - const rkLower = rk.toLowerCase().trim(); - const rkClean = rkLower.includes('/') - ? rkLower.split('/').pop()! - : rkLower.startsWith('news_topic_') - ? rkLower.slice('news_topic_'.length) - : rkLower; - - return ( - rkLower === topicLower || - rkLower === mappedLower || - rkClean === topicLower || - rkClean === mappedLower || - rkLower.includes(topicLower) || - rkLower.includes(mappedLower) - ); - }); - - if (!matchKey && rawTopicKeys[idx]) { - matchKey = rawTopicKeys[idx]; - } - - if (matchKey && s.topic_data[matchKey]) { - newTopicData[topicName] = s.topic_data[matchKey]; - } else if (rawTopicKeys[0] && s.topic_data[rawTopicKeys[0]]) { - newTopicData[topicName] = s.topic_data[rawTopicKeys[0]]; - } - }); - - // Preserve extra keys only if they are not raw URIs Object.entries(s.topic_data).forEach(([rk, val]) => { + const mappedName = this.getMappedTopic(rk); + const canonicalKey = + mappedName && !mappedName.startsWith('http') ? mappedName : rk; + newTopicData[canonicalKey] = val; if ( - !rk.startsWith('http://') && - !rk.startsWith('https://') && - !newTopicData[rk] + rk !== canonicalKey && + (rk.startsWith('http') || /^T\d+$/i.test(rk)) ) { newTopicData[rk] = val; } @@ -859,10 +732,10 @@ export class UniTrendParentComponent implements OnInit { if (type === 'authors') { const currentAuthorIds = new Set( - this.comparisonAuthors().map((a) => a.id.toLowerCase()), + this.comparisonAuthors().map((a) => cleanEntityId(a.id)), ); const filtered = raw.series - .filter((s) => currentAuthorIds.has(s.entity_id.toLowerCase())) + .filter((s) => currentAuthorIds.has(cleanEntityId(s.entity_id))) .map((s) => ({ ...normalizeTopicData(s), visible: this.isVisible(s.entity_id), @@ -873,15 +746,16 @@ export class UniTrendParentComponent implements OnInit { }; } - // Default: publications, patents, projects const currentInstIds = new Set( - this.comparisonInstitutions().map((i: CompareItem) => cleanId(i.id)), + this.comparisonInstitutions().map((i: CompareItem) => + cleanEntityId(i.id), + ), ); const currentCountryIds = new Set( - this.comparisonCountries().map((c: CompareItem) => cleanId(c.id)), + this.comparisonCountries().map((c: CompareItem) => cleanEntityId(c.id)), ); const currentRegionIds = new Set( - this.comparisonRegions().map((r: CompareItem) => cleanId(r.id)), + this.comparisonRegions().map((r: CompareItem) => cleanEntityId(r.id)), ); const primaryInstSeries: TrendSeries[] = []; @@ -890,7 +764,7 @@ export class UniTrendParentComponent implements OnInit { const regionSeries: TrendSeries[] = []; raw.series.forEach((s: TrendSeries) => { - const cId = cleanId(s.entity_id); + const cId = cleanEntityId(s.entity_id); if (s.entity_type === 'institution') { if (cId === primaryInstCleanId) { primaryInstSeries.push(s); @@ -925,7 +799,6 @@ export class UniTrendParentComponent implements OnInit { }); constructor() { - // Generate year range from 2000 to current year const currentYear = new Date().getFullYear(); for (let y = 2000; y <= currentYear; y++) { this.availableYears.push(y); @@ -939,7 +812,6 @@ export class UniTrendParentComponent implements OnInit { } }); - // Subscribe to route resolver data this.route.data.pipe(takeUntilDestroyed()).subscribe((data) => { if (data['trendData']) { const resolved = data['trendData']; @@ -948,61 +820,27 @@ export class UniTrendParentComponent implements OnInit { const type = resolved.searchType || this.selectedSearchType(); this.selectedSearchType.set(type); - this.fetchedSearchType.set(type); - - const fuzzy = this.state?.fuzzySearch() ?? true; - this.fetchedFuzzy.set(fuzzy); if (resolved.topics && resolved.topics.length > 0) { this.selectedTrendTopics.set(resolved.topics); - this.fetchedTopics.set([...resolved.topics]); 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()]); } if (resolved.institutions && resolved.institutions.length > 0) { this.comparisonInstitutions.set(resolved.institutions); - this.fetchedInstitutions.set([...resolved.institutions]); - } else { - this.fetchedInstitutions.set([...this.comparisonInstitutions()]); } - if (resolved.countries && resolved.countries.length > 0) { this.comparisonCountries.set(resolved.countries); - this.fetchedCountries.set([...resolved.countries]); - } else { - this.fetchedCountries.set([...this.comparisonCountries()]); } - if (resolved.regions && resolved.regions.length > 0) { this.comparisonRegions.set(resolved.regions); - this.fetchedRegions.set([...resolved.regions]); - } else { - this.fetchedRegions.set([...this.comparisonRegions()]); } - if (resolved.authors && resolved.authors.length > 0) { this.comparisonAuthors.set(resolved.authors); - this.fetchedAuthors.set([...resolved.authors]); - } else { - 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); } if (resolved.treemapNode !== undefined) { @@ -1013,14 +851,13 @@ export class UniTrendParentComponent implements OnInit { } }); - // Effect: automatically sync checkboxes list whenever input keywords or fuzzy state changes + // Sync active topics list whenever keywords or fuzzy mode state changes effect(() => { const kws = this.keywords(); - const fuzzy = this.state?.fuzzySearch() ?? true; + const fuzzy = this.isFuzzy(); const topics = fuzzy ? (this.state?.topicsList() ?? kws) : kws; const currentSelections = untracked(() => this.selectedTrendTopics()); const currentActive = untracked(() => this.activeChartTopic()); - const searchType = this.selectedSearchType(); if (topics.length > 0) { const altTopics = fuzzy ? kws : (this.state?.topicsList() ?? kws); @@ -1044,7 +881,6 @@ export class UniTrendParentComponent implements OnInit { this.selectedTrendTopics.set(topics); } - // Initialize active chart topic to a valid non-empty topic const active = currentActive; const updatedSelections = untracked(() => this.selectedTrendTopics()); const mappedActive = this.getMappedTopic(active); @@ -1059,260 +895,24 @@ export class UniTrendParentComponent implements OnInit { this.findFirstNonEmptyTopic(updatedSelections), ); } - - // If comparison list is empty, initialize default institutions/authors dynamically (unless explicitly cleared by user) - if (searchType === 'authors') { - const currentAuthors = untracked(() => this.comparisonAuthors()); - if ( - currentAuthors.length === 0 && - !untracked(() => this.hasUserClearedAuthors()) - ) { - untracked(() => this.initializeDefaultAuthors()); - } - } else { - const currentInsts = untracked(() => this.comparisonInstitutions()); - if ( - currentInsts.length === 0 && - !untracked(() => this.hasUserClearedInstitutions()) - ) { - untracked(() => this.initializeDefaultInstitutions()); - } - } } else { this.selectedTrendTopics.set([]); } }); - // Effect: load suggestions when topic or location filters change + // Effect: load suggestions when active topic or location filters change effect(() => { const topic = this.activeChartTopic(); const countries = this.comparisonCountries(); const regions = this.comparisonRegions(); + const searchType = this.selectedSearchType(); untracked(() => { this.loadTrendSuggestions(); }); }); - // Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with cached rawTrendResponse check) - effect(() => { - const topics = this.selectedTrendTopics(); - const insts = this.comparisonInstitutions(); - const countries = this.comparisonCountries(); - const regions = this.comparisonRegions(); - const authors = this.comparisonAuthors(); - const searchType = this.selectedSearchType(); - const fuzzy = this.state?.fuzzySearch() ?? true; - - if (topics.length === 0) return; - - const fetchedT = new Set(untracked(() => this.fetchedTopics())); - const fetchedType = untracked(() => this.fetchedSearchType()); - const fetchedF = untracked(() => this.fetchedFuzzy()); - const rawRes = untracked(() => this.rawTrendResponse()); - - const allTopicsFetched = topics.every((t) => fetchedT.has(t)); - const sameType = searchType === fetchedType; - const sameFuzzy = fuzzy === fetchedF; - - let allEntitiesFetched = false; - if (sameType && rawRes && rawRes.series) { - const rawSeriesCleanIds = new Set( - rawRes.series.map((s) => { - const id = s.entity_id; - return id.includes('/') - ? id.split('/').pop()!.toLowerCase() - : id.toLowerCase(); - }), - ); - - if (searchType === 'authors') { - allEntitiesFetched = - authors.length === 0 || - authors.every((a) => { - const cleanA = a.id.includes('/') - ? a.id.split('/').pop()!.toLowerCase() - : a.id.toLowerCase(); - return rawSeriesCleanIds.has(cleanA); - }); - } else if ( - searchType === 'news' || - searchType === 'all' || - searchType === 'patents' - ) { - allEntitiesFetched = true; - } else { - // publications, patents, projects - allEntitiesFetched = - (insts.length === 0 || - insts.every((i) => { - const cleanI = i.id.includes('/') - ? i.id.split('/').pop()!.toLowerCase() - : i.id.toLowerCase(); - return rawSeriesCleanIds.has(cleanI); - })) && - (countries.length === 0 || - countries.every((c) => - rawSeriesCleanIds.has(c.id.toLowerCase()), - )) && - (regions.length === 0 || - regions.every((r) => rawSeriesCleanIds.has(r.id.toLowerCase()))); - } - } - - if ( - allTopicsFetched && - sameType && - sameFuzzy && - allEntitiesFetched && - !!rawRes - ) { - // All requested data is already present in rawTrendResponse, so skip backend call! - return; - } - - untracked(() => this.fetchTrendData()); - }); - - // Handle initialization and synchronization of URL state - this.route.queryParams.pipe(takeUntilDestroyed()).subscribe((params) => { - let hasInstsFromUrl = false; - if (params['search_type']) { - this.selectedSearchType.set(params['search_type'] as any); - } - - // Parse institutions serialized as id|name - if (params['institutions']) { - hasInstsFromUrl = true; - const insts = Array.isArray(params['institutions']) - ? params['institutions'] - : [params['institutions']]; - const parsed = insts.map((i: string) => { - const parts = i.split('|'); - const cleanId = parts[0].includes('/') - ? parts[0].split('/').pop() || parts[0] - : parts[0]; - return { id: cleanId, name: parts[1] || parts[0] }; - }); - - const currentIds = this.comparisonInstitutions() - .map((i) => i.id) - .sort() - .join(','); - const parsedIds = parsed - .map((i) => i.id) - .sort() - .join(','); - if (currentIds !== parsedIds) { - this.comparisonInstitutions.set(parsed); - } - } - - // If URL didn't specify institutions and list is currently empty, initialize defaults (unless user explicitly cleared them) - if ( - !hasInstsFromUrl && - this.comparisonInstitutions().length === 0 && - !this.hasUserClearedInstitutions() - ) { - this.initializeDefaultInstitutions(); - } - - // Parse countries - if (params['countries']) { - const ccs = Array.isArray(params['countries']) - ? params['countries'] - : [params['countries']]; - const parsed = ccs.map((c: string) => { - const parts = c.split('|'); - return { id: parts[0], name: parts[1] || parts[0] }; - }); - - const currentIds = this.comparisonCountries() - .map((c) => c.id) - .sort() - .join(','); - const parsedIds = parsed - .map((c) => c.id) - .sort() - .join(','); - if (currentIds !== parsedIds) { - this.comparisonCountries.set(parsed); - } - } else { - if (this.comparisonCountries().length > 0) { - this.comparisonCountries.set([]); - } - } - - // Parse regions - if (params['regions']) { - const regs = Array.isArray(params['regions']) - ? params['regions'] - : [params['regions']]; - const parsed = regs.map((r: string) => { - const parts = r.split('|'); - return { id: parts[0], name: parts[1] || parts[0] }; - }); - - const currentIds = this.comparisonRegions() - .map((r) => r.id) - .sort() - .join(','); - const parsedIds = parsed - .map((r) => r.id) - .sort() - .join(','); - if (currentIds !== parsedIds) { - this.comparisonRegions.set(parsed); - } - } else { - if (this.comparisonRegions().length > 0) { - this.comparisonRegions.set([]); - } - } - - // Parse authors - if (params['authors']) { - const auths = Array.isArray(params['authors']) - ? params['authors'] - : [params['authors']]; - const parsed = auths.map((a: string) => { - const parts = a.split('|'); - return { id: parts[0], name: parts[1] || parts[0] }; - }); - - const currentIds = this.comparisonAuthors() - .map((a) => a.id) - .sort() - .join(','); - const parsedIds = parsed - .map((a) => a.id) - .sort() - .join(','); - if (currentIds !== parsedIds) { - this.comparisonAuthors.set(parsed); - } - } else { - if (this.comparisonAuthors().length > 0) { - this.comparisonAuthors.set([]); - } - } - - if (params['start_year']) { - this.startYear.set(Number(params['start_year'])); - } - if (params['end_year']) { - this.endYear.set(Number(params['end_year'])); - } - if (params['chart_mode']) { - this.chartMode.set(params['chart_mode'] as any); - } - if (params['active_chart_topic']) { - this.activeChartTopic.set(params['active_chart_topic']); - } - }); - - // Effect: automatically select/sync selectedPieEntity with active trendResponse series list + // Sync selectedPieEntity when trendResponse series update effect(() => { const data = this.trendResponse(); const currentPie = untracked(() => this.selectedPieEntity()); @@ -1324,14 +924,9 @@ export class UniTrendParentComponent implements OnInit { if (currentPie) { const stillExists = data.series.some((s) => { - const sId = s.entity_id; - const targetId = currentPie.id; - return ( - sId === targetId || - sId.toUpperCase() === targetId.toUpperCase() || - sId.split('/').pop()?.toUpperCase() === targetId.toUpperCase() || - targetId.split('/').pop()?.toUpperCase() === sId.toUpperCase() - ); + const sId = cleanEntityId(s.entity_id); + const targetId = cleanEntityId(currentPie.id); + return sId === targetId; }); if (stillExists) { return; @@ -1341,7 +936,7 @@ export class UniTrendParentComponent implements OnInit { const firstSeries = data.series[0]; if (firstSeries) { this.selectedPieEntity.set({ - id: firstSeries.entity_id, + id: cleanEntityId(firstSeries.entity_id), name: firstSeries.entity_name, type: firstSeries.entity_type as any, }); @@ -1350,7 +945,7 @@ export class UniTrendParentComponent implements OnInit { } }); - // Effect: load top 10 overall topics for selected pie entity + // Load top 10 topics for selected pie entity effect(() => { const entity = this.selectedPieEntity(); const start = this.startYear(); @@ -1358,37 +953,18 @@ export class UniTrendParentComponent implements OnInit { const strategy = this.selectedSearchType(); if (!entity || strategy === 'all') { - this.topTopicsData.set([]); return; } - this.isTopTopicsLoading.set(true); - this.topTopicsError.set(false); - - this.apiService - .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + untracked(() => { + this.trendDataService.loadTopTopicsForEntity( entity.id, entity.type, start, end, strategy, - ) - .subscribe({ - next: (res) => { - const mapped = (res.items || []).map((item) => ({ - value: item.count, - name: item.name, - })); - this.topTopicsData.set(mapped); - this.isTopTopicsLoading.set(false); - }, - error: (err) => { - console.error('Failed to load top topics:', err); - this.topTopicsError.set(true); - this.isTopTopicsLoading.set(false); - this.topTopicsData.set([]); - }, - }); + ); + }); }); } @@ -1407,7 +983,7 @@ export class UniTrendParentComponent implements OnInit { matchingOrg?.other_inst_id || (matchingOrg as any)?.openalex_institution_id; if (matchingOrg && openAlexId) { - this.primaryInstitution.set(openAlexId); + this.primaryInstitution.set(cleanEntityId(openAlexId)); if (matchingOrg.name) { this.primaryInstitutionName.set(matchingOrg.name); } @@ -1417,291 +993,36 @@ export class UniTrendParentComponent implements OnInit { }); } } - this.initializeDefaultInstitutions(); } - // Dynamically load top institutions to initialize comparisons using the top-institutions service - initializeDefaultInstitutions() { - const primaryId = this.primaryInstitution() || 'I62318514'; - const primaryName = - this.primaryInstitutionName() || 'Universität Duisburg-Essen'; - - const kws = this.keywords(); - if (kws.length === 0) { - this.comparisonInstitutions.set([{ id: primaryId, name: primaryName }]); - return; - } - - // Use mapped topic names if softSearch is false - const topics = this.state?.topicsList() ?? kws; - const topic = topics[0] || kws[0] || 'Artificial Intelligence'; - - forkJoin({ - deInsts: - this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - topic, - undefined, - 'DE', - 2, - ), - overallInsts: - this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - topic, - undefined, - undefined, - 2, - ), - }).subscribe({ - next: ({ - deInsts, - overallInsts, - }: { - deInsts: Array; - overallInsts: Array; - }) => { - const uniqueInsts = new Map(); - uniqueInsts.set(primaryId, primaryName); - - deInsts.forEach((inst: TopInstitutionItem) => { - if (inst.id) - uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); - }); - - overallInsts.forEach((inst: TopInstitutionItem) => { - if (inst.id) - uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); - }); - - const list = Array.from(uniqueInsts.entries()).map(([id, name]) => ({ - id, - name, - })); - this.comparisonInstitutions.set(list); - - if (!this.rawTrendResponse()) { - this.fetchTrendData(); - } - }, - error: (err: any) => { - console.error('Failed to load default institutions dynamically:', err); - }, - }); - } - - // Dynamically load top authors for UDE to initialize comparison list - initializeDefaultAuthors() { - const kws = this.keywords(); - if (kws.length === 0) return; - - const topics = this.state?.topicsList() ?? kws; - const topic = - this.findFirstNonEmptyTopic(topics) || - topics[0] || - kws[0] || - 'Artificial Intelligence'; - - this.personsApiService - .searchPersonsList( - undefined, // query - this.primaryInstitution() || 'I62318514', // primary institution ID - 'cited_by_count', // sortBy - 'desc', // sortOrder - [topic], // topic - 1, // page - 3, // pageSize - undefined, // include (fetch all fields!) - ) - .subscribe({ - next: (res) => { - const list = (res.results || []).map((author: any) => ({ - id: author.id, - name: author.display_name || 'Unbekannt', - })); - this.comparisonAuthors.set(list); - - if (!this.rawTrendResponse()) { - this.fetchTrendData(); - } - }, - error: (err) => { - console.error('Failed to load default authors:', err); - }, - }); - } - - // Fetch recommended institutions or authors for comparison based on current topics loadTrendSuggestions() { + const rawTopic = + this.activeChartTopic() || + (this.selectedTrendTopics().length > 0 + ? this.selectedTrendTopics()[0] + : 'Artificial Intelligence'); + const topic = this.getMappedTopic(rawTopic); + if (this.selectedSearchType() === 'authors') { - this.loadRecommendedAuthors(); - return; - } - - this.isSuggestionsLoading.set(true); - const kws = this.keywords(); - const topics = this.state?.topicsList() ?? kws; - const rawTopic = - this.activeChartTopic() || - (this.selectedTrendTopics().length > 0 - ? this.selectedTrendTopics()[0] - : topics.length > 0 - ? topics[0] - : 'Artificial Intelligence'); - const topic = this.getMappedTopic(rawTopic); - - const countryFilter = - this.comparisonCountries().length > 0 - ? this.comparisonCountries()[0].id - : undefined; - const regionFilter = - this.comparisonRegions().length > 0 - ? this.comparisonRegions()[0].id - : undefined; - - this.apiService - .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + const pInst = this.primaryInstitution() || 'I62318514'; + this.trendDataService.loadRecommendedAuthors(topic, pInst); + } else { + const countryFilter = + this.comparisonCountries().length > 0 + ? this.comparisonCountries()[0].id + : undefined; + const regionFilter = + this.comparisonRegions().length > 0 + ? this.comparisonRegions()[0].id + : undefined; + this.trendDataService.loadInstitutionSuggestions( topic, - regionFilter, countryFilter, - 6, - ) - .subscribe({ - next: (res: any) => { - this.topSuggestions.set(res || []); - this.isSuggestionsLoading.set(false); - }, - error: () => { - this.isSuggestionsLoading.set(false); - }, - }); + regionFilter, + ); + } } - // Load UDE recommended authors for selected topic - loadRecommendedAuthors() { - this.isSuggestionsLoading.set(true); - const kws = this.keywords(); - const topics = this.state?.topicsList() ?? kws; - const rawTopic = - this.activeChartTopic() || - (this.selectedTrendTopics().length > 0 - ? this.selectedTrendTopics()[0] - : topics.length > 0 - ? topics[0] - : 'Artificial Intelligence'); - const topic = this.getMappedTopic(rawTopic); - - this.personsApiService - .searchPersonsList( - undefined, // query - this.primaryInstitution() || 'I62318514', // UDE institution ID - 'cited_by_count', // sortBy - 'desc', // sortOrder - [topic], // topic - 1, // page - 6, // pageSize - undefined, // include (fetch all fields!) - ) - .subscribe({ - next: (res) => { - if (res.results && res.results.length > 0) { - this.recommendedAuthors.set(res.results); - this.isSuggestionsLoading.set(false); - } else { - // Fallback: search globally across all institutions - this.personsApiService - .searchPersonsList( - undefined, - undefined, // global! - 'cited_by_count', - 'desc', - [topic], - 1, - 6, - undefined, - ) - .subscribe({ - next: (globalRes) => { - this.recommendedAuthors.set(globalRes.results || []); - this.isSuggestionsLoading.set(false); - }, - error: () => { - this.recommendedAuthors.set([]); - this.isSuggestionsLoading.set(false); - }, - }); - } - }, - error: () => { - this.isSuggestionsLoading.set(false); - }, - }); - } - - // Trigger search trend data - fetchTrendData() { - const topics = this.selectedTrendTopics(); - if (topics.length === 0) return; - - this.isTrendLoading.set(true); - - this.fetchedSearchType.set(this.selectedSearchType()); - this.fetchedTopics.set([...topics]); - this.fetchedInstitutions.set([...this.comparisonInstitutions()]); - this.fetchedCountries.set([...this.comparisonCountries()]); - this.fetchedRegions.set([...this.comparisonRegions()]); - this.fetchedAuthors.set([...this.comparisonAuthors()]); - const fuzzy = this.state?.fuzzySearch() ?? true; - this.fetchedFuzzy.set(fuzzy); - - const kws = this.state?.keywordsList() ?? []; - - this.apiService - .getTrendApiInseServiceUniversityRankingsTrendGet( - topics, - kws, - fuzzy, - this.comparisonInstitutions().map((i: CompareItem) => i.id), - this.comparisonCountries().map((c: CompareItem) => c.id), - this.comparisonRegions().map((r: CompareItem) => r.id), - this.comparisonAuthors().map((a: CompareItem) => a.id), - this.selectedSearchType(), - ) - .subscribe({ - next: (response: TrendResponse) => { - const currentRaw = untracked(() => this.rawTrendResponse()); - if (!currentRaw || !currentRaw.series) { - this.rawTrendResponse.set(response); - } else { - const seriesMap = new Map(); - currentRaw.series.forEach((s) => { - seriesMap.set(`${s.entity_type}_${s.entity_id}`, s); - }); - response.series.forEach((s) => { - const key = `${s.entity_type}_${s.entity_id}`; - const prev = seriesMap.get(key); - if (prev && prev.topic_data && s.topic_data) { - seriesMap.set(key, { - ...prev, - ...s, - topic_data: { ...prev.topic_data, ...s.topic_data }, - }); - } else { - seriesMap.set(key, s); - } - }); - this.rawTrendResponse.set({ - ...response, - series: Array.from(seriesMap.values()), - }); - } - this.isTrendLoading.set(false); - }, - error: () => { - this.isTrendLoading.set(false); - }, - }); - } - - // Update query params to synchronize state updateUrlParams() { const queryParams: any = { search_type: this.selectedSearchType(), @@ -1709,7 +1030,7 @@ export class UniTrendParentComponent implements OnInit { institutions: this.comparisonInstitutions().length > 0 ? this.comparisonInstitutions().map( - (i: CompareItem) => `${i.id}|${i.name}`, + (i: CompareItem) => `${cleanEntityId(i.id)}|${i.name}`, ) : null, countries: @@ -1727,7 +1048,7 @@ export class UniTrendParentComponent implements OnInit { authors: this.comparisonAuthors().length > 0 ? this.comparisonAuthors().map( - (a: CompareItem) => `${a.id}|${a.name}`, + (a: CompareItem) => `${cleanEntityId(a.id)}|${a.name}`, ) : null, start_year: this.startYear(), @@ -1744,35 +1065,13 @@ export class UniTrendParentComponent implements OnInit { }); } - fetchTreemapData() { - const fuzzy = this.state?.fuzzySearch() ?? true; - const topics = this.selectedTrendTopics(); - if (!fuzzy || topics.length === 0) { - this.topicTreemap.set(null); - return; - } - this.isTreemapLoading.set(true); - this.topicsService.countTopicHierarchy(topics).subscribe({ - next: (res: any) => { - this.topicTreemap.set(res); - this.isTreemapLoading.set(false); - }, - error: () => { - this.isTreemapLoading.set(false); - }, - }); - } - onTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedTopicTreemapNode.set(nodeId); this.updateUrlParams(); } - onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { - // Topic selected inside treemap component - } + onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {} - // Checkbox topic toggling onTrendTopicToggle(topic: string, event: Event) { const isChecked = (event.target as HTMLInputElement).checked; const current = this.selectedTrendTopics(); @@ -1796,9 +1095,9 @@ export class UniTrendParentComponent implements OnInit { if (!updated.includes(active) || this.isTopicEmpty(active)) { this.activeChartTopic.set(this.findFirstNonEmptyTopic(updated)); } + this.updateUrlParams(); } - // Strategy SearchType changes setSearchType( type: 'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all', ) { @@ -1806,33 +1105,15 @@ export class UniTrendParentComponent implements OnInit { return; } this.selectedSearchType.set(type); - - // Auto-initialize default lists if empty for the target type - const kws = this.keywords(); - if (kws.length > 0) { - if (type === 'authors' && this.comparisonAuthors().length === 0) { - this.initializeDefaultAuthors(); - } else if ( - type !== 'authors' && - type !== 'news' && - type !== 'all' && - this.comparisonInstitutions().length === 0 - ) { - this.initializeDefaultInstitutions(); - } - } - this.updateUrlParams(); } - // Add comparison institution addInstitution(id: string, name: string) { - const cleanId = this.cleanEntityId(id); + const cleanId = cleanEntityId(id); const current = this.comparisonInstitutions(); - const exists = current.some((i: CompareItem) => { - const itemClean = this.cleanEntityId(i.id); - return itemClean.toLowerCase() === cleanId.toLowerCase(); - }); + const exists = current.some( + (i: CompareItem) => cleanEntityId(i.id) === cleanId, + ); if (!exists) { this.hasUserClearedInstitutions.set(false); this.comparisonInstitutions.set([...current, { id: cleanId, name }]); @@ -1843,10 +1124,10 @@ export class UniTrendParentComponent implements OnInit { } removeInstitution(id: string) { - const cleanTarget = this.cleanEntityId(id); + const cleanTarget = cleanEntityId(id); const current = this.comparisonInstitutions(); const updated = current.filter( - (i: CompareItem) => this.cleanEntityId(i.id) !== cleanTarget, + (i: CompareItem) => cleanEntityId(i.id) !== cleanTarget, ); if (updated.length === 0) { this.hasUserClearedInstitutions.set(true); @@ -1855,14 +1136,13 @@ export class UniTrendParentComponent implements OnInit { this.updateUrlParams(); } - // Add country or region addLocation(loc: AutocompleteLocationItem) { if (loc.type === 'country') { const current = this.comparisonCountries(); if (!current.some((c: CompareItem) => c.id === loc.id)) { this.comparisonCountries.set([ ...current, - { id: loc.id, name: loc.display_name }, + { id: loc.id.toUpperCase(), name: loc.display_name }, ]); } } else if (loc.type === 'continent') { @@ -1896,35 +1176,37 @@ export class UniTrendParentComponent implements OnInit { this.updateUrlParams(); } - // Add Top 3 Authors for a selected institution from institutions autocomplete addInstitutionAuthors(id: string, name: string) { - const kws = this.keywords(); - const topics = this.state?.topicsList() ?? kws; - const topic = - this.activeChartTopic() || topics[0] || 'Artificial Intelligence'; + const cleanInstId = cleanEntityId(id); + const rawTopic = + this.activeChartTopic() || + (this.selectedTrendTopics().length > 0 + ? this.selectedTrendTopics()[0] + : 'Artificial Intelligence'); + const topic = this.getMappedTopic(rawTopic); - this.isSuggestionsLoading.set(true); + this.trendDataService.isSuggestionsLoading.set(true); this.personsApiService .searchPersonsList( - undefined, // query - id, // institutionId - 'cited_by_count', // sortBy - 'desc', // sortOrder - [topic], // topic - 1, // page - 3, // pageSize - undefined, // include + undefined, + cleanInstId, + 'cited_by_count', + 'desc', + [topic], + 1, + 3, + undefined, ) .subscribe({ next: (res) => { const current = this.comparisonAuthors(); const updated = [...current]; (res.results || []).forEach((author: any) => { - const shortId = this.cleanEntityId(author.id); + const shortId = cleanEntityId(author.id); if ( shortId && - !updated.some((a) => this.cleanEntityId(a.id) === shortId) + !updated.some((a) => cleanEntityId(a.id) === shortId) ) { updated.push({ id: shortId, @@ -1936,12 +1218,12 @@ export class UniTrendParentComponent implements OnInit { this.hasUserClearedAuthors.set(false); } this.comparisonAuthors.set(updated); - this.isSuggestionsLoading.set(false); + this.trendDataService.isSuggestionsLoading.set(false); this.updateUrlParams(); }, error: (err) => { console.error('Failed to load top authors for institution:', err); - this.isSuggestionsLoading.set(false); + this.trendDataService.isSuggestionsLoading.set(false); }, }); @@ -1950,9 +1232,9 @@ export class UniTrendParentComponent implements OnInit { } addAuthor(id: string, name: string) { - const shortId = this.cleanEntityId(id); + const shortId = cleanEntityId(id); const current = this.comparisonAuthors(); - if (!current.some((a) => this.cleanEntityId(a.id) === shortId)) { + if (!current.some((a) => cleanEntityId(a.id) === shortId)) { this.hasUserClearedAuthors.set(false); this.comparisonAuthors.set([...current, { id: shortId, name }]); this.updateUrlParams(); @@ -1960,10 +1242,10 @@ export class UniTrendParentComponent implements OnInit { } removeAuthor(id: string) { - const cleanTarget = this.cleanEntityId(id); + const cleanTarget = cleanEntityId(id); const current = this.comparisonAuthors(); const updated = current.filter( - (a: CompareItem) => this.cleanEntityId(a.id) !== cleanTarget, + (a: CompareItem) => cleanEntityId(a.id) !== cleanTarget, ); if (updated.length === 0) { this.hasUserClearedAuthors.set(true); @@ -1972,7 +1254,6 @@ export class UniTrendParentComponent implements OnInit { this.updateUrlParams(); } - // Scaling mode toggle (data reuses instantly) setChartMode(mode: 'normalized' | 'total' | 'cumulative') { this.chartMode.set(mode); this.updateUrlParams(); @@ -1984,7 +1265,6 @@ export class UniTrendParentComponent implements OnInit { } } - // Topic tab toggle (data reuses instantly, no router navigation to prevent chart flickering) updateActiveChartTopic(topic: string) { if (this.isTopicEmpty(topic)) { return; @@ -1992,7 +1272,6 @@ export class UniTrendParentComponent implements OnInit { this.activeChartTopic.set(topic); } - // Autocomplete query changes for institutions onSearchChange(query: string) { this.searchQuery.set(query); if (query.trim().length >= 3) { @@ -2011,7 +1290,6 @@ export class UniTrendParentComponent implements OnInit { } } - // Autocomplete query changes for locations onLocationSearchChange(query: string) { this.locationQuery.set(query); if (query.trim().length >= 2) { @@ -2032,7 +1310,6 @@ export class UniTrendParentComponent implements OnInit { } } - // Autocomplete query changes for authors in the authors tab (direct search) onAuthorSearchChange(query: string) { this.authorSearchQuery.set(query); if (query.trim().length >= 3) { @@ -2054,7 +1331,6 @@ export class UniTrendParentComponent implements OnInit { } } - // Autocomplete query changes for institutions inside the top-authors selector onAuthorInstSearchChange(query: string) { this.authorInstSearchQuery.set(query); if (query.trim().length >= 3) { diff --git a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts new file mode 100644 index 00000000..5c3d3a74 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -0,0 +1,108 @@ +import { TrendSeries, TopicYearlyData } from '../../../api'; +import { CompareItem } from '../models/trend.models'; + +/** + * Extracts short OpenAlex ID from full URL or string, ensuring uppercase ID prefix (e.g. I62318514, A50012345). + */ +export function cleanEntityId(id: string | null | undefined): string { + if (!id) return ''; + const trimmed = id.trim(); + const raw = trimmed.includes('/') ? trimmed.split('/').pop()! : trimmed; + if (raw.length > 1 && /^[a-zA-Z]/.test(raw)) { + return raw[0].toUpperCase() + raw.substring(1); + } + return raw.toUpperCase(); +} + +/** + * Checks if a given topic contains zero publication/patent counts across all series within year range. + */ +export function isTopicEmptyForSeries( + topicName: string, + seriesList: TrendSeries[], + startYr: number, + endYr: number, +): boolean { + if (!seriesList || seriesList.length === 0) return true; + for (const s of seriesList) { + const topicItems = s.topic_data?.[topicName] || []; + const filtered = topicItems.filter( + (y) => y.year >= startYr && y.year <= endYr, + ); + const sumRaw = filtered.reduce((acc, curr) => acc + (curr.raw || 0), 0); + if (sumRaw > 0) return false; + } + return true; +} + +/** + * Finds the first non-empty topic in the list. + */ +export function findFirstNonEmptyTopic( + topics: string[], + seriesList: TrendSeries[], + startYr: number, + endYr: number, +): string { + if (!topics || topics.length === 0) return ''; + for (const t of topics) { + if (!isTopicEmptyForSeries(t, seriesList, startYr, endYr)) { + return t; + } + } + return topics[0]; +} + +/** + * Builds deterministic entity color lookup map based on entity order and ID. + */ +export function buildEntityColorIndex( + primaryId: string | null, + institutions: CompareItem[], + countries: CompareItem[], + regions: CompareItem[], + authors: CompareItem[], +): (id: string) => string { + const entityColors = [ + '#ec4899', // Pink (Primary UDE) + '#3b82f6', // Blue + '#10b981', // Emerald Green + '#f59e0b', // Amber/Yellow + '#8b5cf6', // Purple + '#06b6d4', // Cyan + '#6366f1', // Indigo + '#ef4444', // Red + '#14b8a6', // Teal + '#f97316', // Orange + '#d946ef', // Fuchsia + '#84cc16', // Lime + '#22c55e', // Green + '#a855f7', // Purple/Fuchsia + '#eab308', // Yellow + '#f43f5e', // Rose + ]; + + const colorMap = new Map(); + let nextIdx = 0; + + const cleanPrimary = cleanEntityId(primaryId || 'I62318514'); + if (cleanPrimary) { + colorMap.set(cleanPrimary, entityColors[0]); + nextIdx = 1; + } + + const allItems = [...institutions, ...countries, ...regions, ...authors]; + allItems.forEach((item) => { + const cId = cleanEntityId(item.id); + if (cId && !colorMap.has(cId)) { + const color = entityColors[nextIdx % entityColors.length]; + colorMap.set(cId, color); + nextIdx++; + } + }); + + return (id: string): string => { + const cId = cleanEntityId(id); + return colorMap.get(cId) || entityColors[0]; + }; +} diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 9eef6b9e..a5d2ddb9 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -8,11 +8,12 @@ import { } 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; - name: string; -} +import { CompareItem } from '../modules/university-ranking/models/trend.models'; +import { cleanEntityId } from '../modules/university-ranking/utils/trend.utils'; +import { + TrendDataService, + TrendRequestParams, +} from '../modules/university-ranking/services/trend-data.service'; export interface UniTrendResolvedData { trendResponse: TrendResponse | null; @@ -37,14 +38,16 @@ export const uniTrendResolver: ResolveFn = ( const params = route.queryParamMap; const searchState = inject(SearchResultsStateService, { optional: true }); const credentialService = inject(CredentialService, { optional: true }); + const trendDataService = inject(TrendDataService); 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 = + const rawPrimaryInstId = credentialService?.effectiveInstitutionId() || 'I62318514'; + const primaryInstId = cleanEntityId(rawPrimaryInstId); const primaryInstName = credentialService?.organizationName() || 'Universität Duisburg-Essen'; @@ -87,16 +90,12 @@ export const uniTrendResolver: ResolveFn = ( keywords = topics; } - // Parse comparison items + // Parse comparison items ensuring clean uppercase OpenAlex IDs const instParams = params.getAll('institutions'); const parsedInstitutions: CompareItem[] = instParams.map((i) => { const parts = i.split('|'); - const cleanId = parts[0].includes('/') - ? parts[0].split('/').pop() || parts[0] - : parts[0]; - const isPrimary = - cleanId.toLowerCase() === primaryInstId.toLowerCase() || - primaryInstId.toLowerCase().includes(cleanId.toLowerCase()); + const cleanId = cleanEntityId(parts[0]); + const isPrimary = cleanId === primaryInstId; const name = parts[1] || (isPrimary ? primaryInstName : parts[0]); return { id: cleanId, name }; }); @@ -108,7 +107,7 @@ export const uniTrendResolver: ResolveFn = ( const countryParams = params.getAll('countries'); const parsedCountries: CompareItem[] = countryParams.map((c) => { const parts = c.split('|'); - return { id: parts[0], name: parts[1] || parts[0] }; + return { id: parts[0].toUpperCase(), name: parts[1] || parts[0] }; }); const regionParams = params.getAll('regions'); @@ -120,15 +119,15 @@ export const uniTrendResolver: ResolveFn = ( const authorParams = params.getAll('authors'); const parsedAuthors: CompareItem[] = authorParams.map((a) => { const parts = a.split('|'); - return { id: parts[0], name: parts[1] || parts[0] }; + const cleanId = cleanEntityId(parts[0]); + return { id: cleanId, name: parts[1] || parts[0] }; }); const instIds = parsedInstitutions.length > 0 ? parsedInstitutions.map((i) => i.id) : [primaryInstId]; - const countryIds = - parsedCountries.length > 0 ? parsedCountries.map((c) => c.id) : ['DE']; + const countryIds = parsedCountries.map((c) => c.id); const regionIds = parsedRegions.map((r) => r.id); const authorIds = parsedAuthors.map((a) => a.id); @@ -141,18 +140,41 @@ export const uniTrendResolver: ResolveFn = ( const regionFilter = parsedRegions.length > 0 ? parsedRegions[0].id : undefined; - const trendObs$ = apiService - .getTrendApiInseServiceUniversityRankingsTrendGet( - topics, - keywords, - fuzzy, - instIds, - countryIds, - regionIds, - authorIds, - searchType as any, - ) - .pipe(catchError(() => of(null))); + const currentParams: TrendRequestParams = { + topics, + keywords, + fuzzy, + institutions: instIds, + countries: countryIds, + regions: regionIds, + authors: authorIds, + searchType, + }; + + // Check soft cache + let trendObs$: Observable; + if (trendDataService.canReuseCache(currentParams)) { + trendObs$ = of(trendDataService.cachedResponse()); + } else { + trendObs$ = apiService + .getTrendApiInseServiceUniversityRankingsTrendGet( + topics, + keywords, + fuzzy, + instIds, + countryIds, + regionIds, + authorIds, + searchType as any, + ) + .pipe( + map((res) => { + trendDataService.updateCache(res, currentParams); + return res; + }), + catchError(() => of(null)), + ); + } const topInstObs$ = searchType !== 'authors' @@ -191,7 +213,6 @@ export const uniTrendResolver: ResolveFn = ( recommendedAuthors: recAuthorsObs$, }).pipe( map(({ trendResponse, topSuggestions, recommendedAuthors }) => { - // Find the first topic with non-zero publication data let initialActiveTopic = primaryTopic; if ( trendResponse?.series && @@ -225,7 +246,6 @@ export const uniTrendResolver: ResolveFn = ( } } - // If in author mode and no explicit authors were passed in URL, populate default top authors if ( searchType === 'authors' && parsedAuthors.length === 0 && @@ -233,7 +253,7 @@ export const uniTrendResolver: ResolveFn = ( ) { recommendedAuthors.slice(0, 3).forEach((author: any) => { parsedAuthors.push({ - id: author.id, + id: cleanEntityId(author.id), name: author.display_name || 'Unbekannt', }); }); -- 2.56.1 From 9f10e9e7af6d6c8da555c85d86155b4b0df9dbe1 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 31 Jul 2026 13:55:02 +0200 Subject: [PATCH 2/7] fixed resolver issues, where fuzzy search would not display anything --- webapp/src/app/app.routes.ts | 5 +- .../search-results-state.service.ts | 22 ++++++- .../uni-trend-parent.component.html | 2 +- .../uni-trend-parent.component.ts | 60 ++++++++++++------- .../src/app/resolvers/uni-trend.resolver.ts | 46 +++++++++++--- 5 files changed, 102 insertions(+), 33 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 1a63d1a6..52eb03f3 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -285,6 +285,7 @@ export const routes: Routes = [ 'search_type', 'topic', 'topics', + 'trend_topics', 'keyword', 'keywords', 'institutions', @@ -294,7 +295,9 @@ export const routes: Routes = [ 'fuzzy', ]; return keys.some( - (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + (key) => + from.queryParamMap.getAll(key).join(',') !== + to.queryParamMap.getAll(key).join(','), ); }, }, 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 2401dc97..301b1d72 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 @@ -107,6 +107,15 @@ export class SearchResultsStateService { result.push(entry); } + console.log( + '[TrendDebug] SearchResultsStateService selectedKeywordEntries:', + result.map((e) => ({ + kw: e.llm_keyword?.keyword, + topicName: e.topic_mapping?.topic?.display_name, + topicId: e.topic_mapping?.topic?.id, + })), + ); + return result; }); @@ -150,10 +159,21 @@ export class SearchResultsStateService { return kw; }) .filter((t) => t.length > 0); - return Array.from(new Set(list)); + const uniqueTopics = Array.from(new Set(list)); + console.log( + '[TrendDebug] SearchResultsStateService topicsList computed:', + uniqueTopics, + ); + return uniqueTopics; }); setPayload(payload: SearchResultsPayload): void { + console.log('[TrendDebug] SearchResultsStateService setPayload:', { + keywords: payload.keywords, + extractedCount: payload.extractedKeywords?.length ?? 0, + manualCount: payload.manualKeywords?.length ?? 0, + fuzzy: payload.options?.fuzzy, + }); this._payload.set(payload); } } 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 82362c53..1ea744c2 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 @@ -186,7 +186,7 @@ } @if (selectedTrendTopics().length > 0) {
- @for (topic of selectedTrendTopics(); track topic) { + @for (topic of selectedTrendTopics(); track $index) { @if (selectedSearchType() === 'news') { 0) { this.selectedTrendTopics.set(resolved.topics); const targetTopic = @@ -855,12 +861,12 @@ export class UniTrendParentComponent implements OnInit { effect(() => { const kws = this.keywords(); const fuzzy = this.isFuzzy(); - const topics = fuzzy ? (this.state?.topicsList() ?? kws) : kws; - const currentSelections = untracked(() => this.selectedTrendTopics()); - const currentActive = untracked(() => this.activeChartTopic()); + const stateTopicsList = this.state?.topicsList(); + const topics = fuzzy ? (stateTopicsList ?? kws) : kws; if (topics.length > 0) { - const altTopics = fuzzy ? kws : (this.state?.topicsList() ?? kws); + const currentSelections = untracked(() => this.selectedTrendTopics()); + const altTopics = fuzzy ? kws : (stateTopicsList ?? kws); const mappedSelections: string[] = []; currentSelections.forEach((item) => { @@ -874,29 +880,37 @@ export class UniTrendParentComponent implements OnInit { } }); - const finalSelections = Array.from(new Set(mappedSelections)); - if (finalSelections.length > 0) { - this.selectedTrendTopics.set(finalSelections); - } else { - this.selectedTrendTopics.set(topics); + const targetSelections = + mappedSelections.length > 0 + ? Array.from(new Set(mappedSelections)) + : topics; + + // Only update selectedTrendTopics if array actually changed to prevent DOM re-creation + const current = untracked(() => this.selectedTrendTopics()); + const hasChanged = + targetSelections.length !== current.length || + targetSelections.some((t, i) => t !== current[i]); + + if (hasChanged) { + this.selectedTrendTopics.set(targetSelections); } - const active = currentActive; - const updatedSelections = untracked(() => this.selectedTrendTopics()); - const mappedActive = this.getMappedTopic(active); - if ( - mappedActive && - updatedSelections.includes(mappedActive) && - !this.isTopicEmpty(mappedActive) - ) { - this.activeChartTopic.set(mappedActive); - } else { - this.activeChartTopic.set( - this.findFirstNonEmptyTopic(updatedSelections), - ); + const currentActive = untracked(() => this.activeChartTopic()); + const validSelections = untracked(() => this.selectedTrendTopics()); + + if (!currentActive || !validSelections.includes(currentActive)) { + const firstValid = this.findFirstNonEmptyTopic(validSelections); + if (firstValid) { + this.activeChartTopic.set(firstValid); + } else if (validSelections.length > 0) { + this.activeChartTopic.set(validSelections[0]); + } } } else { - this.selectedTrendTopics.set([]); + const current = untracked(() => this.selectedTrendTopics()); + if (current.length > 0) { + this.selectedTrendTopics.set([]); + } } }); diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index a5d2ddb9..82e87e07 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -66,18 +66,44 @@ export const uniTrendResolver: ResolveFn = ( keywords = searchState.keywords(); } - let topics = params.getAll('topic'); + let topics = [ + ...params.getAll('trend_topics'), + ...params.getAll('trend_topic'), + ]; if (topics.length === 0) { - const rawTopics = params.get('topics'); - if (rawTopics) { - topics = rawTopics - .split(',') + const rawTopicsList = [ + ...params.getAll('topic'), + ...params.getAll('topics'), + ]; + if (rawTopicsList.length > 0) { + topics = rawTopicsList + .flatMap((t) => t.split(',')) .map((t) => t.trim()) .filter((t) => t.length > 0); } } - if (topics.length === 0 && searchState) { - topics = fuzzy ? searchState.topicsList() : searchState.keywords(); + + console.log('[TrendDebug] Resolver input params:', { + fuzzy, + searchType, + urlTrendTopics: params.getAll('trend_topics'), + urlTopics: params.getAll('topics'), + urlKeywords: params.get('keywords') || params.getAll('keyword'), + hasSearchState: !!searchState, + }); + + if (searchState) { + const stateTopics = fuzzy + ? searchState.topicsList() + : searchState.keywords(); + if ( + topics.length === 0 || + (fuzzy && + stateTopics.length > 0 && + topics.some((t) => t.startsWith('http') || /^T\d+$/i.test(t))) + ) { + topics = stateTopics; + } } // Fallback defaults if no topics/keywords present yet @@ -90,6 +116,12 @@ export const uniTrendResolver: ResolveFn = ( keywords = topics; } + console.log('[TrendDebug] Resolver resolved topics & keywords:', { + topics, + keywords, + searchType, + }); + // Parse comparison items ensuring clean uppercase OpenAlex IDs const instParams = params.getAll('institutions'); const parsedInstitutions: CompareItem[] = instParams.map((i) => { -- 2.56.1 From d4daecd921061252a581360f5e5d6492f96b3529 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 31 Jul 2026 14:08:24 +0200 Subject: [PATCH 3/7] fix fuzzy / keyword names on chips --- .../uni-trend-parent/uni-trend-parent.component.ts | 5 ++++- webapp/src/app/resolvers/uni-trend.resolver.ts | 9 +++++---- 2 files changed, 9 insertions(+), 5 deletions(-) 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 ecc9483c..1b7d0cd3 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 @@ -212,6 +212,9 @@ export class UniTrendParentComponent implements OnInit { getMappedTopic(topicOrKeyword: string): string { if (!topicOrKeyword) return ''; + if (!this.isFuzzy()) { + return topicOrKeyword; + } const cleanId = cleanEntityId(topicOrKeyword); const isTopicId = @@ -1040,7 +1043,7 @@ export class UniTrendParentComponent implements OnInit { updateUrlParams() { const queryParams: any = { search_type: this.selectedSearchType(), - trend_topics: this.selectedTrendTopics(), + trend_topics: this.isFuzzy() ? this.selectedTrendTopics() : null, institutions: this.comparisonInstitutions().length > 0 ? this.comparisonInstitutions().map( diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 82e87e07..e94170da 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -66,10 +66,10 @@ export const uniTrendResolver: ResolveFn = ( keywords = searchState.keywords(); } - let topics = [ - ...params.getAll('trend_topics'), - ...params.getAll('trend_topic'), - ]; + let topics = fuzzy + ? [...params.getAll('trend_topics'), ...params.getAll('trend_topic')] + : []; + if (topics.length === 0) { const rawTopicsList = [ ...params.getAll('topic'), @@ -97,6 +97,7 @@ export const uniTrendResolver: ResolveFn = ( ? searchState.topicsList() : searchState.keywords(); if ( + !fuzzy || topics.length === 0 || (fuzzy && stateTopics.length > 0 && -- 2.56.1 From 9c3e36930c42373007ba8cdfc624699db4cfdbcd Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 31 Jul 2026 14:24:20 +0200 Subject: [PATCH 4/7] changed caching to Parameter Keyed caching. Rest is handled by resolver and e-tags --- .../services/trend-data.service.ts | 57 ++++++++++--------- .../uni-trend-parent.component.ts | 12 +++- .../src/app/resolvers/uni-trend.resolver.ts | 4 +- 3 files changed, 41 insertions(+), 32 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts index 106bf141..626102f3 100644 --- a/webapp/src/app/modules/university-ranking/services/trend-data.service.ts +++ b/webapp/src/app/modules/university-ranking/services/trend-data.service.ts @@ -26,7 +26,7 @@ export class TrendDataService { private readonly apiService = inject(UniversityRankingsService); private readonly personsApiService = inject(PersonsService); - // Soft cache signals + // Cache signals readonly cachedResponse = signal(null); readonly cachedParams = signal(null); @@ -40,44 +40,45 @@ export class TrendDataService { readonly isTopTopicsLoading = signal(false); readonly topTopicsError = signal(false); + private readonly cacheMap = new Map(); + + private getCacheKey(params: TrendRequestParams): string { + return JSON.stringify({ + searchType: params.searchType, + fuzzy: params.fuzzy, + topics: [...params.topics].sort(), + keywords: params.keywords ? [...params.keywords].sort() : [], + insts: (params.institutions || []).map(cleanEntityId).sort(), + authors: (params.authors || []).map(cleanEntityId).sort(), + countries: (params.countries || []).sort(), + regions: (params.regions || []).sort(), + }); + } + /** - * Updates soft cache with response and params from resolver or component. + * Updates cache map with response and params from resolver or component. */ updateCache(response: TrendResponse, params: TrendRequestParams): void { + const key = this.getCacheKey(params); + this.cacheMap.set(key, response); this.cachedResponse.set(response); this.cachedParams.set(params); } /** - * Checks if requested params can be satisfied by cached response. + * Checks if exact requested params can be satisfied by cached response. */ canReuseCache(newParams: TrendRequestParams): boolean { - const currentResp = this.cachedResponse(); - const currentParams = this.cachedParams(); - if (!currentResp || !currentParams) return false; + const key = this.getCacheKey(newParams); + return this.cacheMap.has(key); + } - if (currentParams.searchType !== newParams.searchType) return false; - if (currentParams.fuzzy !== newParams.fuzzy) return false; - - // Topics check - const currentTopics = [...currentParams.topics].sort().join(','); - const targetTopics = [...newParams.topics].sort().join(','); - if (currentTopics !== targetTopics) return false; - - // Check if new entities are a subset of cached entities - const currentInsts = new Set( - (currentParams.institutions || []).map(cleanEntityId), - ); - const targetInsts = (newParams.institutions || []).map(cleanEntityId); - if (!targetInsts.every((id) => currentInsts.has(id))) return false; - - const currentAuthors = new Set( - (currentParams.authors || []).map(cleanEntityId), - ); - const targetAuthors = (newParams.authors || []).map(cleanEntityId); - if (!targetAuthors.every((id) => currentAuthors.has(id))) return false; - - return true; + /** + * Retrieves exact cached response for requested params. + */ + getCachedResponse(newParams: TrendRequestParams): TrendResponse | null { + const key = this.getCacheKey(newParams); + return this.cacheMap.get(key) ?? null; } /** 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 1b7d0cd3..81aa247e 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 @@ -42,6 +42,7 @@ import { InstitutionsService, PersonsService, OrganizationService, + Author, } from '../../../api'; import { CredentialService } from '../../../shared/services/credential.service'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; @@ -197,7 +198,7 @@ export class UniTrendParentComponent implements OnInit { readonly locationQuery = signal(''); readonly locationSearchResults = signal([]); readonly authorSearchQuery = signal(''); - readonly authorSearchResults = signal([]); + readonly authorSearchResults = signal([]); readonly authorInstSearchQuery = signal(''); readonly authorInstSearchResults = signal( [], @@ -1134,6 +1135,7 @@ export class UniTrendParentComponent implements OnInit { if (!exists) { this.hasUserClearedInstitutions.set(false); this.comparisonInstitutions.set([...current, { id: cleanId, name }]); + this.isTrendLoading.set(true); this.updateUrlParams(); } this.searchQuery.set(''); @@ -1150,6 +1152,7 @@ export class UniTrendParentComponent implements OnInit { this.hasUserClearedInstitutions.set(true); } this.comparisonInstitutions.set(updated); + this.isTrendLoading.set(true); this.updateUrlParams(); } @@ -1174,6 +1177,7 @@ export class UniTrendParentComponent implements OnInit { this.locationQuery.set(''); this.locationSearchResults.set([]); this.loadTrendSuggestions(); + this.isTrendLoading.set(true); this.updateUrlParams(); } @@ -1190,6 +1194,7 @@ export class UniTrendParentComponent implements OnInit { ); } this.loadTrendSuggestions(); + this.isTrendLoading.set(true); this.updateUrlParams(); } @@ -1219,7 +1224,7 @@ export class UniTrendParentComponent implements OnInit { next: (res) => { const current = this.comparisonAuthors(); const updated = [...current]; - (res.results || []).forEach((author: any) => { + (res.results || []).forEach((author: Author) => { const shortId = cleanEntityId(author.id); if ( shortId && @@ -1236,6 +1241,7 @@ export class UniTrendParentComponent implements OnInit { } this.comparisonAuthors.set(updated); this.trendDataService.isSuggestionsLoading.set(false); + this.isTrendLoading.set(true); this.updateUrlParams(); }, error: (err) => { @@ -1254,6 +1260,7 @@ export class UniTrendParentComponent implements OnInit { if (!current.some((a) => cleanEntityId(a.id) === shortId)) { this.hasUserClearedAuthors.set(false); this.comparisonAuthors.set([...current, { id: shortId, name }]); + this.isTrendLoading.set(true); this.updateUrlParams(); } } @@ -1268,6 +1275,7 @@ export class UniTrendParentComponent implements OnInit { this.hasUserClearedAuthors.set(true); } this.comparisonAuthors.set(updated); + this.isTrendLoading.set(true); this.updateUrlParams(); } diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index e94170da..e48f81de 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -184,10 +184,10 @@ export const uniTrendResolver: ResolveFn = ( searchType, }; - // Check soft cache + // Check exact parameter keyed cache let trendObs$: Observable; if (trendDataService.canReuseCache(currentParams)) { - trendObs$ = of(trendDataService.cachedResponse()); + trendObs$ = of(trendDataService.getCachedResponse(currentParams)); } else { trendObs$ = apiService .getTrendApiInseServiceUniversityRankingsTrendGet( -- 2.56.1 From faa866f4e1a382d4aa601bc9b727e7a2c9e2bc7a Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 31 Jul 2026 16:04:14 +0200 Subject: [PATCH 5/7] added exception handling --- .../main/inse/university_ranking/service.py | 5 +++- .../src/app/resolvers/uni-trend.resolver.ts | 28 ++++++++----------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py index 112a2a6f..f22427ed 100644 --- a/service/src/main/inse/university_ranking/service.py +++ b/service/src/main/inse/university_ranking/service.py @@ -3,6 +3,7 @@ from typing import List, Optional from fastapi import APIRouter, Query, Depends from inse.tags import Tags +from inse.exceptions import BadRequestException from . import logic, trend_logic from .model import ( RankingResponse, @@ -43,7 +44,7 @@ def get_trend_strategy(search_type: TrendSearchType = Query(TrendSearchType.PUBL return NewsTrendStrategy() elif search_type == TrendSearchType.ALL: return AllTrendStrategy() - raise ValueError(f"Unknown search type: {search_type}") + raise BadRequestException(f"Unknown search type: {search_type}") @router.get( "", @@ -74,6 +75,8 @@ async def get_trend( authors: Optional[List[str]] = Query(None, description="List of OpenAlex Author IDs"), strategy: TrendStrategy = Depends(get_trend_strategy) ): + if not topics or len(topics) == 0: + raise BadRequestException("Topics list cannot be empty") return await strategy.get_trend( topics=topics, keywords=keywords, diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index e48f81de..679ac38a 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -10,6 +10,7 @@ import { SearchResultsStateService } from '../modules/keywords-search/search-res import { CredentialService } from '../shared/services/credential.service'; import { CompareItem } from '../modules/university-ranking/models/trend.models'; import { cleanEntityId } from '../modules/university-ranking/utils/trend.utils'; +import { ErrorService } from '../shared/services/error.service'; import { TrendDataService, TrendRequestParams, @@ -83,15 +84,6 @@ export const uniTrendResolver: ResolveFn = ( } } - console.log('[TrendDebug] Resolver input params:', { - fuzzy, - searchType, - urlTrendTopics: params.getAll('trend_topics'), - urlTopics: params.getAll('topics'), - urlKeywords: params.get('keywords') || params.getAll('keyword'), - hasSearchState: !!searchState, - }); - if (searchState) { const stateTopics = fuzzy ? searchState.topicsList() @@ -117,12 +109,6 @@ export const uniTrendResolver: ResolveFn = ( keywords = topics; } - console.log('[TrendDebug] Resolver resolved topics & keywords:', { - topics, - keywords, - searchType, - }); - // Parse comparison items ensuring clean uppercase OpenAlex IDs const instParams = params.getAll('institutions'); const parsedInstitutions: CompareItem[] = instParams.map((i) => { @@ -163,8 +149,8 @@ export const uniTrendResolver: ResolveFn = ( const countryIds = parsedCountries.map((c) => c.id); const regionIds = parsedRegions.map((r) => r.id); const authorIds = parsedAuthors.map((a) => a.id); - const apiService = inject(UniversityRankingsService); + const errorService = inject(ErrorService); const personsService = inject(PersonsService, { optional: true }); const primaryTopic = topics[0] || 'Artificial Intelligence'; @@ -205,7 +191,15 @@ export const uniTrendResolver: ResolveFn = ( trendDataService.updateCache(res, currentParams); return res; }), - catchError(() => of(null)), + catchError((err) => { + errorService.setError({ + statusCode: err?.status || 500, + title: 'Visualisierungs-Fehler', + message: 'Trenddaten konnten nicht geladen werden.', + errorDetails: err?.message || String(err), + }); + return of(null); + }), ); } -- 2.56.1 From 034d3ee453e24d1b8849afee185a5983db1ac316 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 31 Jul 2026 16:56:32 +0200 Subject: [PATCH 6/7] style changes and removed last logs --- .../search-results-state.service.ts | 20 +------------------ .../uni-trend-parent.component.ts | 18 +++++++++++------ .../university-ranking/utils/trend.utils.ts | 11 +++++++++- webapp/src/styles.scss | 11 ++++++++++ 4 files changed, 34 insertions(+), 26 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 301b1d72..3791c58c 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 @@ -107,15 +107,6 @@ export class SearchResultsStateService { result.push(entry); } - console.log( - '[TrendDebug] SearchResultsStateService selectedKeywordEntries:', - result.map((e) => ({ - kw: e.llm_keyword?.keyword, - topicName: e.topic_mapping?.topic?.display_name, - topicId: e.topic_mapping?.topic?.id, - })), - ); - return result; }); @@ -160,20 +151,11 @@ export class SearchResultsStateService { }) .filter((t) => t.length > 0); const uniqueTopics = Array.from(new Set(list)); - console.log( - '[TrendDebug] SearchResultsStateService topicsList computed:', - uniqueTopics, - ); + return uniqueTopics; }); setPayload(payload: SearchResultsPayload): void { - console.log('[TrendDebug] SearchResultsStateService setPayload:', { - keywords: payload.keywords, - extractedCount: payload.extractedKeywords?.length ?? 0, - manualCount: payload.manualKeywords?.length ?? 0, - fuzzy: payload.options?.fuzzy, - }); this._payload.set(payload); } } 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 81aa247e..bb8d6308 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 @@ -584,6 +584,18 @@ export class UniTrendParentComponent implements OnInit { } getEntityColor(entityId: string): string { + if (this.selectedSearchType() === 'all') { + const categoryColors: Record = { + publications: '#3b82f6', + patents: '#f59e0b', + projects: '#10b981', + news: '#ec4899', + }; + const cleanKey = entityId.toLowerCase().trim(); + if (categoryColors[cleanKey]) { + return categoryColors[cleanKey]; + } + } if (this.selectedSearchType() === 'news') { const topicName = entityId.startsWith('news_topic_') ? entityId.slice('news_topic_'.length) @@ -825,12 +837,6 @@ export class UniTrendParentComponent implements OnInit { const type = resolved.searchType || this.selectedSearchType(); this.selectedSearchType.set(type); - console.log('[TrendDebug] UniTrendParent route data received:', { - resolvedTopics: resolved.topics, - initialActiveTopic: resolved.initialActiveTopic, - seriesCount: res?.series?.length ?? 0, - }); - if (resolved.topics && resolved.topics.length > 0) { this.selectedTrendTopics.set(resolved.topics); const targetTopic = diff --git a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts index 5c3d3a74..b5f28f9e 100644 --- a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -103,6 +103,15 @@ export function buildEntityColorIndex( return (id: string): string => { const cId = cleanEntityId(id); - return colorMap.get(cId) || entityColors[0]; + if (cId === 'WORLD') { + return '#3b82f6'; + } + if (colorMap.has(cId)) { + return colorMap.get(cId)!; + } + const charCodeSum = cId + .split('') + .reduce((sum, char) => sum + char.charCodeAt(0), 0); + return entityColors[(nextIdx + charCodeSum) % entityColors.length]; }; } diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index a0be26ca..71142e29 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -317,3 +317,14 @@ h3 { color: var(--sg-text-muted); font-size: 13px; } + +/* Scalable Relative Inline Icon Utility */ +.pie-icon-indicator { + font-size: 1.1em !important; + width: 1.1em !important; + height: 1.1em !important; + line-height: 1.1em !important; + vertical-align: middle; + flex-shrink: 0; + transition: transform 0.3s ease; +} -- 2.56.1 From 621a9dd2a1b67ae6dd6d7ca67a6cea52505c7f80 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 1 Aug 2026 12:30:18 +0200 Subject: [PATCH 7/7] fix: moved huggingface offline mode settings to base image, to prevent first call to fetch updates from huggingface --- service/Dockerfile.base | 11 +- .../sentence_transformer/download_model.py | 25 +++- service/sentence_transformer/index_topics.py | 3 +- service/src/main/inse/util.py | 132 ++++++++++-------- 4 files changed, 106 insertions(+), 65 deletions(-) diff --git a/service/Dockerfile.base b/service/Dockerfile.base index b278044a..41b4af31 100644 --- a/service/Dockerfile.base +++ b/service/Dockerfile.base @@ -6,5 +6,14 @@ RUN mkdir /test && \ pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \ pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1" +ARG MODEL_NAME=intfloat/multilingual-e5-base +ENV MODEL_NAME=${MODEL_NAME} ENV SENTENCE_TRANSFORMERS_HOME=/models -RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')" +ENV HF_HOME=/models + +RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])" + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 +ENV HF_DATASETS_OFFLINE=1 + diff --git a/service/sentence_transformer/download_model.py b/service/sentence_transformer/download_model.py index c4d7722e..cef45c27 100644 --- a/service/sentence_transformer/download_model.py +++ b/service/sentence_transformer/download_model.py @@ -6,9 +6,28 @@ so it is available for local runs or testing. Usage (run once from project root): python service/sentence_transformer/download_model.py """ +import os +import sys +from pathlib import Path + +# Ensure service/src/main is in sys.path +current_dir = Path(__file__).parent.resolve() +src_main_dir = current_dir.parent / "src" / "main" +if str(src_main_dir) not in sys.path: + sys.path.insert(0, str(src_main_dir)) + +from inse.config import settings from sentence_transformers import SentenceTransformer -MODEL_NAME = "intfloat/multilingual-e5-base" -print(f"Downloading '{MODEL_NAME}' to default cache directory...") +MODEL_NAME = settings.sentence_transformers_model_name +print(f"Downloading '{MODEL_NAME}' to cache directory...") model = SentenceTransformer(MODEL_NAME) -print("Done.") + +print(f"Verifying offline model loading for '{MODEL_NAME}'...") +os.environ["HF_HUB_OFFLINE"] = "1" +os.environ["TRANSFORMERS_OFFLINE"] = "1" +os.environ["HF_DATASETS_OFFLINE"] = "1" + +offline_model = SentenceTransformer(MODEL_NAME, local_files_only=True) +print("Done. Model downloaded and verified for 100% offline usage.") + diff --git a/service/sentence_transformer/index_topics.py b/service/sentence_transformer/index_topics.py index 12f29a9d..b340ee30 100644 --- a/service/sentence_transformer/index_topics.py +++ b/service/sentence_transformer/index_topics.py @@ -169,8 +169,9 @@ def main(): print("No topics found. Exiting.") return + from inse.util import get_model print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...") - model = SentenceTransformer(MODEL_NAME) + model = get_model() # 1. Gather all texts to embed keywords_by_topic = [] diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index 5848c92e..c41c469d 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -1,60 +1,72 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - This module contains utility functions - for the service implementation. -""" -from typing import Optional -from typing import TypeVar -from inse.models.openalex import Author -from . import model -from inse.exceptions import NotFoundException - -T = TypeVar('T') - -def raise_not_found_if_none(value: Optional[T]) -> T: - ''' Returns the value, if it is set, or raises a 404, if the value is None.''' - if value == None: - raise NotFoundException("Not found.") - else: - return value - -def get_persons_data(hit:dict): - source = hit.get("_source", {}) - source_copy = dict(source) - source_copy["id"] = hit.get("_id", "") or source_copy.get("id") - - # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) - ids = source_copy.get("ids") - if isinstance(ids, dict): - ids_copy = {} - orcid_val = ids.get("orcid") - if orcid_val: - ids_copy["orcid"] = str(orcid_val) - source_copy["ids"] = ids_copy - - author = Author.from_dict(source_copy) - return author - -from sentence_transformers import SentenceTransformer -from .config import settings -# Sentence Transformer Model -_model: SentenceTransformer | None = None - -def get_model(): - global _model - if _model is None: - import os - # If SENTENCE_TRANSFORMERS_HOME is not set, check if container-baked /models folder is available - if "SENTENCE_TRANSFORMERS_HOME" not in os.environ: - if os.path.exists("/models"): - os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models" - os.environ["HF_HUB_OFFLINE"] = "1" - else: - # If it is set to /models, enforce offline mode as it is baked into the image - if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models": - os.environ["HF_HUB_OFFLINE"] = "1" - - model_name = settings.sentence_transformers_model_name - _model = SentenceTransformer(model_name) - return _model \ No newline at end of file +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + This module contains utility functions + for the service implementation. +""" +from typing import Optional +from typing import TypeVar +from inse.models.openalex import Author +from . import model +from inse.exceptions import NotFoundException + +T = TypeVar('T') + +def raise_not_found_if_none(value: Optional[T]) -> T: + ''' Returns the value, if it is set, or raises a 404, if the value is None.''' + if value == None: + raise NotFoundException("Not found.") + else: + return value + +def get_persons_data(hit:dict): + source = hit.get("_source", {}) + source_copy = dict(source) + source_copy["id"] = hit.get("_id", "") or source_copy.get("id") + + # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) + ids = source_copy.get("ids") + if isinstance(ids, dict): + ids_copy = {} + orcid_val = ids.get("orcid") + if orcid_val: + ids_copy["orcid"] = str(orcid_val) + source_copy["ids"] = ids_copy + + author = Author.from_dict(source_copy) + return author + +from sentence_transformers import SentenceTransformer +from .config import settings +# Sentence Transformer Model +_model: SentenceTransformer | None = None + +def get_model(): + global _model + if _model is None: + import os + # Determine offline mode + is_offline = os.environ.get("HF_HUB_OFFLINE") == "1" + if "SENTENCE_TRANSFORMERS_HOME" not in os.environ: + if os.path.exists("/models"): + os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models" + os.environ["HF_HOME"] = "/models" + is_offline = True + elif os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models": + is_offline = True + + if is_offline: + os.environ["HF_HUB_OFFLINE"] = "1" + os.environ["TRANSFORMERS_OFFLINE"] = "1" + os.environ["HF_DATASETS_OFFLINE"] = "1" + + model_name = settings.sentence_transformers_model_name + try: + if is_offline: + _model = SentenceTransformer(model_name, local_files_only=True) + else: + _model = SentenceTransformer(model_name) + except Exception: + # Fallback if local_files_only fails in unexpected local dev environments + _model = SentenceTransformer(model_name) + return _model \ No newline at end of file -- 2.56.1