From daa4f79ea08a0ad8f0fa0c1dad7a157c213e5c80 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Thu, 6 Aug 2026 16:30:28 +0200 Subject: [PATCH] fix: author prefetch did not work (moved away from excessive effect() usage, implemented additional methods to avoid missmatches) --- .../services/trend-data.service.ts | 223 +++++++------ .../uni-trend-parent.component.ts | 57 ++-- .../university-ranking/utils/trend.utils.ts | 44 ++- .../src/app/resolvers/uni-trend.resolver.ts | 312 ++++++++++-------- 4 files changed, 358 insertions(+), 278 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 626102f3..55e47938 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 @@ -1,4 +1,6 @@ import { Injectable, inject, signal } from '@angular/core'; +import { Subject, of } from 'rxjs'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { UniversityRankingsService, PersonsService, @@ -42,6 +44,124 @@ export class TrendDataService { private readonly cacheMap = new Map(); + // RxJS Subjects for cancellation of pending requests + private readonly topTopicsSubject = new Subject<{ + cleanId: string; + entityType: string; + startYear: number; + endYear: number; + searchType: string; + }>(); + + private readonly instSuggestionsSubject = new Subject<{ + topic: string; + countryFilter?: string; + regionFilter?: string; + }>(); + + private readonly recAuthorsSubject = new Subject<{ + topic: string; + primaryInstId: string; + }>(); + + constructor() { + this.topTopicsSubject + .pipe( + switchMap((params) => { + if (!params.cleanId || params.searchType === 'all') { + this.isTopTopicsLoading.set(false); + this.topTopicsData.set([]); + return of([]); + } + return this.apiService + .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + params.cleanId, + params.entityType, + params.startYear, + params.endYear, + params.searchType, + ) + .pipe( + map((res) => + (res.items || []).map((item) => ({ + value: item.count, + name: item.name, + })), + ), + catchError((err) => { + console.error('Failed to load top topics:', err); + this.topTopicsError.set(true); + return of([]); + }), + ); + }), + ) + .subscribe((data) => { + this.topTopicsData.set(data); + this.isTopTopicsLoading.set(false); + }); + + this.instSuggestionsSubject + .pipe( + switchMap((params) => + this.apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + params.topic, + params.regionFilter, + params.countryFilter, + 6, + ) + .pipe(catchError(() => of([]))), + ), + ) + .subscribe((data: any) => { + this.topSuggestions.set(data || []); + this.isSuggestionsLoading.set(false); + }); + + this.recAuthorsSubject + .pipe( + switchMap((params) => { + const cleanInst = cleanEntityId(params.primaryInstId) || 'I62318514'; + return this.personsApiService + .searchPersonsList( + undefined, + cleanInst, + 'cited_by_count', + 'desc', + [params.topic], + 1, + 6, + undefined, + ) + .pipe( + switchMap((res) => { + if (res.results && res.results.length > 0) { + return of(res.results); + } + return this.personsApiService + .searchPersonsList( + undefined, + undefined, + 'cited_by_count', + 'desc', + [params.topic], + 1, + 6, + undefined, + ) + .pipe(map((gRes) => gRes.results || [])); + }), + catchError(() => of([])), + ); + }), + ) + .subscribe((authors) => { + this.recommendedAuthors.set(authors); + this.isSuggestionsLoading.set(false); + }); + } + private getCacheKey(params: TrendRequestParams): string { return JSON.stringify({ searchType: params.searchType, @@ -93,38 +213,19 @@ export class TrendDataService { ): void { if (!entityId || searchType === 'all') { this.topTopicsData.set([]); + this.isTopTopicsLoading.set(false); 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([]); - }, - }); + this.topTopicsSubject.next({ + cleanId: cleanEntityId(entityId), + entityType, + startYear, + endYear, + searchType, + }); } /** @@ -136,24 +237,7 @@ export class TrendDataService { 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); - }, - }); + this.instSuggestionsSubject.next({ topic, countryFilter, regionFilter }); } /** @@ -161,53 +245,6 @@ export class TrendDataService { */ 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); - }, - }); + this.recAuthorsSubject.next({ topic, primaryInstId }); } } 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 f9dfc8e2..ef57e6dc 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 @@ -557,49 +557,33 @@ export class UniTrendParentComponent implements OnInit { } isTopicEmpty(topic: string): boolean { - const allSeries = this.rawTrendResponse()?.series || []; + const allSeries = + this.trendResponse()?.series || this.rawTrendResponse()?.series || []; if (allSeries.length === 0) return true; const series = this.selectedSearchType() === 'news' ? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic) : allSeries; - if (series.length === 0) return true; - - const mapped = this.getMappedTopic(topic); - const startYr = this.startYear(); - const endYr = this.endYear(); - const cId = cleanEntityId(topic); - - 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; + return isTopicEmptyForSeries( + topic, + series, + this.startYear(), + this.endYear(), + (t) => this.getMappedTopic(t), + ); } findFirstNonEmptyTopic(topics: string[]): string { + const allSeries = + this.trendResponse()?.series || this.rawTrendResponse()?.series || []; if (!topics || topics.length === 0) return ''; - for (const t of topics) { - if (!this.isTopicEmpty(t)) { - return t; - } - } - return topics[0]; + return findFirstNonEmptyTopic( + topics, + allSeries, + this.startYear(), + this.endYear(), + (t) => this.getMappedTopic(t), + ); } isVisible(id: string): boolean { @@ -903,6 +887,11 @@ export class UniTrendParentComponent implements OnInit { } if (resolved.authors && resolved.authors.length > 0) { this.comparisonAuthors.set(resolved.authors); + const currentUrlAuthors = + this.route.snapshot.queryParamMap.getAll('authors'); + if (currentUrlAuthors.length === 0 && type === 'authors') { + this.updateUrlParams(); + } } if (resolved.treemapNode !== undefined) { 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 d8e720ae..b0a30958 100644 --- a/webapp/src/app/modules/university-ranking/utils/trend.utils.ts +++ b/webapp/src/app/modules/university-ranking/utils/trend.utils.ts @@ -26,15 +26,42 @@ export function isTopicEmptyForSeries( seriesList: TrendSeries[], startYr: number, endYr: number, + getMappedTopicFn?: (topic: string) => string, ): boolean { if (!seriesList || seriesList.length === 0) return true; + const mapped = getMappedTopicFn ? getMappedTopicFn(topicName) : topicName; + const cleanId = cleanEntityId(topicName); + const cleanMappedId = cleanEntityId(mapped); + const topicLower = topicName.toLowerCase().trim(); + const mappedLower = mapped.toLowerCase().trim(); + 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; + if (!s.topic_data) continue; + const entries = Object.entries(s.topic_data); + + for (const [key, topicItems] of entries) { + if (!topicItems || topicItems.length === 0) continue; + + const keyLower = key.toLowerCase().trim(); + const keyClean = cleanEntityId(key); + const revMapped = getMappedTopicFn + ? getMappedTopicFn(key).toLowerCase().trim() + : ''; + + const isMatch = + keyLower === topicLower || + keyLower === mappedLower || + (cleanId && keyClean === cleanId) || + (cleanMappedId && keyClean === cleanMappedId) || + (revMapped && (revMapped === topicLower || revMapped === mappedLower)); + + if (isMatch) { + 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; } @@ -47,10 +74,13 @@ export function findFirstNonEmptyTopic( seriesList: TrendSeries[], startYr: number, endYr: number, + getMappedTopicFn?: (topic: string) => string, ): string { if (!topics || topics.length === 0) return ''; for (const t of topics) { - if (!isTopicEmptyForSeries(t, seriesList, startYr, endYr)) { + if ( + !isTopicEmptyForSeries(t, seriesList, startYr, endYr, getMappedTopicFn) + ) { return t; } } diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index 60e54789..887f1bae 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -1,6 +1,6 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { catchError, of, Observable, map, forkJoin } from 'rxjs'; +import { catchError, of, Observable, map, forkJoin, switchMap } from 'rxjs'; import { TrendResponse, UniversityRankingsService, @@ -142,13 +142,6 @@ export const uniTrendResolver: ResolveFn = ( return { id: cleanId, name: parts[1] || parts[0] }; }); - const instIds = - parsedInstitutions.length > 0 - ? parsedInstitutions.map((i) => i.id) - : [primaryInstId]; - 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 }); @@ -159,148 +152,179 @@ export const uniTrendResolver: ResolveFn = ( const regionFilter = parsedRegions.length > 0 ? parsedRegions[0].id : undefined; - const currentParams: TrendRequestParams = { - topics, - keywords, - fuzzy, - institutions: instIds, - countries: countryIds, - regions: regionIds, - authors: authorIds, - searchType, + const fetchTrendAndSuggestions = ( + authors: CompareItem[], + ): Observable => { + const instIds = + parsedInstitutions.length > 0 + ? parsedInstitutions.map((i) => i.id) + : [primaryInstId]; + const countryIds = parsedCountries.map((c) => c.id); + const regionIds = parsedRegions.map((r) => r.id); + const authorIds = authors.map((a) => a.id); + + const currentParams: TrendRequestParams = { + topics, + keywords, + fuzzy, + institutions: instIds, + countries: countryIds, + regions: regionIds, + authors: authorIds, + searchType, + }; + + let trendObs$: Observable; + if (trendDataService.canReuseCache(currentParams)) { + trendObs$ = of(trendDataService.getCachedResponse(currentParams)); + } else { + trendObs$ = apiService + .getTrendApiInseServiceUniversityRankingsTrendGet( + topics, + keywords, + fuzzy, + instIds, + countryIds, + regionIds, + authorIds, + searchType as any, + ) + .pipe( + map((res) => { + trendDataService.updateCache(res, currentParams); + return res; + }), + 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); + }), + ); + } + + const topInstObs$ = + searchType !== 'authors' + ? apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + primaryTopic, + regionFilter, + countryFilter, + 6, + ) + .pipe(catchError(() => of([]))) + : of([]); + + const recAuthorsObs$ = + searchType === 'authors' && personsService + ? personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, + ) + .pipe( + map((res: any) => res.results || []), + catchError(() => of([])), + ) + : of([]); + + return forkJoin({ + trendResponse: trendObs$, + topSuggestions: topInstObs$, + recommendedAuthors: recAuthorsObs$, + }).pipe( + map(({ trendResponse, topSuggestions, recommendedAuthors }) => { + let initialActiveTopic = primaryTopic; + if ( + trendResponse?.series && + trendResponse.series.length > 0 && + topics.length > 0 + ) { + const nonEmptyTopic = topics.find((t) => + trendResponse.series.some((s) => { + if (!s.topic_data) return false; + const tLower = t.toLowerCase().trim(); + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === tLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === tLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; + const total = yearlyList.reduce( + (sum, item) => sum + (item.raw || 0), + 0, + ); + return total > 0; + }), + ); + if (nonEmptyTopic) { + initialActiveTopic = nonEmptyTopic; + } + } + + return { + trendResponse, + searchType, + topics, + keywords, + fuzzy, + institutions: parsedInstitutions, + countries: parsedCountries, + regions: parsedRegions, + authors, + initialActiveTopic, + topSuggestions: topSuggestions as any[], + recommendedAuthors: recommendedAuthors as any[], + treemapNode, + }; + }), + ); }; - // Check exact parameter keyed cache - let trendObs$: Observable; - if (trendDataService.canReuseCache(currentParams)) { - trendObs$ = of(trendDataService.getCachedResponse(currentParams)); - } else { - trendObs$ = apiService - .getTrendApiInseServiceUniversityRankingsTrendGet( - topics, - keywords, - fuzzy, - instIds, - countryIds, - regionIds, - authorIds, - searchType as any, + if ( + searchType === 'authors' && + parsedAuthors.length === 0 && + personsService + ) { + return personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, ) .pipe( - map((res) => { - trendDataService.updateCache(res, currentParams); - return res; - }), - 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); + map((res: any) => res.results || []), + catchError(() => of([])), + switchMap((recAuthors) => { + const defaultAuthors: CompareItem[] = recAuthors + .slice(0, 3) + .map((author: any) => ({ + id: cleanEntityId(author.id), + name: author.display_name || 'Unbekannt', + })); + return fetchTrendAndSuggestions(defaultAuthors); }), ); } - const topInstObs$ = - searchType !== 'authors' - ? apiService - .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - primaryTopic, - regionFilter, - countryFilter, - 6, - ) - .pipe(catchError(() => of([]))) - : of([]); - - const recAuthorsObs$ = - searchType === 'authors' && personsService - ? personsService - .searchPersonsList( - undefined, - primaryInstId, - 'cited_by_count', - 'desc', - [primaryTopic], - 1, - 6, - undefined, - ) - .pipe( - map((res: any) => res.results || []), - catchError(() => of([])), - ) - : of([]); - - return forkJoin({ - trendResponse: trendObs$, - topSuggestions: topInstObs$, - recommendedAuthors: recAuthorsObs$, - }).pipe( - map(({ trendResponse, topSuggestions, recommendedAuthors }) => { - let initialActiveTopic = primaryTopic; - if ( - trendResponse?.series && - trendResponse.series.length > 0 && - topics.length > 0 - ) { - const nonEmptyTopic = topics.find((t) => - trendResponse.series.some((s) => { - if (!s.topic_data) return false; - const tLower = t.toLowerCase().trim(); - const matchingKey = Object.keys(s.topic_data).find((key) => { - const kLower = key.toLowerCase().trim(); - return ( - kLower === tLower || - (kLower.startsWith('news_topic_') && - kLower.slice('news_topic_'.length) === tLower) - ); - }); - if (!matchingKey) return false; - const yearlyList = s.topic_data[matchingKey]; - if (!yearlyList || !Array.isArray(yearlyList)) return false; - const total = yearlyList.reduce( - (sum, item) => sum + (item.raw || 0), - 0, - ); - return total > 0; - }), - ); - if (nonEmptyTopic) { - initialActiveTopic = nonEmptyTopic; - } - } - - if ( - searchType === 'authors' && - parsedAuthors.length === 0 && - recommendedAuthors?.length - ) { - recommendedAuthors.slice(0, 3).forEach((author: any) => { - parsedAuthors.push({ - id: cleanEntityId(author.id), - name: author.display_name || 'Unbekannt', - }); - }); - } - - return { - trendResponse, - searchType, - topics, - keywords, - fuzzy, - institutions: parsedInstitutions, - countries: parsedCountries, - regions: parsedRegions, - authors: parsedAuthors, - initialActiveTopic, - topSuggestions: topSuggestions as any[], - recommendedAuthors: recommendedAuthors as any[], - treemapNode, - }; - }), - ); + return fetchTrendAndSuggestions(parsedAuthors); };