From dc573433d98ed70700ec09d9b3fee29e560dfa39 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Tue, 16 Jun 2026 16:27:31 +0200 Subject: [PATCH 01/53] Log career metrics runtime --- service/src/main/inse/persons/logic.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 76db43c7..f142ee37 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -389,7 +389,13 @@ def get_person_by_id( raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") author = util.get_persons_data(hit) + start_time = time.time() career_metrics = get_career_metrics_for_author(author_id) + elapsed_time = time.time() - start_time + + logger.info( + f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds" + ) custom_author = CustomAuthor( **author.model_dump(), From 6a6e07a0dc213c110d66a98d9e6b30a1e890afdf Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Thu, 18 Jun 2026 22:10:41 +0200 Subject: [PATCH 02/53] display career stage in profile --- service/src/main/inse/persons/logic.py | 6 ++--- .../app/modules/person/person.component.html | 12 +++++++++ .../app/modules/person/person.component.scss | 27 +++++++++++++++++++ .../app/modules/person/person.component.ts | 25 ++++++++++++----- webapp/src/app/resolvers/person.resolver.ts | 22 ++++++--------- 5 files changed, 68 insertions(+), 24 deletions(-) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index f142ee37..609b8b88 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -371,15 +371,13 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s def get_person_by_id( author_id: str, include: Optional[str] = None ) -> CustomAuthorsListResponse: - body = { - "_source": include.split(",") if include else True, - } + source = include.split(",") if include else None try: hit = elasticsearch.get( index="openalex-authors", - body=body, doc_id=author_id, + source=source, ) except NotFoundError: raise HTTPException( diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index a0b50703..e58bd84d 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -29,6 +29,18 @@ } } + @if (displayCareerStage()) { +
+ Career Stage: + + {{ displayCareerStage() }} + +
+ }
diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index be93f021..e232d508 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -85,6 +85,33 @@ font-size: 13px; } +.career-stage-line { + display: flex; + align-items: center; + gap: 8px; + color: var(--sg-text-muted); + font-size: 13px; +} + +.career-stage-label { + color: var(--sg-text-muted); +} + +.career-stage-chip { + display: inline-flex; + align-items: center; + min-height: 24px; + padding: 2px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: var(--sg-surface-muted); + color: var(--sg-primary); + font-size: 13px; + font-weight: 600; + line-height: 1.2; + cursor: help; +} + .profile-contact { display: grid; gap: 16px; diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 724e9882..0f756693 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -7,6 +7,7 @@ import { import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatTabsModule } from '@angular/material/tabs'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { ActivatedRoute, ResolveEnd, @@ -19,7 +20,7 @@ import { import { of, switchMap, finalize, map, catchError } from 'rxjs'; import { PersonInterestingComponent } from '../person-interesting/person-interesting.component'; -import { PersonsService, WorksService } from '../../api'; +import { WorksService } from '../../api'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PersonBioResolved } from '../../resolvers/person-bio.resolver'; @@ -28,6 +29,7 @@ import { PersonBioResolved } from '../../resolvers/person-bio.resolver'; imports: [ MatIconModule, MatTabsModule, + MatTooltipModule, PersonInterestingComponent, RouterOutlet, RouterModule, @@ -41,7 +43,6 @@ export class PersonComponent { private readonly router = inject(Router); private readonly activatedRoute = inject(ActivatedRoute); - private readonly personsApi = inject(PersonsService); private readonly worksApi = inject(WorksService); private readonly destroyRef = inject(DestroyRef); @@ -62,9 +63,9 @@ export class PersonComponent { const event = this.routerEvents(); if ( - !(event instanceof RouterEvent) || // not a router event - !this.isResolverEvent(event) || // not a resolver event - !this.isNetworkRouterEvent(event) // not navigating to network route + !(event instanceof RouterEvent) || + !this.isResolverEvent(event) || + !this.isNetworkRouterEvent(event) ) { return false; } @@ -84,7 +85,6 @@ export class PersonComponent { return event.url.startsWith(`/person/${this.authorId()}/network`); } - // loading states readonly isPersonLoading = signal(false); readonly isBioLoading = signal(false); @@ -111,6 +111,7 @@ export class PersonComponent { ), { initialValue: null }, ); + readonly displayName = computed( () => this.person()?.display_name ?? 'Unbekannte Person', ); @@ -142,6 +143,17 @@ export class PersonComponent { readonly h_index = computed( () => this.person()?.summary_stats?.h_index ?? null, ); + readonly displayCareerStage = computed(() => { + const stage = this.person()?.career_metrics?.career_stage; + + if (!stage || stage === 'unknown') { + return null; + } + + return stage; + }); + readonly careerStageTooltip = + 'Dies ist eine Einschätzung zur Karrierephase, die ausschließlich auf OpenAlex-Publikationsdaten basiert. Es ist kein offizieller akademischer Status.'; readonly orcid = computed(() => { const rawOrcid = this.getId('orcid'); if (!rawOrcid) { @@ -168,6 +180,7 @@ export class PersonComponent { ), { initialValue: [] }, ); + links = [ { label: 'Übersicht', path: 'overview', disabled: false }, { diff --git a/webapp/src/app/resolvers/person.resolver.ts b/webapp/src/app/resolvers/person.resolver.ts index a20198f2..64bde7da 100644 --- a/webapp/src/app/resolvers/person.resolver.ts +++ b/webapp/src/app/resolvers/person.resolver.ts @@ -1,23 +1,17 @@ import { ResolveFn } from '@angular/router'; import { inject } from '@angular/core'; -import { AuthorsListResponse, PersonsService } from '../api'; +import { CustomAuthorsListResponse, PersonsService } from '../api'; -export const personResolver: ResolveFn = ( +export const personResolver: ResolveFn = ( route, state, ) => { - const parseQueryParamArray = (val: any): string[] => { - if (!val) return []; - if (Array.isArray(val)) return val; - return [val]; - }; - const PERSON_INCLUDE_TAGS = - 'topics_full,topic_share,summary_stats,ids,last_known_institutions,' + - 'sources,counts_by_year,works_api_url,dates,cited_by_count_boost'; - const params = route.paramMap; - - const query = params.get('id') || undefined; + const authorId = route.paramMap.get('id'); const personsService = inject(PersonsService); - return personsService.searchPersons(query, undefined, PERSON_INCLUDE_TAGS); + if (!authorId) { + return { results: [] }; + } + + return personsService.getPersonByID(authorId); }; From 6e3c5107f1bf551e17e1fdc9e0cc5c262ff8d4b0 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Thu, 18 Jun 2026 23:09:32 +0200 Subject: [PATCH 03/53] show career stage on person cards --- service/src/main/inse/persons/logic.py | 11 +++++++ .../person-card/person-card.component.html | 12 +++++++ .../person-card/person-card.component.scss | 33 +++++++++++++++++++ .../person-card/person-card.component.ts | 22 ++++++++++++- .../src/app/resolvers/person-list.resolver.ts | 2 +- 5 files changed, 78 insertions(+), 2 deletions(-) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 609b8b88..63c4d128 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -680,11 +680,22 @@ def advanced_search_persons( hits = response_dict.get("hits", {}).get("hits", []) total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) + include_career_metrics = include is None or "career_metrics" in include results = [] for hit in hits: raw_data = util.get_persons_data(hit) custom_author = _enrich_author_data(raw_data) if custom_author: + if include_career_metrics: + start_time = time.time() + custom_author.career_metrics = get_career_metrics_for_author( + custom_author.id + ) + elapsed_time = time.time() - start_time + logger.info( + f"Career metrics calculation for author {custom_author.id} took " + f"{elapsed_time:.2f} seconds" + ) results.append(custom_author) return CustomAuthorsListResponse( diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 43698f60..59e1fc6b 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -33,6 +33,18 @@

{{ getHIndexString() }}

+ @if (!loading && getCareerStage(); as careerStage) { +
+ Career Stage: + + {{ careerStage }} + +
+ }
diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index f3a53722..8aebf59a 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -193,6 +193,39 @@ white-space: nowrap; } +.career-stage-line { + display: flex; + align-items: center; + gap: 6px; + margin-top: 6px; + color: var(--sg-text-muted); + font-size: 10px; + min-height: 18px; +} + +.career-stage-label { + flex-shrink: 0; +} + +.career-stage-chip { + display: inline-flex; + align-items: center; + min-width: 0; + max-width: 100%; + padding: 2px 8px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: var(--sg-surface-muted); + color: var(--sg-primary); + font-size: 10px; + font-weight: 600; + line-height: 1.2; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + cursor: help; +} + .card-body { padding: 16px; flex-grow: 1; diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 89f0440c..c7815275 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -2,12 +2,19 @@ import { Component, Input, Output, EventEmitter } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; import { SkTextDirective } from '../../custom-directives/sk-text.directive'; @Component({ selector: 'app-person-card', standalone: true, - imports: [CommonModule, RouterLink, MatIconModule, SkTextDirective], + imports: [ + CommonModule, + RouterLink, + MatIconModule, + MatTooltipModule, + SkTextDirective, + ], templateUrl: './person-card.component.html', styleUrl: './person-card.component.scss', }) @@ -94,6 +101,19 @@ export class PersonCardComponent { return ''; } + getCareerStage(): string | null { + const stage = this.person.career_metrics?.career_stage; + + if (!stage || stage === 'unknown') { + return null; + } + + return stage; + } + + readonly careerStageTooltip = + 'Dies ist eine Einschätzung zur Karrierephase, die ausschließlich auf OpenAlex-Publikationsdaten basiert. Es ist kein offizieller akademischer Status.'; + toggleBookmark(): void { this.bookmarkToggle.emit(this.person); } diff --git a/webapp/src/app/resolvers/person-list.resolver.ts b/webapp/src/app/resolvers/person-list.resolver.ts index 8e4b824c..926dd58c 100644 --- a/webapp/src/app/resolvers/person-list.resolver.ts +++ b/webapp/src/app/resolvers/person-list.resolver.ts @@ -12,7 +12,7 @@ export const personListResolver: ResolveFn = ( return [val]; }; const defaultIncludes = - 'display_name,works_count,cited_by_count,summary_stats,topics,orcid,relevance_rating,last_known_institutions,affiliations'; + 'display_name,works_count,cited_by_count,summary_stats,topics,orcid,relevance_rating,last_known_institutions,affiliations,career_metrics'; const params = route.queryParamMap; const query = params.get('query') || undefined; From c62f284866c880b7bfd3fbf663ec4e39b07a54ec Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 19 Jun 2026 13:35:17 +0200 Subject: [PATCH 04/53] batch career metrics for search results --- service/src/main/inse/persons/logic.py | 137 +++++++++++++++++++++++-- 1 file changed, 126 insertions(+), 11 deletions(-) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 63c4d128..273b649b 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -188,8 +188,17 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics +def _get_openalex_author_url(author_id: str) -> str: + author_id = author_id.strip() + + if author_id.startswith("https://openalex.org/"): + return author_id + + return f"https://openalex.org/{author_id}" + + def _get_publication_years_for_author(author_id: str) -> list[int]: - author_url = f"https://openalex.org/{author_id.strip()}" + author_url = _get_openalex_author_url(author_id) body = { "size": 0, @@ -237,6 +246,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: return publication_years + def _classify_career_stage(active_years: int) -> str: if active_years <= 0: return "unknown" @@ -297,11 +307,108 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: ) +def _get_publication_years_for_authors(author_ids: list[str]) -> dict[str, list[int]]: + author_ids = list(dict.fromkeys(author_id for author_id in author_ids if author_id)) + + if not author_ids: + return {} + + author_url_by_id = { + author_id: _get_openalex_author_url(author_id) for author_id in author_ids + } + + body = { + "size": 0, + "query": { + "nested": { + "path": "authorships", + "query": { + "terms": { + "authorships.author.id": list(author_url_by_id.values()) + }, + }, + }, + }, + "aggs": { + "authors": { + "filters": { + "filters": { + author_id: { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": author_url + }, + }, + }, + } + for author_id, author_url in author_url_by_id.items() + }, + }, + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 1000, + }, + }, + }, + }, + }, + } + + try: + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + except httpx.TimeoutException: + logger.warning( + "Batch career metrics Elasticsearch request timed out. " + "Returning empty career metrics for this search page." + ) + return {author_id: [] for author_id in author_ids} + + publication_years_by_author = {author_id: [] for author_id in author_ids} + author_buckets = ( + response.get("aggregations", {}) + .get("authors", {}) + .get("buckets", {}) + ) + + for author_id, author_bucket in author_buckets.items(): + year_buckets = ( + author_bucket.get("publication_years", {}) + .get("buckets", []) + ) + + for year_bucket in year_buckets: + year = year_bucket.get("key") + count = year_bucket.get("doc_count", 0) + + if isinstance(year, int): + publication_years_by_author[author_id].extend([year] * count) + + return publication_years_by_author + + def get_career_metrics_for_author(author_id: str) -> CareerMetrics: publication_years = _get_publication_years_for_author(author_id) return _compute_career_metrics(publication_years) +def get_career_metrics_for_authors(author_ids: list[str]) -> dict[str, CareerMetrics]: + publication_years_by_author = _get_publication_years_for_authors(author_ids) + + return { + author_id: _compute_career_metrics( + publication_years_by_author.get(author_id, []) + ) + for author_id in author_ids + } + + def _build_papers(works: list) -> list: papers = [] @@ -686,18 +793,26 @@ def advanced_search_persons( raw_data = util.get_persons_data(hit) custom_author = _enrich_author_data(raw_data) if custom_author: - if include_career_metrics: - start_time = time.time() - custom_author.career_metrics = get_career_metrics_for_author( - custom_author.id - ) - elapsed_time = time.time() - start_time - logger.info( - f"Career metrics calculation for author {custom_author.id} took " - f"{elapsed_time:.2f} seconds" - ) results.append(custom_author) + if include_career_metrics and results: + author_ids = [custom_author.id for custom_author in results if custom_author.id] + + start_time = time.time() + career_metrics_by_author = get_career_metrics_for_authors(author_ids) + elapsed_time = time.time() - start_time + + logger.info( + f"Batch career metrics calculation for {len(author_ids)} authors took " + f"{elapsed_time:.2f} seconds" + ) + + for custom_author in results: + if custom_author.id: + custom_author.career_metrics = career_metrics_by_author.get( + custom_author.id, CareerMetrics() + ) + return CustomAuthorsListResponse( results=results, meta=Meta(count=total_count, page=page, per_page=page_size) ) From eba2b73c6b4276578d08b785ba9ae27e77a7ca5a Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 19 Jun 2026 14:03:41 +0200 Subject: [PATCH 05/53] update career stage tooltip --- .../person-card/person-card.component.html | 5 ++-- .../person-card/person-card.component.ts | 18 +++++++++++++-- .../app/modules/person/person.component.html | 5 ++-- .../app/modules/person/person.component.ts | 23 +++++++++++++++++-- webapp/src/styles.scss | 8 ++++++- 5 files changed, 50 insertions(+), 9 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 59e1fc6b..1ce09684 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -38,8 +38,9 @@ Career Stage: {{ careerStage }} diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index c7815275..c9c9fa48 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -111,8 +111,22 @@ export class PersonCardComponent { return stage; } - readonly careerStageTooltip = - 'Dies ist eine Einschätzung zur Karrierephase, die ausschließlich auf OpenAlex-Publikationsdaten basiert. Es ist kein offizieller akademischer Status.'; + getCareerStageTooltip(careerStage: string): string { + const activeYears = this.person.career_metrics?.active_years ?? '-'; + + return [ + `Aktuell: ${careerStage}`, + `Aktive Publikationsjahre: ${activeYears}`, + '', + 'Einteilung:', + 'Early Researcher: 1\u20134 aktive Publikationsjahre', + 'Emerging Researcher: 5\u201310 aktive Publikationsjahre', + 'Established Researcher: 11\u201320 aktive Publikationsjahre', + 'Senior Researcher: 20+ aktive Publikationsjahre', + '', + 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', + ].join('\n'); + } toggleBookmark(): void { this.bookmarkToggle.emit(this.person); diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index e58bd84d..0dea7f11 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -34,8 +34,9 @@ Career Stage: {{ displayCareerStage() }} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 55afbb2a..bd8c5fd2 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -152,8 +152,27 @@ export class PersonComponent { return stage; }); - readonly careerStageTooltip = - 'Dies ist eine Einschätzung zur Karrierephase, die ausschließlich auf OpenAlex-Publikationsdaten basiert. Es ist kein offizieller akademischer Status.'; + readonly careerStageTooltip = computed(() => { + const stage = this.displayCareerStage(); + if (!stage) { + return ''; + } + + const activeYears = this.person()?.career_metrics?.active_years ?? '-'; + + return [ + `Aktuell: ${stage}`, + `Aktive Publikationsjahre: ${activeYears}`, + '', + 'Einteilung:', + 'Early Researcher: 1\u20134 aktive Publikationsjahre', + 'Emerging Researcher: 5\u201310 aktive Publikationsjahre', + 'Established Researcher: 11\u201320 aktive Publikationsjahre', + 'Senior Researcher: 20+ aktive Publikationsjahre', + '', + 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', + ].join('\n'); + }); readonly orcid = computed(() => { const rawOrcid = this.getId('orcid'); if (!rawOrcid) { diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index b69df54f..d2edeee7 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -218,4 +218,10 @@ h3 { .cdk-overlay-pane .mat-mdc-option:hover, .cdk-overlay-pane .mat-mdc-option.mdc-list-item--focused { background: rgba(0, 0, 0, 0.04); -} \ No newline at end of file +} + +.career-stage-tooltip, +.career-stage-tooltip .mdc-tooltip__surface { + max-width: 360px; + white-space: pre-line; +} From 5def7ac5f13d964f4f7aa42939bfe1e6593f55b6 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 19 Jun 2026 14:29:50 +0200 Subject: [PATCH 06/53] fix(persons): include required detail fields in resolver --- webapp/src/app/resolvers/person.resolver.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/resolvers/person.resolver.ts b/webapp/src/app/resolvers/person.resolver.ts index 1dc145ac..b8175a50 100644 --- a/webapp/src/app/resolvers/person.resolver.ts +++ b/webapp/src/app/resolvers/person.resolver.ts @@ -7,8 +7,10 @@ export const personResolver: ResolveFn = ( state, ) => { const PERSON_INCLUDE_TAGS = - 'topics_full,topic_share,summary_stats,ids,last_known_institutions,' + - 'sources,counts_by_year,works_api_url,dates,cited_by_count_boost,career_metrics'; + 'display_name,works_count,cited_by_count,summary_stats,ids,' + + 'last_known_institutions,affiliations,topics,orcid,' + + 'topics_full,topic_share,sources,counts_by_year,works_api_url,' + + 'dates,cited_by_count_boost,career_metrics'; const authorId = route.paramMap.get('id') || undefined; const personsService = inject(PersonsService); From 123db12ac4e100fdbd98e00d75d21a9aa7be0f2e Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 19 Jun 2026 14:46:42 +0200 Subject: [PATCH 07/53] Update career stage backend thresholds --- service/src/main/inse/persons/logic.py | 141 +++---------------------- 1 file changed, 13 insertions(+), 128 deletions(-) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 273b649b..ac94a469 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -188,17 +188,8 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics -def _get_openalex_author_url(author_id: str) -> str: - author_id = author_id.strip() - - if author_id.startswith("https://openalex.org/"): - return author_id - - return f"https://openalex.org/{author_id}" - - def _get_publication_years_for_author(author_id: str) -> list[int]: - author_url = _get_openalex_author_url(author_id) + author_url = f"https://openalex.org/{author_id.strip()}" body = { "size": 0, @@ -246,7 +237,6 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: return publication_years - def _classify_career_stage(active_years: int) -> str: if active_years <= 0: return "unknown" @@ -254,10 +244,10 @@ def _classify_career_stage(active_years: int) -> str: if active_years <= 4: return "Early Researcher" - if active_years <= 10: + if active_years <= 9: return "Emerging Researcher" - if active_years <= 20: + if active_years <= 14: return "Established Researcher" return "Senior Researcher" @@ -307,108 +297,11 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: ) -def _get_publication_years_for_authors(author_ids: list[str]) -> dict[str, list[int]]: - author_ids = list(dict.fromkeys(author_id for author_id in author_ids if author_id)) - - if not author_ids: - return {} - - author_url_by_id = { - author_id: _get_openalex_author_url(author_id) for author_id in author_ids - } - - body = { - "size": 0, - "query": { - "nested": { - "path": "authorships", - "query": { - "terms": { - "authorships.author.id": list(author_url_by_id.values()) - }, - }, - }, - }, - "aggs": { - "authors": { - "filters": { - "filters": { - author_id: { - "nested": { - "path": "authorships", - "query": { - "term": { - "authorships.author.id": author_url - }, - }, - }, - } - for author_id, author_url in author_url_by_id.items() - }, - }, - "aggs": { - "publication_years": { - "terms": { - "field": "publication_year", - "size": 1000, - }, - }, - }, - }, - }, - } - - try: - response = elasticsearch.search( - index=config.settings.openalex_works_search_index, - body=body, - ) - except httpx.TimeoutException: - logger.warning( - "Batch career metrics Elasticsearch request timed out. " - "Returning empty career metrics for this search page." - ) - return {author_id: [] for author_id in author_ids} - - publication_years_by_author = {author_id: [] for author_id in author_ids} - author_buckets = ( - response.get("aggregations", {}) - .get("authors", {}) - .get("buckets", {}) - ) - - for author_id, author_bucket in author_buckets.items(): - year_buckets = ( - author_bucket.get("publication_years", {}) - .get("buckets", []) - ) - - for year_bucket in year_buckets: - year = year_bucket.get("key") - count = year_bucket.get("doc_count", 0) - - if isinstance(year, int): - publication_years_by_author[author_id].extend([year] * count) - - return publication_years_by_author - - def get_career_metrics_for_author(author_id: str) -> CareerMetrics: publication_years = _get_publication_years_for_author(author_id) return _compute_career_metrics(publication_years) -def get_career_metrics_for_authors(author_ids: list[str]) -> dict[str, CareerMetrics]: - publication_years_by_author = _get_publication_years_for_authors(author_ids) - - return { - author_id: _compute_career_metrics( - publication_years_by_author.get(author_id, []) - ) - for author_id in author_ids - } - - def _build_papers(works: list) -> list: papers = [] @@ -793,25 +686,17 @@ def advanced_search_persons( raw_data = util.get_persons_data(hit) custom_author = _enrich_author_data(raw_data) if custom_author: - results.append(custom_author) - - if include_career_metrics and results: - author_ids = [custom_author.id for custom_author in results if custom_author.id] - - start_time = time.time() - career_metrics_by_author = get_career_metrics_for_authors(author_ids) - elapsed_time = time.time() - start_time - - logger.info( - f"Batch career metrics calculation for {len(author_ids)} authors took " - f"{elapsed_time:.2f} seconds" - ) - - for custom_author in results: - if custom_author.id: - custom_author.career_metrics = career_metrics_by_author.get( - custom_author.id, CareerMetrics() + if include_career_metrics: + start_time = time.time() + custom_author.career_metrics = get_career_metrics_for_author( + custom_author.id ) + elapsed_time = time.time() - start_time + logger.info( + f"Career metrics calculation for author {custom_author.id} took " + f"{elapsed_time:.2f} seconds" + ) + results.append(custom_author) return CustomAuthorsListResponse( results=results, meta=Meta(count=total_count, page=page, per_page=page_size) From ae04eae6e65e849a6c6d18330db7466c73f38280 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 19 Jun 2026 14:57:58 +0200 Subject: [PATCH 08/53] update career stage tooltip boundaries --- webapp/src/app/modules/person-card/person-card.component.ts | 6 +++--- webapp/src/app/modules/person/person.component.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index c9c9fa48..48e4ed9a 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -120,9 +120,9 @@ export class PersonCardComponent { '', 'Einteilung:', 'Early Researcher: 1\u20134 aktive Publikationsjahre', - 'Emerging Researcher: 5\u201310 aktive Publikationsjahre', - 'Established Researcher: 11\u201320 aktive Publikationsjahre', - 'Senior Researcher: 20+ aktive Publikationsjahre', + 'Emerging Researcher: 5\u20139 aktive Publikationsjahre', + 'Established Researcher: 10\u201314 aktive Publikationsjahre', + 'Senior Researcher: ab 15 aktiven Publikationsjahre', '', 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', ].join('\n'); diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index bd8c5fd2..3bd44f29 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -166,9 +166,9 @@ export class PersonComponent { '', 'Einteilung:', 'Early Researcher: 1\u20134 aktive Publikationsjahre', - 'Emerging Researcher: 5\u201310 aktive Publikationsjahre', - 'Established Researcher: 11\u201320 aktive Publikationsjahre', - 'Senior Researcher: 20+ aktive Publikationsjahre', + 'Emerging Researcher: 5\u20139 aktive Publikationsjahre', + 'Established Researcher: 10\u201314 aktive Publikationsjahre', + 'Senior Researcher: ab 15 aktiven Publikationsjahre', '', 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', ].join('\n'); From 79854123b6d63dbdca51788827b6c0afae07b3e9 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 19 Jun 2026 15:01:19 +0200 Subject: [PATCH 09/53] correct career stage tooltip wording --- webapp/src/app/modules/person-card/person-card.component.ts | 2 +- webapp/src/app/modules/person/person.component.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 48e4ed9a..2844a6c3 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -122,7 +122,7 @@ export class PersonCardComponent { 'Early Researcher: 1\u20134 aktive Publikationsjahre', 'Emerging Researcher: 5\u20139 aktive Publikationsjahre', 'Established Researcher: 10\u201314 aktive Publikationsjahre', - 'Senior Researcher: ab 15 aktiven Publikationsjahre', + 'Senior Researcher: ab 15 aktiven Publikationsjahren', '', 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', ].join('\n'); diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 3bd44f29..4d7986ef 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -168,7 +168,7 @@ export class PersonComponent { 'Early Researcher: 1\u20134 aktive Publikationsjahre', 'Emerging Researcher: 5\u20139 aktive Publikationsjahre', 'Established Researcher: 10\u201314 aktive Publikationsjahre', - 'Senior Researcher: ab 15 aktiven Publikationsjahre', + 'Senior Researcher: ab 15 aktiven Publikationsjahren', '', 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', ].join('\n'); From 110977c847cbbd027d1aeca989e9ba56f58b823c Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 20 Jun 2026 10:55:41 +0200 Subject: [PATCH 10/53] Update career stage labels --- service/src/main/inse/persons/logic.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index ac94a469..3b535d2d 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -242,15 +242,15 @@ def _classify_career_stage(active_years: int) -> str: return "unknown" if active_years <= 4: - return "Early Researcher" + return "Early" if active_years <= 9: - return "Emerging Researcher" + return "Emerging" if active_years <= 14: - return "Established Researcher" + return "Established" - return "Senior Researcher" + return "Senior" def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: From 28b57059b7d5879865f9f5d11f5eb3207c081fbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 20 Jun 2026 15:12:33 +0200 Subject: [PATCH 11/53] Added support for eu projects for other institutions than UDE --- .../institutions_search_client.py | 185 ++++++++--- service/src/main/inse/projects/model.py | 2 +- .../inse/projects/projects_search_client.py | 291 ++++++++---------- service/src/main/inse/projects/router.py | 29 ++ service/src/main/inse/projects/service.py | 111 ++++--- service/src/main/inse/works/logic.py | 65 +++- ude_person.http | 157 +++++++++- webapp/src/app/api/api/projects.service.ts | 56 ++++ webapp/src/app/app.routes.ts | 2 + .../person-projects.component.ts | 8 +- .../modules/projects/projects.component.ts | 2 +- .../resolvers/bund-project-page.resolver.ts | 4 +- .../cordis-eu-project-page.resolver.ts | 17 +- .../person-cordis-eu-project-page.resolver.ts | 24 ++ 14 files changed, 660 insertions(+), 293 deletions(-) create mode 100644 webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 0d9f0ff8..0e86c8de 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -20,13 +20,21 @@ class InstitutionsSearchClient: """ pass - def get_institution_by_id(self, raw_institution_id: str) -> Institution: - """ - Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster. + def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: + """Retrieves an institution by its raw OpenAlex institution ID. + + Args: + raw_oa_institution_id (str): The raw OpenAlex institution ID to search for. + + Raises: + NotFoundException: If no institution is found with the given ID or if the institution data cannot be parsed. + + Returns: + Institution: The institution corresponding to the given raw OpenAlex institution ID. """ query = { "match": { - "id": f"https://openalex.org/{raw_institution_id.upper()}", + "id": f"https://openalex.org/{raw_oa_institution_id.upper()}", } } @@ -35,13 +43,13 @@ class InstitutionsSearchClient: hits = res.get("hits", {}).get("hits", []) if not hits: raise NotFoundException( - f"Institution with ID '{raw_institution_id}' not found." + f"Institution with ID '{raw_oa_institution_id}' not found." ) institution = self._convert_hit_to_institution(hits[0]) if not institution: raise NotFoundException( - f"Institution with ID '{raw_institution_id}' could not be parsed." + f"Institution with ID '{raw_oa_institution_id}' could not be parsed." ) return institution @@ -208,37 +216,39 @@ class InstitutionsSearchClient: if query_text: stripped = query_text.strip() - must.append({ - "bool": { - "should": [ - { - "wildcard": { - "display_name.keyword": { - "value": f"*{stripped}*", - "boost": 2 - } - } - }, - { - "wildcard": { - "display_name_alternatives.keyword": { - "value": f"*{stripped}*", - "boost": 2 - } - } - }, - { - "wildcard": { - "display_name_acronyms.keyword": { - "value": f"*{stripped.upper()}*", - "boost": 10 - } - } + must.append( + { + "bool": { + "should": [ + { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "boost": 2, + } + } + }, + { + "wildcard": { + "display_name_alternatives.keyword": { + "value": f"*{stripped}*", + "boost": 2, + } + } + }, + { + "wildcard": { + "display_name_acronyms.keyword": { + "value": f"*{stripped.upper()}*", + "boost": 10, + } + } + }, + ], + "minimum_should_match": 1, } - ], - "minimum_should_match": 1 - } - }) + } + ) filter_queries = [] @@ -278,35 +288,41 @@ class InstitutionsSearchClient: return [Institution.from_dict(hit["_source"]) for hit in hits] - def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]: + def get_institution_aliases_by_oa_institution_id( + self, raw_oa_institution_id: str + ) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. Args: - raw_institution_id (str): The raw institution ID for which to retrieve aliases. + raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve aliases. Returns: List[str]: A list of aliases for the given institution ID. """ - institution = self.get_institution_by_id(raw_institution_id) + institution = self.get_institution_by_id(raw_oa_institution_id) aliases = list( self.augment_aliases(set(institution.display_name_alternatives or [])) - | self.get_predefined_institution_aliases(raw_institution_id) + | self.get_predefined_institution_aliases(raw_oa_institution_id) ) logger.debug( - "Retrieved aliases for institution_id=%s: %s", raw_institution_id, aliases + "Retrieved aliases for institution_id=%s: %s", + raw_oa_institution_id, + aliases, ) return aliases - def get_predefined_institution_aliases(self, raw_institution_id: str) -> Set[str]: + def get_predefined_institution_aliases( + self, raw_oa_institution_id: str + ) -> Set[str]: """Get predefined aliases for a given institution ID. Args: - raw_institution_id (str): The raw institution ID for which to retrieve predefined aliases. + raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve predefined aliases. Returns: Set[str]: A set of predefined aliases for the given institution ID. """ - raw_institution_id = raw_institution_id.upper() + raw_oa_institution_id = raw_oa_institution_id.upper() predefined_aliases = { "I62318514": [ "universität duisburg-essen", @@ -317,7 +333,9 @@ class InstitutionsSearchClient: ], } - return self.augment_aliases(set(predefined_aliases.get(raw_institution_id, []))) + return self.augment_aliases( + set(predefined_aliases.get(raw_oa_institution_id, [])) + ) def augment_aliases(self, aliases: Set[str]) -> Set[str]: """Augment a set of aliases by applying the augment_alias function to each alias. @@ -407,3 +425,80 @@ class InstitutionsSearchClient: "Failed to validate institution hit ID %s: %s", hit.get("_id"), e ) return None + + def get_cordis_eu_organisation_ids_by_oa_institution_id( + self, raw_oa_institution_id: str + ) -> Optional[List[str]]: + """Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices. + + Args: + raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve the corresponding EU organisation IDs. + + Returns: + Optional[List[str]]: A list of corresponding EU organisation IDs or None if the search fails. + """ + + institution_aliases = set( + self.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id=raw_oa_institution_id + ) + ) + + body = { + "size": 0, + "query": { + "bool": { + "filter": [ + { + "terms": { + "name.keyword": [ + institution_alias.upper() + for institution_alias in institution_aliases + ] + } + } + ] + } + }, + "aggs": { + "organisation_ids": { + "terms": {"field": "organisationID", "size": 10000} + } + }, + } + + logger.debug( + "Searching for EU organisation IDs for raw_oa_institution_id=%s with aliases=%s and query: %s", + raw_oa_institution_id, + institution_aliases, + body, + ) + + try: + # IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results + response = elasticsearch.search( + index="cordis_eu_*_organizations", body=body, cluster="inse" + ) + except Exception as e: + logger.exception("Error while searching for EU organisation IDs: %s", e) + return None + + logger.debug( + "Received response for EU organisation ID search for raw_oa_institution_id=%s: %s", + raw_oa_institution_id, + response, + ) + + aggregations = response.get("aggregations", {}) + organisation_ids_buckets = aggregations.get("organisation_ids", {}).get( + "buckets", [] + ) + organisation_ids = [bucket.get("key") for bucket in organisation_ids_buckets] + + logger.debug( + "Extracted EU organisation IDs for raw_oa_institution_id=%s: %s", + raw_oa_institution_id, + organisation_ids, + ) + + return organisation_ids diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index ae05256b..dd75726f 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -184,7 +184,7 @@ class FundingProject(BaseModel): title=source.get("title"), start_date=source.get("startDate"), end_date=source.get("endDate"), - funding_amount=source.get("ecMacContribution"), + funding_amount=source.get("ecMaxContribution"), ) @classmethod diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 8f8c93cd..3347fc3c 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1,6 +1,6 @@ import json import logging -from typing import Any, Dict, List, Literal, Optional, Set +from typing import Any, Dict, List, Optional, Set import httpx @@ -23,6 +23,7 @@ from inse.models.eu_project import EuProject from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject +from inse.integrations import elasticsearch settings = get_settings() @@ -256,7 +257,7 @@ class BundProjectsSearchClient(ProjectsSearchClient): sort_by: str = "topic", sort_direction: str = "asc", ) -> BundProjectPage: - query = self.bund_projects_query( + query = self._bund_projects_query( page=page, size=size, institution_names=institution_names, @@ -297,100 +298,19 @@ class EuProjectsSearchClient(ProjectsSearchClient): api_key=settings.elasticsearch_inse_api_key, ) - def eu_projects_query( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = "Network", - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> dict: - from_ = page * size - query: Dict[str, Any] = {"size": size, "from": from_, "query": {}} + def _eu_projects_id_body(self, eu_organisation_ids: List[str]) -> Dict[str, Any]: + """Constructs the Elasticsearch query body to retrieve project IDs associated with the given list of EU organisation IDs. - must_clauses: List[Dict[str, Any]] = [] - if id: - must_clauses.append({"match": {"id": id}}) + Args: + eu_organisation_ids (List[str]): A list of EU organisation IDs for which to retrieve associated project IDs. - if topic is not None and topic.strip() != "": - must_clauses.append( - { - "match_phrase_prefix": { - "title": { - "query": topic, - "max_expansions": 50, - } - } - } - ) - - if institution_names: - must_clauses.append( - { - "nested": { - "path": "organization_nested", - "query": { - "bool": { - "should": [ - { - "match": { - "organization_nested.name": { - "query": name, - "operator": "and", - } - } - } - for name in institution_names - ], - "minimum_should_match": 1, - } - }, - } - } - ) - - if must_clauses: - query["query"] = {"bool": {"must": must_clauses}} - else: - query["query"] = {"match_all": {}} - - sort_by = sort_by.strip().lower() - sort_direction = sort_direction.strip().lower() - if sort_direction not in ["asc", "desc"]: - sort_direction = "asc" - - sort_config: Dict[str, Any] = {} - - if sort_by == "topic": - sort_config = {"title.keyword": {"order": sort_direction}} - - elif sort_by == "grant_amount": - sort_config = {"totalCost.keyword": {"order": sort_direction}} - - elif sort_by == "department": - sort_config = { - "programme_nested.programme.keyword": { - "order": sort_direction, - "nested": {"path": "programme_nested"}, - } - } - else: - sort_config = {"id.keyword": {"order": sort_direction}} - - query["sort"] = [sort_config] - - query_str = json.dumps(query, indent=2) - logger.debug(f"Constructed EU project query: {query_str}") - - return query - - def _eu_projects_id_body(self, eu_organisation_id: str) -> Dict[str, Any]: + Returns: + Dict[str, Any]: The Elasticsearch query body. + """ body: Dict[str, Any] = { "size": 0, "query": { - "bool": {"filter": [{"term": {"organisationID": eu_organisation_id}}]} + "bool": {"filter": [{"terms": {"organisationID": eu_organisation_ids}}]} }, "aggs": { "associated_project_ids": { @@ -422,6 +342,14 @@ class EuProjectsSearchClient(ProjectsSearchClient): return ids def _eu_project_sort_by_field(self, sort_by: ProjectsSortBy) -> str: + """Maps the ProjectsSortBy enum to the corresponding Elasticsearch field for sorting EU projects. + + Args: + sort_by (ProjectsSortBy): The sorting criterion specified as a ProjectsSortBy enum value. + + Returns: + str: The corresponding Elasticsearch field for sorting. + """ if sort_by == ProjectsSortBy.TITLE: return "title.keyword" elif sort_by == ProjectsSortBy.FUNDING_START: @@ -475,22 +403,22 @@ class EuProjectsSearchClient(ProjectsSearchClient): logger.debug(f"Constructed EU project details query: {query_str}") return body - async def search_eu_projects2( + async def search_eu_projects( self, - eu_organisation_id: str, + eu_organisation_ids: List[str], projects_filtering_properties: ProjectsFilteringProperties, ) -> CordisEuProjectPage: - projects_id_body = self._eu_projects_id_body(eu_organisation_id) + projects_id_body = self._eu_projects_id_body(eu_organisation_ids) id_response = await self.make_search_request( projects_id_body, index="cordis_eu_*_organizations" ) project_ids = self._eu_projects_id_response_to_ids(id_response) logger.debug( - f"Found project IDs for organization ID {eu_organisation_id}: {project_ids}" + f"Found project IDs for organization IDs {eu_organisation_ids}: {project_ids}" ) if not project_ids: logger.debug( - f"No project IDs found for organization ID {eu_organisation_id}" + f"No project IDs found for organization IDs {eu_organisation_ids}" ) return CordisEuProjectPage( elements=[], @@ -517,6 +445,16 @@ class EuProjectsSearchClient(ProjectsSearchClient): def _response_to_cordis_eu_project_page( self, response: Dict[str, Any], page: int, size: int ) -> CordisEuProjectPage: + """Converts the Elasticsearch response to a CordisEuProjectPage containing CordisEuProject elements. + + Args: + response (Dict[str, Any]): The Elasticsearch response. + page (int): The page number. + size (int): The number of items per page. + + Returns: + CordisEuProjectPage: The converted project page. + """ hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [ @@ -527,56 +465,81 @@ class EuProjectsSearchClient(ProjectsSearchClient): elements=elements, total=total_hits, page=page, size=size ) - def response_to_eu_project_page( - self, response: Dict[str, Any], page: int, size: int - ) -> EuProjectPage: + def _get_raw_doi(self, doi: str) -> str: + """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. + + Args: + doi (str): The DOI string to process. + + Returns: + str: The raw DOI string. + """ + if doi.startswith("https://doi.org/"): + return doi[len("https://doi.org/") :] + elif doi.startswith("http://dx.doi.org/"): + return doi[len("http://dx.doi.org/") :] + else: + return doi + + def get_cordis_eu_publications_by_dois(self, dois: List[str]): + """Retrieves Cordis EU publications associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve publications. + + Returns: + _type_: The retrieved publications. + """ + raw_dois = [self._get_raw_doi(doi) for doi in dois] + query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + response = elasticsearch.search( + query=query, index="cordis_eu_*_publications", cluster="inse" + ) + + logger.debug( + f"Received publications response: {json.dumps(response, indent=2)}" + ) + + return response + + def get_cordis_eu_project_ids_by_dois(self, dois: List[str]) -> List[str]: + """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve project IDs. + + Returns: + List[str]: The list of project IDs. + """ + response = self.get_cordis_eu_publications_by_dois(dois=dois) + hits_block = response.get("hits", {}) + project_ids = set() + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if project_id: + project_ids.add(project_id) + return list(project_ids) + + def get_cordis_eu_projects_by_project_ids( + self, project_ids: List[str] + ) -> CordisEuProjectPage: + query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} + + response = elasticsearch.search( + query=query, index="cordis_eu_*_projects", cluster="inse" + ) + hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [ - EuProject.model_validate(hit["_source"]) + CordisEuProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", []) ] - return EuProjectPage(elements=elements, total=total_hits, page=page, size=size) - - async def search_eu_projects( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> EuProjectPage: - query = self.eu_projects_query( - page=page, - size=size, - id=id, - institution_names=institution_names, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, + return CordisEuProjectPage( + elements=elements, total=total_hits, page=0, size=len(elements) ) - response = await self.make_search_request(query) - return self.response_to_eu_project_page(response, page, size) - - async def get_eu_projects_by_institution_name( - self, - institution_names: List[str], - page: int, - size: int, - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> EuProjectPage: - query = self.eu_projects_query( - page=page, - size=size, - institution_names=institution_names, - sort_by=sort_by, - sort_direction=sort_direction, - ) - response = await self.make_search_request(query) - return self.response_to_eu_project_page(response, page, size) class DfgProjectsSearchClient(ProjectsSearchClient): @@ -892,28 +855,6 @@ class CompleteProjectsSearchClient(ProjectsSearchClient): else: raise ValueError(f"Unsupported project type: {project_type}") - def _hit_to_funding_project(self, hit: Dict[str, Any]) -> FundingProject: - if hit.get("_index", "").startswith("cordis_eu_") and hit.get( - "_index", "" - ).endswith("_projects"): - return FundingProject.from_cordis_projects_hit(hit=hit) - elif hit.get("_index") == "projects_bund_v1": - return FundingProject.from_bund_projects_hit(hit=hit) - elif hit.get("_index") == "projects_dfg_all": - return FundingProject.from_dfg_projects_hit(hit=hit) - else: - raise ValueError( - "The provided hit does not belong to a recognized project index." - ) - - def _response_to_funding_project_page( - self, response: Dict[str, Any], page: int, size: int - ) -> FundingProjectPage: - hits = response.get("hits", {}).get("hits", []) - projects = [self._hit_to_funding_project(hit=hit) for hit in hits] - total = response.get("hits", {}).get("total", {}).get("value", 0) - return FundingProjectPage(elements=projects, total=total, page=page, size=size) - async def search_projects( self, page: int, @@ -937,4 +878,28 @@ class CompleteProjectsSearchClient(ProjectsSearchClient): ) projects_response = await self.make_search_request(body, index=index) - return self._response_to_funding_project_page(projects_response, page, size) + return _response_to_funding_project_page(projects_response, page, size) + + +def _response_to_funding_project_page( + response: Dict[str, Any], page: int, size: int +) -> FundingProjectPage: + hits = response.get("hits", {}).get("hits", []) + projects = [_hit_to_funding_project(hit=hit) for hit in hits] + total = response.get("hits", {}).get("total", {}).get("value", 0) + return FundingProjectPage(elements=projects, total=total, page=page, size=size) + + +def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: + if hit.get("_index", "").startswith("cordis_eu_") and hit.get( + "_index", "" + ).endswith("_projects"): + return FundingProject.from_cordis_projects_hit(hit=hit) + elif hit.get("_index") == "projects_bund_v1": + return FundingProject.from_bund_projects_hit(hit=hit) + elif hit.get("_index") == "projects_dfg_all": + return FundingProject.from_dfg_projects_hit(hit=hit) + else: + raise ValueError( + "The provided hit does not belong to a recognized project index." + ) diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 60beae82..7d6e45f9 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -55,6 +55,35 @@ def get_complete_projects_search_client() -> CompleteProjectsSearchClient: return CompleteProjectsSearchClient() +@router.get( + "/author/{raw_oa_author_id}/eu", + summary="Get EU projects for an author.", + description="Returns a list of EU projects associated with the specified author ID.", + operation_id="getEuProjectsForAuthor", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": CordisEuProjectPage, + }, + status.HTTP_404_NOT_FOUND: {"description": "Author not found"}, + }, + response_model_by_alias=False, +) +def get_eu_projects_for_author( + eu_projects_search_client: Annotated[ + EuProjectsSearchClient, Depends(get_eu_search_client) + ], + raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")], +) -> CordisEuProjectPage: + logger.debug( + f"Received request to get EU projects for author_id={raw_oa_author_id}" + ) + return projects_service.search_cordis_eu_projects_for_author_id( + eu_projects_search_client=eu_projects_search_client, + raw_oa_author_id=raw_oa_author_id, + ) + + @router.post( "/institution/bund/search", summary="Get bund projects.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 83f55211..9dde9e87 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -27,6 +27,7 @@ from inse.institutions.institutions_search_client import ( ) from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id +from inse.works.logic import get_publication_dois_of_author logger = logging.getLogger(__name__) @@ -78,8 +79,10 @@ async def get_bund_projects_by_institution_id( logger.info( f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}" ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - filtering_properties.raw_oa_institution_id + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + filtering_properties.raw_oa_institution_id + ) ) logger.debug( f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" @@ -126,79 +129,39 @@ async def get_cordis_eu_projects_by_institution_id( logger.info( f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}" ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - projects_filtering_properties.raw_oa_institution_id + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + projects_filtering_properties.raw_oa_institution_id + ) ) logger.debug( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - institution_eu_organisation_id = await ( - institutions_search_client.get_eu_organisation_id_by_oa_institution_id( + institution_eu_organisation_ids = ( + institutions_search_client.get_cordis_eu_organisation_ids_by_oa_institution_id( projects_filtering_properties.raw_oa_institution_id ) ) - if not institution_eu_organisation_id: + if not institution_eu_organisation_ids: logger.debug( - f"No EU organization ID found for institution_id={projects_filtering_properties.raw_oa_institution_id}" + f"No EU organization IDs found for institution_id={projects_filtering_properties.raw_oa_institution_id}" ) - raise NotFoundException( - f"EU organization ID for institution with id {projects_filtering_properties.raw_oa_institution_id} not found" + return CordisEuProjectPage( + elements=[], + total=0, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, ) - cordis_eu_project_page = await eu_search_client.search_eu_projects2( - eu_organisation_id=institution_eu_organisation_id, + cordis_eu_project_page = await eu_search_client.search_eu_projects( + eu_organisation_ids=institution_eu_organisation_ids, projects_filtering_properties=projects_filtering_properties, ) return cordis_eu_project_page -async def get_eu_projects_by_institution_id( - eu_search_client: EuProjectsSearchClient, - institutions_search_client: InstitutionsSearchClient, - raw_oa_institution_id: str, - topic: Optional[str], - page: int, - size: int, - sort_by: str = "topic", - sort_direction: str = "asc", -) -> EuProjectPage: - logger.info( - f"Fetching EU projects for institution_id={raw_oa_institution_id}, page={page}, size={size}" - ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - raw_oa_institution_id - ) - logger.debug( - f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" - ) - - institution_eu_organisation_id = await ( - institutions_search_client.get_eu_organisation_id_by_oa_institution_id( - raw_oa_institution_id - ) - ) - if not institution_eu_organisation_id: - logger.debug( - f"No EU organization ID found for institution_id={raw_oa_institution_id}" - ) - raise NotFoundException( - f"EU organization ID for institution with id {raw_oa_institution_id} not found" - ) - - response = await eu_search_client.search_eu_projects( - page=page, - size=size, - institution_names=institution_aliases, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, - ) - logger.debug(f"get_eu_projects_by_institution_id response: {response}") - return response - - async def get_dfg_projects_by_author_id( dfg_search_client: DfgProjectsSearchClient, author_id: str, @@ -264,8 +227,10 @@ async def get_institution_bund_projects_funding_over_time( logger.info( f"Fetching funding over time for institution_id={raw_oa_institution_id}" ) - institution_aliases = institutions_search_client.get_institution_aliases_by_id( - raw_oa_institution_id + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) ) logger.debug( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" @@ -375,3 +340,31 @@ async def get_single_bund_project( if not project: raise NotFoundException(f"BUND project with id {project_id} not found") return project + + +def search_cordis_eu_projects_for_author_id( + eu_projects_search_client: EuProjectsSearchClient, raw_oa_author_id: str +) -> CordisEuProjectPage: + + # Direct search not possible -> multi stage search + # 1. Exisiting author has publications with DOIs + # 2. CORDIS EU projects have associated publications with DOIs + # 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author + + dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id) + + logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}") + + project_ids = eu_projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) + + logger.debug( + f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}" + ) + + funding_project_page = ( + eu_projects_search_client.get_cordis_eu_projects_by_project_ids( + project_ids=project_ids + ) + ) + + return funding_project_page diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 37540cda..26528505 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -649,9 +649,7 @@ def _author_works_query(author_id: str) -> dict[str, Any]: def _parse_year_count_buckets(response: dict) -> list[dict]: return ( - response.get("aggregations", {}) - .get("publication_years", {}) - .get("buckets", []) + response.get("aggregations", {}).get("publication_years", {}).get("buckets", []) ) @@ -691,13 +689,9 @@ def _collect_topic_ids_from_year_buckets(year_buckets: list[dict]) -> set[str]: topic_ids: set[str] = set() for year_bucket in year_buckets: - primary_buckets = ( - year_bucket.get("primary_topics", {}).get("buckets", []) - ) + primary_buckets = year_bucket.get("primary_topics", {}).get("buckets", []) topic_buckets = ( - year_bucket.get("topics_nested", {}) - .get("topics", {}) - .get("buckets", []) + year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", []) ) for bucket in primary_buckets + topic_buckets: @@ -723,9 +717,7 @@ def _build_timeline_elements_from_aggregations( continue topics = _build_topic_counts_from_buckets( - year_bucket.get("topics_nested", {}) - .get("topics", {}) - .get("buckets", []), + year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", []), topic_details=topic_details, max_topics_per_year=max_topics_per_year, use_reverse_nested_count=True, @@ -781,6 +773,7 @@ def _build_topic_counts_from_buckets( return topics + async def _search_author_works_data( search_client: OpenAlexWorksSearchClient, author_id: str, @@ -860,4 +853,50 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: detail="OpenAlex works search response could not be parsed.", ) from exc - return elements, total \ No newline at end of file + return elements, total + + +def get_publication_dois_of_author( + raw_oa_author_id: str, +) -> List[str]: + query = { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": f"https://openalex.org/{raw_oa_author_id.strip().upper()}" + } + }, + } + } + ], + "filter": [{"exists": {"field": "doi"}}], + } + } + + try: + response = elasticsearch.search( + index="openalex-works", + source=["doi"], + size=10000, + query=query, + cluster="nes", + ) + except httpx.HTTPError as exc: + logger.exception("Request for publication DOIs of author failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Request for publication DOIs of author failed.", + ) from exc + + dois = [] + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi = source.get("doi") + if doi: + dois.append(doi) + + return dois diff --git a/ude_person.http b/ude_person.http index 35ed2607..f4691a10 100644 --- a/ude_person.http +++ b/ude_person.http @@ -17,6 +17,21 @@ GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json +{ + "size": 100, + "query": { + "bool": { + "filter": [ + { + "terms": { + "projectID": ["287661"] + } + } + ] + } + } +} + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_mapping Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== @@ -47,6 +62,73 @@ Content-Type: application/json } } +# 10.1371/journal.pone.0018216 + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_mapping +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_fp7_project_iprs/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "qaProcessedDoi": [ + "10.5555/3234847.3234861", + "10.1145/1858367.1858373", + "10.1145/3583120.3586961", + "10.1109/ipin.2017.8115906", + "10.1145/3274783.3275217", + "10.1007/978-3-031-20716-7_7", + "10.1109/percomw.2012.6197554", + "10.1016/j.pmcj.2012.12.002", + "10.1007/978-3-658-32266-3_30", + "10.1109/percomw.2013.6529502", + "10.1109/ie.2010.40", + "10.18419/opus-2650", + "10.1007/s00138-024-01553-z", + "10.1007/978-3-030-90439-5_15", + "10.1201/9781003338659-4", + "10.1016/j.pmcj.2013.10.013", + "10.1109/percom.2009.4912852", + "10.1109/icra55743.2025.11128432", + "10.1145/2494091.2497327", + "10.1007/978-3-658-46485-1_31", + "10.1109/ie.2017.22", + "10.1109/jiot.2016.2554146", + "10.1145/2493432.2493459", + "10.3233/ais-160416", + "10.1109/percomw.2007.111", + "10.5194/asr-17-183-2020", + "10.1007/978-3-658-36430-4_37", + "10.1007/978-3-030-64559-5_50" + ] + } + } + ] + } + } +} + + + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== @@ -127,7 +209,7 @@ Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw Content-Type: application/json { - "size": 0, + "size": 10, "query": { "bool": { "filter": [ @@ -138,12 +220,41 @@ Content-Type: application/json } ] } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "terms": { + "name.keyword": [ + "UNIVERSITAET DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG-ESSEN", + "UNIVERSITÄT DUISBURG-ESSEN", + "UNIVERSITAT DUISBURG ESSEN", + "UNIVERSITÄT DUISBURG ESSEN", + "UNIVERSITY OF DUISBURG ESSEN", + "UNIVERSITAET DUISBURG ESSEN", + "UNIVERSITAT DUISBURG-ESSEN" + ] + } + } + ] + } }, "aggs": { - "specific_org_rcn_values": { + "organisation_ids": { "terms": { "field": "organisationID", - "size": 1000 + "size": 10000 } } } @@ -1052,6 +1163,46 @@ Content-Type: application/json ### +GET https://project.nes.uni-due.de/elastic/openalex-works/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + +### + +GET https://project.nes.uni-due.de/elastic/openalex-works/_search +Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== +Content-Type: application/json + +{ + "_source": ["title", "doi"], + "size": 100, + "query": { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": "https://openalex.org/A5007170803" + } + } + } + } + ], + "filter": [ + { + "exists": { + "field": "doi" + } + } + ] + } + } +} + +### + GET https://project.nes.uni-due.de/elastic/openalex-authors/_search Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ== Content-Type: application/json diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 584633f1..b3b91911 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -133,6 +133,62 @@ export class ProjectsService extends BaseService { ); } + /** + * Get EU projects for an author. + * Returns a list of EU projects associated with the specified author ID. + * @endpoint get /api/projects/author/{raw_oa_author_id}/eu + * @param rawOaAuthorId The author ID to filter by. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getEuProjectsForAuthor(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaAuthorId === null || rawOaAuthorId === undefined) { + throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.'); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/projects/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/eu`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Get funding over time for bund projects. * Returns the funding over time for bund projects associated with the specified institution. diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 32b49d9d..a0f72fbb 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -14,6 +14,7 @@ import { bundSingleProjectResolver } from './resolvers/bund-single-project-resol import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver'; import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver'; import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver'; +import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; export const routes: Routes = [ { @@ -147,6 +148,7 @@ export const routes: Routes = [ ), resolve: { dfgProjectPage: dfgProjectsResolver, + personCordisEuProjectPage: personCordisEuProjectPageResolver, }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 6374de4f..3b7ad95e 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -8,7 +8,11 @@ import { TemplateRef, viewChild, } from '@angular/core'; -import { DfgProjectPage, DfgProjectSummary } from '../../api'; +import { + CordisEuProjectPage, + DfgProjectPage, + DfgProjectSummary, +} from '../../api'; import { DataTableComponent, GenericColumn, @@ -47,6 +51,8 @@ export class PersonProjectsComponent implements OnInit { dfgProjectColumns: GenericColumn[] = []; dfgProjectData: DfgProjectSummary[] = []; + personCordisEuProjectPage = input.required(); + dfgProjectFundingEndTmp = viewChild.required>( 'dfgProjectFundingEndTmp', ); diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts index 3e68025a..4fc6f46d 100644 --- a/webapp/src/app/modules/projects/projects.component.ts +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -66,7 +66,7 @@ export class ProjectsComponent { handleSearchTermChange(newTerm: string): void { this.router.navigate([], { - queryParams: { search: newTerm }, + queryParams: { search: newTerm, page: 0, size: 10 }, queryParamsHandling: 'merge', }); } diff --git a/webapp/src/app/resolvers/bund-project-page.resolver.ts b/webapp/src/app/resolvers/bund-project-page.resolver.ts index 57657d8c..548cbb34 100644 --- a/webapp/src/app/resolvers/bund-project-page.resolver.ts +++ b/webapp/src/app/resolvers/bund-project-page.resolver.ts @@ -19,9 +19,9 @@ export const bundProjectPageResolver: ResolveFn = ( institutionId = route.parent?.paramMap.get('institutionId') ?? null; } - const sortBy = (route.queryParamMap.get('sort_by') ?? + const sortBy = (route.queryParamMap.get('sort_by') || 'title') as ProjectsSortBy; - const sortDirection = (route.queryParamMap.get('sort_direction') ?? + const sortDirection = (route.queryParamMap.get('sort_direction') || 'asc') as SortDirection; const search = route.queryParamMap.get('search'); diff --git a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts index 791a0423..2508fa68 100644 --- a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts @@ -1,5 +1,10 @@ import { ResolveFn } from '@angular/router'; -import { CordisEuProjectPage, ProjectsService } from '../api'; +import { + CordisEuProjectPage, + ProjectsService, + ProjectsSortBy, + SortDirection, +} from '../api'; import { inject } from '@angular/core'; export const cordisEuProjectPageResolver: ResolveFn = ( @@ -13,8 +18,10 @@ export const cordisEuProjectPageResolver: ResolveFn = ( institutionId = route.parent?.paramMap.get('institutionId') ?? null; } - const sortBy = route.queryParamMap.get('sort_by') ?? 'title'; - const sortDirection = route.queryParamMap.get('sort_direction') ?? 'asc'; + const sortBy = (route.queryParamMap.get('sort_by') || + 'title') as ProjectsSortBy; + const sortDirection = (route.queryParamMap.get('sort_direction') || + 'asc') as SortDirection; const search = route.queryParamMap.get('search'); return inject(ProjectsService).searchCordisEuProjects({ @@ -23,7 +30,7 @@ export const cordisEuProjectPageResolver: ResolveFn = ( size: Number(size), raw_oa_institution_id: institutionId, query: search, - sort_by: sortBy as 'title' | 'funding_start' | 'funding_end', - sort_direction: sortDirection as 'asc' | 'desc', + sort_by: sortBy, + sort_direction: sortDirection, }); }; diff --git a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts new file mode 100644 index 00000000..fa15f0d1 --- /dev/null +++ b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts @@ -0,0 +1,24 @@ +import { ResolveFn } from '@angular/router'; +import { CordisEuProjectPage, ProjectsService } from '../api'; +import { inject } from '@angular/core'; + +export const personCordisEuProjectPageResolver: ResolveFn< + CordisEuProjectPage +> = (route, state) => { + const rawAuthorId = route.parent?.params['id']; + if (!rawAuthorId) { + throw new Error('Author ID is required to resolve collaboration network'); + } + + console.log('Before calling getEuProjectsForAuthor'); + inject(ProjectsService) + .getEuProjectsForAuthor(rawAuthorId) + .subscribe({ + next: (data) => { + console.log('Received data from getEuProjectsForAuthor:', data); + }, + }); + console.log('After calling getEuProjectsForAuthor'); + + return { elements: [], total: 0, page: 1, page_size: 10 }; +}; From 522c8ca3e861f948fbf41a1ab810976bade2178a Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sat, 20 Jun 2026 15:30:31 +0200 Subject: [PATCH 12/53] Update career stage labels (frontend) --- .../app/modules/person-card/person-card.component.ts | 10 +++++----- webapp/src/app/modules/person/person.component.ts | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 2844a6c3..0017a99a 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -115,14 +115,14 @@ export class PersonCardComponent { const activeYears = this.person.career_metrics?.active_years ?? '-'; return [ - `Aktuell: ${careerStage}`, + `Aktuell: ${careerStage.replace(' Researcher', '')}`, `Aktive Publikationsjahre: ${activeYears}`, '', 'Einteilung:', - 'Early Researcher: 1\u20134 aktive Publikationsjahre', - 'Emerging Researcher: 5\u20139 aktive Publikationsjahre', - 'Established Researcher: 10\u201314 aktive Publikationsjahre', - 'Senior Researcher: ab 15 aktiven Publikationsjahren', + 'Early: 1\u20134 aktive Publikationsjahre', + 'Emerging: 5\u20139 aktive Publikationsjahre', + 'Established: 10\u201314 aktive Publikationsjahre', + 'Senior: ab 15 aktiven Publikationsjahren', '', 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', ].join('\n'); diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 4d7986ef..edc7f00d 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -161,14 +161,14 @@ export class PersonComponent { const activeYears = this.person()?.career_metrics?.active_years ?? '-'; return [ - `Aktuell: ${stage}`, + `Aktuell: ${stage.replace(' Researcher', '')}`, `Aktive Publikationsjahre: ${activeYears}`, '', 'Einteilung:', - 'Early Researcher: 1\u20134 aktive Publikationsjahre', - 'Emerging Researcher: 5\u20139 aktive Publikationsjahre', - 'Established Researcher: 10\u201314 aktive Publikationsjahre', - 'Senior Researcher: ab 15 aktiven Publikationsjahren', + 'Early: 1\u20134 aktive Publikationsjahre', + 'Emerging: 5\u20139 aktive Publikationsjahre', + 'Established: 10\u201314 aktive Publikationsjahre', + 'Senior: ab 15 aktiven Publikationsjahren', '', 'Diese Einschätzung basiert ausschließlich auf OpenAlex-Publikationsdaten und ist kein offizieller akademischer Status.', ].join('\n'); From 124d65f8c9bdd671d9081a8894d9e62695135306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 20 Jun 2026 15:50:55 +0200 Subject: [PATCH 13/53] Added eu projects for single persons by DOI publication mapping --- .../person-projects.component.html | 27 +++++++ .../person-projects.component.ts | 72 +++++++++++++++++-- .../person-cordis-eu-project-page.resolver.ts | 13 +--- 3 files changed, 93 insertions(+), 19 deletions(-) diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index 90e01edf..e33bdee6 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -28,6 +28,11 @@ [sortDirection]="urlSortDirection()" (sortChange)="handleSortChange($event)" /> + + +
+ + + {{ element.startDate | date: 'dd.MM.yyyy' }} + + + + {{ element.endDate | date: 'dd.MM.yyyy' }} + + + + {{ element.ecMaxContribution | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }} + + + + + open_in_new + + diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 3b7ad95e..9e208870 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -9,6 +9,7 @@ import { viewChild, } from '@angular/core'; import { + CordisEuProject, CordisEuProjectPage, DfgProjectPage, DfgProjectSummary, @@ -28,6 +29,7 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { Sort, SortDirection } from '@angular/material/sort'; +import { CurrencyPipe, DatePipe } from '@angular/common'; @Component({ selector: 'app-person-projects', @@ -42,6 +44,8 @@ import { Sort, SortDirection } from '@angular/material/sort'; DebounceDirective, MatPaginatorModule, RouterModule, + DatePipe, + CurrencyPipe, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', @@ -51,8 +55,6 @@ export class PersonProjectsComponent implements OnInit { dfgProjectColumns: GenericColumn[] = []; dfgProjectData: DfgProjectSummary[] = []; - personCordisEuProjectPage = input.required(); - dfgProjectFundingEndTmp = viewChild.required>( 'dfgProjectFundingEndTmp', ); @@ -63,6 +65,23 @@ export class PersonProjectsComponent implements OnInit { 'dfgProjectDetailRowTmp', ); + personCordisEuProjectPage = input.required(); + personCordisEuProjectColumns: GenericColumn[] = []; + personCordisEuProjectData: CordisEuProject[] = []; + + euProjectsFundingStartTmp = viewChild.required>( + 'euProjectsFundingStartTmp', + ); + euProjectsFundingEndTmp = viewChild.required>( + 'euProjectsFundingEndTmp', + ); + euProjectsFundingAmountTmp = viewChild.required>( + 'euProjectsFundingAmountTmp', + ); + euProjectsActionsTmp = viewChild.required>( + 'euProjectsActionsTmp', + ); + urlSearchTerm = signal(''); urlSortKey = signal(''); urlSortDirection = signal(''); @@ -90,18 +109,24 @@ export class PersonProjectsComponent implements OnInit { }); effect(() => { - console.log( - 'PersonProjectsComponent: dfgProjectPage changed', - this.dfgProjectPage(), - ); this.dfgProjectData = this.dfgProjectPage().elements || []; }); + effect(() => { + console.log( + 'Updating personCordisEuProjectData with', + this.personCordisEuProjectPage(), + ); + + this.personCordisEuProjectData = + this.personCordisEuProjectPage().elements || []; + }); + effect(() => { const searchTerm = this.urlSearchTerm(); if (searchTerm) { this.router.navigate([], { - queryParams: { search: searchTerm }, + queryParams: { search: searchTerm, page: 0, size: this.pageSize() }, queryParamsHandling: 'merge', }); } @@ -137,6 +162,39 @@ export class PersonProjectsComponent implements OnInit { cellTemplate: this.dfgProjectActionsTmp(), }, ]; + + this.personCordisEuProjectColumns = [ + { + id: 'title', + header: 'Titel', + type: 'accessor', + accessorKey: 'title', + }, + { + id: 'startDate', + header: 'Startdatum', + type: 'display', + cellTemplate: this.euProjectsFundingStartTmp(), + }, + { + id: 'endDate', + header: 'Enddatum', + type: 'display', + cellTemplate: this.euProjectsFundingEndTmp(), + }, + { + id: 'ecMaxContribution', + header: 'Förderbetrag (EU)', + type: 'display', + cellTemplate: this.euProjectsFundingAmountTmp(), + }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.euProjectsActionsTmp(), + }, + ]; } handleSearchTermChange(newTerm: string): void { diff --git a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts index fa15f0d1..90427263 100644 --- a/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/person-cordis-eu-project-page.resolver.ts @@ -9,16 +9,5 @@ export const personCordisEuProjectPageResolver: ResolveFn< if (!rawAuthorId) { throw new Error('Author ID is required to resolve collaboration network'); } - - console.log('Before calling getEuProjectsForAuthor'); - inject(ProjectsService) - .getEuProjectsForAuthor(rawAuthorId) - .subscribe({ - next: (data) => { - console.log('Received data from getEuProjectsForAuthor:', data); - }, - }); - console.log('After calling getEuProjectsForAuthor'); - - return { elements: [], total: 0, page: 1, page_size: 10 }; + return inject(ProjectsService).getEuProjectsForAuthor(rawAuthorId); }; From 535e5d165f0391c3e851acfbfe0e251e00a08931 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sat, 20 Jun 2026 17:33:49 +0200 Subject: [PATCH 14/53] Create reusable topic chip component --- .../person-interesting.component.html | 21 +-- .../person-interesting.component.scss | 92 ----------- .../person-interesting.component.ts | 10 +- .../research-timeline.component.html | 74 +++------ .../research-timeline.component.scss | 107 +----------- .../research-timeline.component.ts | 13 +- .../ui/topic-chip/topic-chip.component.html | 27 +++ .../ui/topic-chip/topic-chip.component.scss | 108 ++++++++++++ .../ui/topic-chip/topic-chip.component.ts | 156 ++++++++++++++++++ 9 files changed, 345 insertions(+), 263 deletions(-) create mode 100644 webapp/src/app/shared/ui/topic-chip/topic-chip.component.html create mode 100644 webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss create mode 100644 webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index 92f4d52a..1a853cf8 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -11,19 +11,16 @@
@if (tags().length > 0) { @for (tag of tags(); track tag.label; let i = $index) { - + countIcon="article" + descriptionTooltipTarget="button" + (chipClick)="onTagClick(tag)"> + } } @else { Keine Themen gefunden diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.scss b/webapp/src/app/modules/person-interesting/person-interesting.component.scss index 178b12b0..1405142c 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.scss +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.scss @@ -29,98 +29,6 @@ gap: 12px; } -.topic-chip { - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - justify-items: center; - column-gap: 8px; - box-sizing: border-box; - min-height: 34px; - padding: 6px 12px; - border: 1px solid var(--topic-border); - border-radius: 8px; - background: var(--topic-bg); - color: var(--topic-color); - font-family: inherit; - font-size: 12px; - font-weight: 500; - line-height: 1.25; - cursor: pointer; - transition: - transform 0.15s ease, - box-shadow 0.15s ease; - - &:hover:not(:disabled) { - transform: translateY(-1px); - box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12); - text-decoration: none; - } - - &:disabled { - cursor: default; - } -} - -.topic-name { - min-width: 0; - text-align: center; - overflow-wrap: anywhere; -} - -.topic-count { - display: inline-flex; - flex: 0 0 auto; - align-items: center; - justify-content: center; - gap: 2px; - min-width: 18px; - height: 18px; - padding: 0 5px; - border-radius: 999px; - background: rgba(255, 255, 255, 0.78); - color: inherit; - font-size: 11px; - font-weight: 700; -} - -.topic-count .count-icon { - width: 13px; - height: 13px; - font-size: 13px; - line-height: 1; -} - -.purple { - --topic-border: #d8cafe; - --topic-bg: #f6f0ff; - --topic-color: #7255d9; -} - -.blue { - --topic-border: #bdd4ff; - --topic-bg: #f0f6ff; - --topic-color: #0b63ce; -} - -.green { - --topic-border: #bdebcf; - --topic-bg: #effaf3; - --topic-color: #24834f; -} - -.orange { - --topic-border: #ffd796; - --topic-bg: #fff7e8; - --topic-color: #c67500; -} - -.pink { - --topic-border: #ffc7d7; - --topic-bg: #fff1f5; - --topic-color: #d12f61; -} - .interest-footnote { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index d137caa6..40575afb 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -1,9 +1,12 @@ import { Component, input, computed, output } from '@angular/core'; -import { MatTooltipModule } from '@angular/material/tooltip'; import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; import { TopicCount } from '../../api'; +import { + TOPIC_CHIP_PALETTE, + TopicChipComponent, +} from '../../shared/ui/topic-chip/topic-chip.component'; interface InterestTag { id: string; @@ -13,11 +16,10 @@ interface InterestTag { } const MAX_TAGS = 5; -const colors = ['purple', 'blue', 'green', 'orange', 'pink']; @Component({ selector: 'app-person-interesting', - imports: [CommonModule, MatTooltipModule, MatIconModule], + imports: [CommonModule, MatIconModule, TopicChipComponent], templateUrl: './person-interesting.component.html', styleUrl: './person-interesting.component.scss', }) @@ -46,7 +48,7 @@ export class PersonInterestingComponent { }); getColorClass(index: number): string { - return colors[index % colors.length]; + return TOPIC_CHIP_PALETTE[index % TOPIC_CHIP_PALETTE.length]; } onTagClick(tag: InterestTag): void { diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index dc6026c8..bb7ba6f1 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -248,28 +248,20 @@ getDisplayedTopics(item).length > 0; else noTopicsForYear "> - + (chipClick)="selectTopic(topic, [item.year])"> + @@ -344,25 +336,17 @@
- + (chipClick)="selectTopic(topic, getPhaseYears(phase))"> + @@ -420,8 +404,7 @@ ).length > 0; else noPhaseYearTopics "> - + (chipClick)="selectTopic(topic, [year.year])"> + diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index adf3af43..540b5793 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -11,9 +11,6 @@ button { font-family: inherit; - } - - button:not(:where(.topic-chip, .mini-topic-chip)) { border: 0; background: transparent; padding: 0; @@ -366,60 +363,9 @@ gap: 8px; } -.topic-chip { - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - justify-items: center; - column-gap: 8px; +app-topic-chip.timeline-topic-chip { width: 100%; max-width: 210px; - box-sizing: border-box; - min-height: 34px; - padding: 6px 10px; - border: 1px solid var(--topic-border); - border-radius: 8px; - background: var(--topic-bg); - color: var(--topic-color); - font-family: inherit; - font-size: 12px; - font-weight: 500; - line-height: 1.25; - cursor: pointer; - transition: - transform 0.15s ease, - box-shadow 0.15s ease; - - &:hover:not(:disabled) { - transform: translateY(-1px); - box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12); - text-decoration: none; - } - - &:disabled { - cursor: default; - } -} - -.topic-name, -.mini-topic-chip span { - min-width: 0; - text-align: center; - overflow-wrap: anywhere; -} - -.topic-count { - display: inline-flex; - align-items: center; - justify-content: center; - min-width: 18px; - height: 18px; - padding: 0 5px; - border-radius: 999px; - background: rgba(255, 255, 255, 0.78); - color: inherit; - font-size: 11px; - font-weight: 700; } .no-topics { @@ -505,7 +451,7 @@ gap: 7px; margin-top: 14px; - .topic-chip { + app-topic-chip.phase-topic-chip { flex: 0 0 calc((100% - 7px) / 2); width: calc((100% - 7px) / 2); max-width: none; @@ -574,73 +520,24 @@ gap: 6px; } -.mini-topic-chip { - display: inline-grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - column-gap: 5px; - max-width: 100%; - padding: 4px 7px; - border: 0; - border-radius: 7px; - background: #f2f6ff; - color: #40506f; - font-family: inherit; - font-size: 11px; - line-height: 1.25; - cursor: pointer; - - &:hover:not(:disabled) { - color: var(--accent); - text-decoration: none; - } - - &:disabled { - cursor: default; - } - - strong { - display: inline-flex; - align-items: center; - gap: 2px; - color: var(--accent); - font-size: 10px; - } -} - .purple { --timeline-color: #7255d9; - --topic-border: #d8cafe; - --topic-bg: #f6f0ff; - --topic-color: #7255d9; } .blue { --timeline-color: #2678e8; - --topic-border: #bdd4ff; - --topic-bg: #f0f6ff; - --topic-color: #0b63ce; } .green { --timeline-color: #39a96b; - --topic-border: #bdebcf; - --topic-bg: #effaf3; - --topic-color: #24834f; } .orange { --timeline-color: #f59e0b; - --topic-border: #ffd796; - --topic-bg: #fff7e8; - --topic-color: #c67500; } .pink { --timeline-color: #e0527c; - --topic-border: #ffc7d7; - --topic-bg: #fff1f5; - --topic-color: #d12f61; } .timeline-note { diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index 43c99ff3..608ed040 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -12,6 +12,10 @@ import { SimpleChanges, ViewChild, } from '@angular/core'; +import { + TOPIC_CHIP_PALETTE, + TopicChipComponent, +} from '../../../../shared/ui/topic-chip/topic-chip.component'; export interface TopicTimelineTopic { id?: string; @@ -68,7 +72,12 @@ interface TimelineScrollAnchor { @Component({ selector: 'app-research-timeline', standalone: true, - imports: [CommonModule, MatProgressSpinnerModule, MatTooltipModule], + imports: [ + CommonModule, + MatProgressSpinnerModule, + MatTooltipModule, + TopicChipComponent, + ], templateUrl: './research-timeline.component.html', styleUrl: './research-timeline.component.scss', }) @@ -98,7 +107,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { selectedStartYear = 0; selectedEndYear = 0; - private readonly colors = ['purple', 'blue', 'green', 'orange', 'pink']; + private readonly colors = TOPIC_CHIP_PALETTE; private readonly columnWidth = 240; private readonly displayedTopicLimit = 3; private readonly displayedPhaseTopicLimit = 4; diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.html b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.html new file mode 100644 index 00000000..9ad26847 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.html @@ -0,0 +1,27 @@ + diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss new file mode 100644 index 00000000..fd1c2675 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss @@ -0,0 +1,108 @@ +:host { + display: inline-flex; + width: fit-content; + max-width: 100%; +} + +.topic-chip__button { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + justify-items: center; + box-sizing: border-box; + width: 100%; + max-width: 100%; + color: inherit; + font-family: inherit; + line-height: 1.25; + cursor: pointer; + + &:disabled { + cursor: default; + } +} + +:host(.topic-chip--normal) .topic-chip__button { + column-gap: 8px; + min-height: 34px; + padding: 6px 10px; + border: 1px solid var(--topic-border); + border-radius: 8px; + background: var(--topic-bg); + color: var(--topic-color); + font-size: 12px; + font-weight: 500; + transition: + transform 0.15s ease, + box-shadow 0.15s ease; + + &:hover:not(:disabled) { + transform: translateY(-1px); + box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12); + text-decoration: none; + } +} + +:host(.topic-chip--mini) .topic-chip__button { + column-gap: 5px; + padding: 4px 7px; + border: 0; + border-radius: 7px; + background: #f2f6ff; + color: #40506f; + font-size: 11px; + + &:hover:not(:disabled) { + color: var(--accent); + text-decoration: none; + } +} + +:host(.topic-chip--active.topic-chip--normal) .topic-chip__button { + border-color: var(--topic-color); + box-shadow: 0 0 0 2px color-mix(in srgb, var(--topic-color) 18%, transparent); +} + +:host(.topic-chip--active.topic-chip--mini) .topic-chip__button { + background: #eaf1ff; + color: var(--accent); +} + +.topic-chip__label { + min-width: 0; + text-align: center; + overflow-wrap: anywhere; +} + +.topic-chip__count { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + justify-content: center; + gap: 2px; + min-width: 18px; + height: 18px; + padding: 0 5px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.78); + color: inherit; + font-size: 11px; + font-weight: 700; +} + +:host(.topic-chip--mini) .topic-chip__count { + min-width: 0; + height: auto; + padding: 0; + border-radius: 0; + background: transparent; + color: var(--accent); + font-size: 10px; +} + +.topic-chip__count-icon { + width: 13px; + height: 13px; + font-size: 13px; + line-height: 1; +} diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts new file mode 100644 index 00000000..695b777b --- /dev/null +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts @@ -0,0 +1,156 @@ +import { + Component, + EventEmitter, + HostBinding, + Input, + Output, +} from '@angular/core'; +import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; + +export const TOPIC_CHIP_PALETTE = [ + 'purple', + 'blue', + 'green', + 'orange', + 'pink', +] as const; + +export type TopicChipPaletteColor = (typeof TOPIC_CHIP_PALETTE)[number]; +export type TopicChipColor = TopicChipPaletteColor | string; +export type TopicChipSize = 'normal' | 'mini'; +export type TopicChipTooltipTarget = 'label' | 'button'; + +interface TopicChipColorTokens { + border: string; + background: string; + color: string; +} + +const TOPIC_CHIP_COLORS: Record = { + purple: { + border: '#d8cafe', + background: '#f6f0ff', + color: '#7255d9', + }, + blue: { + border: '#bdd4ff', + background: '#f0f6ff', + color: '#0b63ce', + }, + green: { + border: '#bdebcf', + background: '#effaf3', + color: '#24834f', + }, + orange: { + border: '#ffd796', + background: '#fff7e8', + color: '#c67500', + }, + pink: { + border: '#ffc7d7', + background: '#fff1f5', + color: '#d12f61', + }, +}; + +@Component({ + selector: 'app-topic-chip', + imports: [MatIconModule, MatTooltipModule], + templateUrl: './topic-chip.component.html', + styleUrl: './topic-chip.component.scss', + standalone: true, +}) +export class TopicChipComponent { + @Input() label = ''; + @Input() count: number | string | null | undefined; + @Input() description: string | null | undefined = ''; + @Input() countTooltip: string | null | undefined = ''; + @Input() countIcon: string | null | undefined; + @Input() color: TopicChipColor = 'purple'; + @Input() size: TopicChipSize = 'normal'; + @Input() disabled = false; + @Input() active = false; + @Input() descriptionTooltipTarget: TopicChipTooltipTarget = 'label'; + + @Output() chipClick = new EventEmitter(); + + @HostBinding('class.topic-chip--normal') + get normalSize(): boolean { + return this.size === 'normal'; + } + + @HostBinding('class.topic-chip--mini') + get miniSize(): boolean { + return this.size === 'mini'; + } + + @HostBinding('class.topic-chip--active') + get activeState(): boolean { + return this.active; + } + + @HostBinding('style.--topic-border') + get topicBorder(): string { + return ( + this.colorTokens?.border ?? + `color-mix(in srgb, ${this.topicColor} 35%, #ffffff)` + ); + } + + @HostBinding('style.--topic-bg') + get topicBackground(): string { + return ( + this.colorTokens?.background ?? + `color-mix(in srgb, ${this.topicColor} 10%, #ffffff)` + ); + } + + @HostBinding('style.--topic-color') + get topicColor(): string { + return this.colorTokens?.color ?? this.color; + } + + get hasCount(): boolean { + return ( + this.count !== undefined && this.count !== null && `${this.count}` !== '' + ); + } + + get labelTooltip(): string { + return this.descriptionTooltipTarget === 'label' + ? this.normalizedDescription + : ''; + } + + get buttonTooltip(): string { + return this.descriptionTooltipTarget === 'button' + ? this.normalizedDescription + : ''; + } + + get normalizedCountTooltip(): string { + return (this.countTooltip ?? '').trim(); + } + + get countIconName(): string { + return (this.countIcon ?? '').trim(); + } + + handleClick(): void { + if (this.disabled) { + return; + } + + this.chipClick.emit(); + } + + private get normalizedDescription(): string { + return (this.description ?? '').trim(); + } + + private get colorTokens(): TopicChipColorTokens | undefined { + return TOPIC_CHIP_COLORS[this.color as TopicChipPaletteColor]; + } +} From 8c61b4d54f41bb916fdacfc708942fd3867a7b34 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 20 Jun 2026 21:07:23 +0200 Subject: [PATCH 15/53] Changed index to vectorize each keyword & updated database topicvector --- service/sentence_transformer/index_topics.py | 142 +++++++++++++------ 1 file changed, 101 insertions(+), 41 deletions(-) diff --git a/service/sentence_transformer/index_topics.py b/service/sentence_transformer/index_topics.py index 7b506427..c1e4496d 100644 --- a/service/sentence_transformer/index_topics.py +++ b/service/sentence_transformer/index_topics.py @@ -1,17 +1,13 @@ #!/usr/bin/env python3 """ -One-time script to fetch all topics from 'openalex-topics', -vectorize display names and chunked descriptions using the sentence-transformers model, -and push them to the 'topicvectors' index with multi-vector hybrid mapping. +Script to fetch all topics from 'openalex-topics', +vectorize display names, full descriptions, and individual keywords using the sentence-transformers model, +and push them to the 'topicvectors' index with multi-vector mapping. """ -import os import sys import json -import base64 -import re from pathlib import Path import httpx -import numpy as np from dotenv import load_dotenv # Add service/src/main to python path to load settings @@ -24,8 +20,10 @@ sys.path.append(str(project_root / "service" / "src" / "main")) from inse.config import settings ELASTIC_URL = settings.elasticsearch_url +if ELASTIC_URL and not ELASTIC_URL.endswith("/"): + ELASTIC_URL += "/" API_KEY = settings.elasticsearch_api_key -MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2" +MODEL_NAME = settings.sentence_transformers_model_name # Import sentence-transformers from sentence_transformers import SentenceTransformer @@ -35,14 +33,6 @@ headers = { "Content-Type": "application/json" } -def split_into_sentences(text): - if not text: - return [] - # Split on period, exclamation, or question mark followed by whitespace - sentences = re.split(r'(?<=[.!?])\s+', text.strip()) - # Filter out empty or extremely short sentences - return [s for s in sentences if len(s.strip()) > 3] - def fetch_all_topics(): print("Fetching topics from 'openalex-topics'...") topics = [] @@ -75,7 +65,67 @@ def fetch_all_topics(): print(f"Total topics fetched: {len(topics)}") return topics -def bulk_index_topics(topics, display_name_vectors, nested_description_vectors): +def update_mappings(): + print("Checking/updating mappings for 'topicvectors'...") + mapping_payload = { + "properties": { + "display_name_vector": { + "type": "dense_vector", + "dims": 768, + "index": True, + "similarity": "cosine", + "index_options": { + "type": "int8_hnsw", + "m": 16, + "ef_construction": 100 + } + }, + "description_vector": { + "type": "dense_vector", + "dims": 768, + "index": True, + "similarity": "cosine", + "index_options": { + "type": "int8_hnsw", + "m": 16, + "ef_construction": 100 + } + }, + "keyword_vectors": { + "type": "nested", + "properties": { + "vector": { + "type": "dense_vector", + "dims": 768, + "index": True, + "similarity": "cosine", + "index_options": { + "type": "int8_hnsw", + "m": 16, + "ef_construction": 100 + } + } + } + } + } + } + with httpx.Client(timeout=30.0) as client: + # Check if index exists + check_resp = client.get(f"{ELASTIC_URL}topicvectors", headers=headers) + if check_resp.status_code == 404: + print("Index 'topicvectors' does not exist. Creating it...") + create_payload = { + "mappings": mapping_payload + } + resp = client.put(f"{ELASTIC_URL}topicvectors", json=create_payload, headers=headers) + resp.raise_for_status() + else: + print("Index 'topicvectors' exists. Updating mappings...") + resp = client.put(f"{ELASTIC_URL}topicvectors/_mapping", json=mapping_payload, headers=headers) + resp.raise_for_status() + print("Mappings update process completed.") + +def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list): print("Bulk indexing vectorized topics into 'topicvectors'...") batch_size = 500 @@ -83,22 +133,24 @@ def bulk_index_topics(topics, display_name_vectors, nested_description_vectors): for i in range(0, len(topics), batch_size): batch_topics = topics[i:i+batch_size] batch_name_vecs = display_name_vectors[i:i+batch_size] - batch_desc_vecs_list = nested_description_vectors[i:i+batch_size] + batch_desc_vecs = description_vectors[i:i+batch_size] + batch_kw_vecs_list = keyword_vectors_list[i:i+batch_size] bulk_lines = [] - for t, name_vec, desc_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs_list): + for t, name_vec, desc_vec, kw_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs, batch_kw_vecs_list): source = t["_source"] - # Remove deprecated single vector if present - if "vector" in source: - del source["vector"] + source.pop("siblings", None) # drop siblings field when making the copy # Assign name vector as a standard float list source["display_name_vector"] = name_vec.tolist() - # Assign nested description vectors as standard float lists - source["description_vectors"] = [ - {"vector": vec.tolist()} for vec in desc_vecs + # Assign description vector + source["description_vector"] = desc_vec.tolist() + + # Assign nested keyword vectors + source["keyword_vectors"] = [ + {"vector": vec.tolist()} for vec in kw_vecs ] # Meta line @@ -124,6 +176,8 @@ def bulk_index_topics(topics, display_name_vectors, nested_description_vectors): print(f"Indexed batch {i} to {i + len(batch_topics)}") def main(): + update_mappings() + topics = fetch_all_topics() if not topics: print("No topics found. Exiting.") @@ -133,44 +187,50 @@ def main(): model = SentenceTransformer(MODEL_NAME) # 1. Gather all texts to embed - display_names = [] - description_sentences_by_topic = [] + keywords_by_topic = [] all_texts_to_embed = [] for t in topics: source = t["_source"] + name = source.get("display_name") or "" - display_names.append(name) all_texts_to_embed.append(name) desc = source.get("description") or "" - sentences = split_into_sentences(desc) - description_sentences_by_topic.append(sentences) - all_texts_to_embed.extend(sentences) + all_texts_to_embed.append(desc) - print(f"Embedding {len(all_texts_to_embed)} texts (display names and description passages)...") + kws = source.get("keywords") or [] + if not isinstance(kws, list): + kws = [kws] if kws else [] + keywords_by_topic.append(kws) + all_texts_to_embed.extend(kws) + + print(f"Embedding {len(all_texts_to_embed)} texts (display names, descriptions, and keywords)...") all_vectors = model.encode(all_texts_to_embed, show_progress_bar=True, batch_size=32) # 2. Map embeddings back to topics display_name_vectors = [] - nested_description_vectors = [] + description_vectors = [] + keyword_vectors_list = [] vector_idx = 0 for idx, t in enumerate(topics): - # First vector is the display name + display_name_vectors.append(all_vectors[vector_idx]) vector_idx += 1 - # Next N vectors are the description chunks - sentences = description_sentences_by_topic[idx] - topic_desc_vecs = [] - for _ in range(len(sentences)): - topic_desc_vecs.append(all_vectors[vector_idx]) + description_vectors.append(all_vectors[vector_idx]) + vector_idx += 1 + + kws = keywords_by_topic[idx] + topic_kw_vecs = [] + for _ in range(len(kws)): + topic_kw_vecs.append(all_vectors[vector_idx]) vector_idx += 1 - nested_description_vectors.append(topic_desc_vecs) + keyword_vectors_list.append(topic_kw_vecs) # Bulk index - bulk_index_topics(topics, display_name_vectors, nested_description_vectors) + bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list) print("Done!") if __name__ == "__main__": From c30208e61e9152808ec72e28554a36fb30acb6ae Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 20 Jun 2026 21:08:27 +0200 Subject: [PATCH 16/53] added model to config and .env --- service/src/main/inse/.env | 4 ++++ service/src/main/inse/config.py | 3 +++ service/src/main/inse/util.py | 4 +++- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index c7f128ed..55d8c5e7 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -17,3 +17,7 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 LLM_MODEL=gemma4-e4b + +# Sentence Transformers Configuration +SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2 + diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 80335dab..a5ab3a47 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -49,6 +49,9 @@ class Settings(BaseSettings): llm_api_key: Optional[str] = None llm_model: Optional[str] = None + # Sentence Transformers config + sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2" + # elasticsearch config elasticsearch_url: Optional[str] = None elasticsearch_api_key: Optional[str] = None diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index 1acf6d2e..dc47d976 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -38,6 +38,7 @@ def get_persons_data(hit:dict): return author from sentence_transformers import SentenceTransformer +from .config import settings # Sentence Transformer Model _model: SentenceTransformer | None = None @@ -55,5 +56,6 @@ def get_model(): if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models": os.environ["HF_HUB_OFFLINE"] = "1" - _model = SentenceTransformer("paraphrase-multilingual-mpnet-base-v2") + model_name = settings.sentence_transformers_model_name + _model = SentenceTransformer(model_name) return _model \ No newline at end of file From 8f707df86fb2e436672421ea4b8af768ad94d300 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 21 Jun 2026 09:33:57 +0200 Subject: [PATCH 17/53] implementing radio button option to select hybrid vs semantic --- service/src/main/inse/topics/service.py | 5 + webapp/src/app/api/api/topics.service.ts | 1147 +++++++++++------ .../topic-hierarchy.component.html | 33 + .../topic-hierarchy.component.ts | 53 +- 4 files changed, 847 insertions(+), 391 deletions(-) diff --git a/service/src/main/inse/topics/service.py b/service/src/main/inse/topics/service.py index bf6346fc..50c69fbc 100644 --- a/service/src/main/inse/topics/service.py +++ b/service/src/main/inse/topics/service.py @@ -129,9 +129,14 @@ async def vector_search_topics( int, Query(description="Maximum number of topics to return.", ge=1, le=100), ] = 25, + search_type: Annotated[ + str, + Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."), + ] = "hybrid", ): return await logic.vector_search_topics( query=query, limit=limit, + search_type=search_type, ) diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 4c2902a1..2b90f737 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,12 +9,18 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AutocompleteResponse } from '../model/autocompleteResponse'; @@ -24,410 +30,803 @@ import { HTTPValidationError } from '../model/hTTPValidationError'; import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class TopicsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); + /** + * Returns topic options for autocomplete inputs. + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public autocompleteTopics( + query: string, + domainId?: string, + fieldId?: string, + subfieldId?: string, + limit?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public autocompleteTopics( + query: string, + domainId?: string, + fieldId?: string, + subfieldId?: string, + limit?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public autocompleteTopics( + query: string, + domainId?: string, + fieldId?: string, + subfieldId?: string, + limit?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public autocompleteTopics( + query: string, + domainId?: string, + fieldId?: string, + subfieldId?: string, + limit?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling autocompleteTopics.', + ); } - /** - * Returns topic options for autocomplete inputs. - * @endpoint get /api/topics/autocomplete - * @param query Topic search text, for example \'machine learning\'. - * @param domainId Optional OpenAlex domain id filter. - * @param fieldId Optional OpenAlex field id filter. - * @param subfieldId Optional OpenAlex subfield id filter. - * @param limit Maximum number of autocomplete options. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling autocompleteTopics.'); - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + domainId, + 'domainId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fieldId, + 'fieldId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + subfieldId, + 'subfieldId', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - domainId, 'domainId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - fieldId, 'fieldId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - subfieldId, 'subfieldId'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + let localVarPath = `/api/topics/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public buildTopicCache( + pageSize?: number, + saveJson?: boolean, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public buildTopicCache( + pageSize?: number, + saveJson?: boolean, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public buildTopicCache( + pageSize?: number, + saveJson?: boolean, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public buildTopicCache( + pageSize?: number, + saveJson?: boolean, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + pageSize, + 'page_size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + saveJson, + 'save_json', + ); - let localVarPath = `/api/topics/autocomplete`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/topics/cache`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public countTopicHierarchy( + topic: Array, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public countTopicHierarchy( + topic: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public countTopicHierarchy( + topic: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public countTopicHierarchy( + topic: Array, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (topic === null || topic === undefined) { + throw new Error( + 'Required parameter topic was null or undefined when calling countTopicHierarchy.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topic', ); + }); } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarHeaders = this.defaultHeaders; - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - pageSize, 'page_size'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - saveJson, 'save_json'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/cache`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (topic === null || topic === undefined) { - throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topic'); - }) - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/count`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). - * @endpoint get /api/inse-service/topics/hierarchy - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarPath = `/api/inse-service/topics/count`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarHeaders = this.defaultHeaders; + /** + * Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics). + * @endpoint get /api/inse-service/topics/hierarchy + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getTopicHierarchy( + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getTopicHierarchy( + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopicHierarchy( + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopicHierarchy( + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/topics/hierarchy`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Returns a list of OpenAlex topics. - * @endpoint get /api/topics - * @param search Full-text search, for example \'machine learning\'. - * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. - * @param sort Sort field, for example \'works_count:desc\'. - * @param groupBy OpenAlex group_by field, for example \'domain.id\'. - * @param perPage Results per page. - * @param page Page number. Use cursor for deep pagination. - * @param cursor Cursor pagination token. Use \'*\' to start. - * @param sample Random sample size. Cannot be combined with sort or page. - * @param select Comma-separated fields to return. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - search, 'search'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filter, 'filter'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sort, 'sort'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - groupBy, 'group_by'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - perPage, 'per_page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - cursor, 'cursor'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sample, 'sample'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - select, 'select'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/topics`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Semantic / vector search for topics using a keyword/sentence. - * @endpoint get /api/topics/vector-search - * @param query Word or sentence to search by similarity. - * @param limit Maximum number of topics to return. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public vectorSearchTopics(query: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public vectorSearchTopics(query: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public vectorSearchTopics(query: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public vectorSearchTopics(query: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling vectorSearchTopics.'); - } + let localVarPath = `/api/inse-service/topics/hierarchy`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); + /** + * Returns a list of OpenAlex topics. + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public listTopics( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listTopics( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listTopics( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listTopics( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + search, + 'search', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filter, + 'filter', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sort, + 'sort', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + groupBy, + 'group_by', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + perPage, + 'per_page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + cursor, + 'cursor', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sample, + 'sample', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + select, + 'select', + ); - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/topics/vector-search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Semantic / vector search for topics using a keyword/sentence. + * @endpoint get /api/topics/vector-search + * @param query Word or sentence to search by similarity. + * @param limit Maximum number of topics to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public vectorSearchTopics( + query: string, + limit?: number, + searchType?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public vectorSearchTopics( + query: string, + limit?: number, + searchType?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public vectorSearchTopics( + query: string, + limit?: number, + searchType?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public vectorSearchTopics( + query: string, + limit?: number, + searchType?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling vectorSearchTopics.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + if (searchType !== undefined && searchType !== null) { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + searchType, + 'searchType', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/vector-search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html index 0ba8f150..08e8e6fd 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html @@ -1,4 +1,37 @@
+ @if (searchQuery) { +
+ Modus: + + + Hybrid + + + Semantisch + + +
+ } @if (loading()) {
diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts index eb9468e3..20060484 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts @@ -10,6 +10,7 @@ import { CommonModule } from '@angular/common'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatRadioModule } from '@angular/material/radio'; import { TopicsService } from '../../api/api/topics.service'; import { Subject, of } from 'rxjs'; import { @@ -53,6 +54,7 @@ interface FlatTopic { MatCheckboxModule, MatIconModule, MatProgressSpinnerModule, + MatRadioModule, ], templateUrl: './topic-hierarchy.component.html', styleUrl: './topic-hierarchy.component.scss', @@ -80,38 +82,47 @@ export class TopicHierarchyComponent implements OnInit { flatTopics: FlatTopic[] = []; filteredFlatTopics: FlatTopic[] = []; loading = signal(true); + searchType = signal<'hybrid' | 'semantic'>('hybrid'); // Set of names of expanded nodes (lazy content rendering) expandedDomains = new Set(); expandedFields = new Set(); expandedSubfields = new Set(); - private readonly searchSubject = new Subject(); + private readonly searchSubject = new Subject<{ + query: string; + searchType: 'hybrid' | 'semantic'; + }>(); constructor(private topicsService: TopicsService) { this.searchSubject .pipe( debounceTime(300), - distinctUntilChanged(), - switchMap((query) => { + distinctUntilChanged( + (prev, curr) => + prev.query === curr.query && prev.searchType === curr.searchType, + ), + switchMap(({ query, searchType }) => { if (!query) { this.filteredFlatTopics = []; return of({ results: [] }); } this.loading.set(true); - return this.topicsService.vectorSearchTopics(query, 50).pipe( - catchError((err) => { - console.error('Error in semantic topic search:', err); - // Fallback to local filtering - const q = query.toLowerCase(); - this.filteredFlatTopics = this.flatTopics.filter( - (t) => - t.name.toLowerCase().includes(q) || - t.path.toLowerCase().includes(q), - ); - return of({ results: [] }); - }), - ); + return this.topicsService + .vectorSearchTopics(query, 50, searchType) + .pipe( + catchError((err) => { + console.error('Error in semantic topic search:', err); + // Fallback to local filtering + const q = query.toLowerCase(); + this.filteredFlatTopics = this.flatTopics.filter( + (t) => + t.name.toLowerCase().includes(q) || + t.path.toLowerCase().includes(q), + ); + return of({ results: [] }); + }), + ); }), ) .subscribe((response) => { @@ -175,7 +186,15 @@ export class TopicHierarchyComponent implements OnInit { this.filteredFlatTopics = []; return; } - this.searchSubject.next(this.searchQuery); + this.searchSubject.next({ + query: this.searchQuery, + searchType: this.searchType(), + }); + } + + onSearchTypeChange(type: 'hybrid' | 'semantic'): void { + this.searchType.set(type); + this.filterFlatTopics(); } toggleTopic(name: string): void { From 5b37115e46e4e1eb744f1daedb3f145928d1c704 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 21 Jun 2026 12:36:36 +0200 Subject: [PATCH 18/53] changed logic of semantic and hybrid query. Tested different boostings --- service/src/main/inse/topics/logic.py | 106 ++++++++++++++++---------- 1 file changed, 66 insertions(+), 40 deletions(-) diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index adc56a7a..94646f16 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -256,10 +256,19 @@ def _datetime_str_or_none(value: Any) -> str | None: return f"{text}T00:00:00Z" return text +# Configuration for vector search similarity thresholds and boosts +SIMILARITY_THRESHOLD = 0.62 +BOOST_LEXICAL = 1.0 +# higher values for semantic weights, because cosine similarity is between 0 and 1 +BOOST_DISPLAY_NAME_VECTOR = 30.0 +BOOST_DESCRIPTION_VECTOR = 15.0 +BOOST_KEYWORD_VECTORS = 25.0 + async def vector_search_topics( *, query: str, limit: int = 25, + search_type: str = "hybrid", ) -> TopicsListResponse: """ Perform a semantic similarity search on the topicvectors index. @@ -287,53 +296,70 @@ async def vector_search_topics( ) # 2. Query Elasticsearch using standard Bool Should hybrid search + should_clauses = [] + + # Lexical multi_match search (only in hybrid mode) + if search_type == "hybrid": + should_clauses.append({ + "multi_match": { + "query": query, + "fields": [ + "display_name^3", + "keywords^2", + "description^1" + ], + "boost": BOOST_LEXICAL + } + }) + + # Semantic KNN clauses + should_clauses.extend([ + { + "knn": { + "field": "display_name_vector", + "query_vector": query_vector, + "k": limit, + "num_candidates": 100, + "similarity": SIMILARITY_THRESHOLD, + "boost": BOOST_DISPLAY_NAME_VECTOR + } + }, + { + "knn": { + "field": "description_vector", + "query_vector": query_vector, + "k": limit, + "num_candidates": 100, + "similarity": SIMILARITY_THRESHOLD, + "boost": BOOST_DESCRIPTION_VECTOR + } + }, + { + "nested": { + "path": "keyword_vectors", + "query": { + "knn": { + "field": "keyword_vectors.vector", + "query_vector": query_vector, + "k": limit, + "num_candidates": 100, + "similarity": SIMILARITY_THRESHOLD + } + }, + "score_mode": "max", + "boost": BOOST_KEYWORD_VECTORS + } + } + ]) body = { "query": { "bool": { - "should": [ - { - "multi_match": { - "query": query, - "fields": [ - "display_name^3", - "keywords^2", - "description^1" - ], - "boost": 1.0 - } - }, - { - "knn": { - "field": "display_name_vector", - "query_vector": query_vector, - "k": limit, - "num_candidates": 100, - "similarity": 0.62, - "boost": 2.0 - } - }, - { - "nested": { - "path": "description_vectors", - "query": { - "knn": { - "field": "description_vectors.vector", - "query_vector": query_vector, - "k": limit, - "num_candidates": 100, - "similarity": 0.62 - } - }, - "score_mode": "max", - "boost": 1.0 - } - } - ] + "should": should_clauses } }, "_source": { - "excludes": ["display_name_vector", "description_vectors", "description", "siblings"] # remove unrequired fields (description, sibling currently not needed) + "excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"] # remove unrequired fields }, "size": limit } From 84f3314b60305f827f80dae21c44d33accc275e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 14:07:39 +0200 Subject: [PATCH 19/53] Fixed institution cordis eu funding amount to show the amount actually received not total for project --- .../main/inse/integrations/elasticsearch.py | 51 +++- service/src/main/inse/model.py | 27 ++- service/src/main/inse/projects/model.py | 64 +++++ .../inse/projects/projects_search_client.py | 222 +++++++++++++++++- service/src/main/inse/projects/router.py | 8 +- service/src/main/inse/projects/service.py | 72 +++--- ude_person.http | 50 +++- webapp/src/app/api/.openapi-generator/FILES | 2 + webapp/src/app/api/api/projects.service.ts | 10 +- .../api/model/euOrganizationProjectSummary.ts | 27 +++ .../model/euOrganizationProjectSummaryPage.ts | 31 +++ webapp/src/app/api/model/models.ts | 2 + .../institution-projects.component.html | 16 +- .../institution-projects.component.ts | 41 +++- .../cordis-eu-project-page.resolver.ts | 4 +- 15 files changed, 543 insertions(+), 84 deletions(-) create mode 100644 webapp/src/app/api/model/euOrganizationProjectSummary.ts create mode 100644 webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 449b748f..bd32501a 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,16 +1,18 @@ import logging from typing import Any, Dict, List, Optional, Tuple import httpx + +from inse.model import ESCluster, ESIndex from .. import config logger = logging.getLogger(__name__) -def _cluster_credentials(cluster: str) -> Tuple[str, str]: +def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: """Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration. Args: - cluster (str): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse". + cluster (ElasticsearchCluster): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse". Raises: ValueError: If the cluster is unknown or the credentials are not set in the configuration. @@ -19,7 +21,7 @@ def _cluster_credentials(cluster: str) -> Tuple[str, str]: Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster. """ - if cluster == "nes": + if cluster == ESCluster.NES: if ( not config.settings.elasticsearch_url or not config.settings.elasticsearch_api_key @@ -28,7 +30,7 @@ def _cluster_credentials(cluster: str) -> Tuple[str, str]: "Elasticsearch URL and API key must be set in the configuration for cluster 'nes'" ) return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key - elif cluster == "inse": + elif cluster == ESCluster.INSE: if ( not config.settings.elasticsearch_inse_url or not config.settings.elasticsearch_inse_api_key @@ -45,8 +47,37 @@ def _cluster_credentials(cluster: str) -> Tuple[str, str]: raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')") +def _index_to_cluster(index: ESIndex) -> ESCluster: + """Determines the Elasticsearch cluster to use based on the specified index. + + Args: + index (ESIndex): The Elasticsearch index for which to determine the cluster. Allowed values are defined in the ESIndex enum. + + Raises: + ValueError: If the index is unknown. + + Returns: + ESCluster: The Elasticsearch cluster to use for the specified index. + """ + + if index in { + ESIndex.OPENALEX_WORKS, + ESIndex.OPENALEX_AUTHORS, + ESIndex.OPENALEX_INSTITUTIONS, + ESIndex.OPENALEX_PUBLICATIONS, + }: + return ESCluster.NES + elif index in { + ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + }: + return ESCluster.INSE + else: + raise ValueError(f"Unknown index: {index!r}") + + def search( - index: str, + index: ESIndex, query_field: Optional[str] = None, query_value: Optional[str] = None, query: Optional[Dict] = None, @@ -56,12 +87,12 @@ def search( sort: Optional[List] = None, body: Optional[Dict] = None, track_total_hits=False, - cluster: str = "nes", + cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: """Searches the specified Elasticsearch index using either a simple query string or a full query body. Args: - index (str): The name of the Elasticsearch index to search. + index (ElasticsearchIndex): The Elasticsearch index to search. query_field (Optional[str], optional): The field to search in. Defaults to None. query_value (Optional[str], optional): The value to search for. Defaults to None. query (Optional[Dict], optional): The full query body. Defaults to None. @@ -71,7 +102,7 @@ def search( sort (Optional[List], optional): The fields to sort by. Defaults to None. body (Optional[Dict], optional): The full query body. Defaults to None. track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False. - cluster (str, optional): The Elasticsearch cluster to search. Defaults to "nes". + cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES. Returns: Dict[str, Any]: The search results. @@ -116,10 +147,10 @@ def search( def get( - index: str, + index: ESIndex, doc_id: str, source: Optional[list] = None, - cluster: str = "nes", + cluster: ESCluster = ESCluster.NES, ) -> dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 669f049f..55d556eb 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -1,9 +1,12 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ - This module defines the model classes returned from - our api using pydantic. +This module defines the model classes returned from +our api using pydantic. """ + +from enum import StrEnum + from pydantic import BaseModel from pydantic import ConfigDict from pydantic import Field @@ -13,28 +16,46 @@ from typing import Generic from typing import Optional -T = TypeVar('T', bound=BaseModel) +T = TypeVar("T", bound=BaseModel) + class Entity(BaseModel): id: int = Field(description="The id of the entity.") + class Item(Entity): model_config = ConfigDict(from_attributes=True) name: str = Field(description="The name of the item.") description: str = Field(description="The description of the item.") + class ItemCreate(BaseModel): name: str = Field(description="The name of the item.") description: str = Field(description="The description of the item.") + class Page(BaseModel, Generic[T]): elements: List[T] = Field(default=[], description="The elements of the page.") offset: int = Field(default=0, description="The page offset in elements.") total: int = Field(default=0, description="The total number of elements.") size: int = Field(default=20, description="The page size in elements.") + class ItemPage(Page[Item]): pass +class ESCluster(StrEnum): + NES = "nes" + INSE = "inse" + +class ESIndex(StrEnum): + OPENALEX_WORKS = "openalex-works" + OPENALEX_AUTHORS = "openalex-authors" + OPENALEX_INSTITUTIONS = "openalex-institutions" + OPENALEX_PUBLICATIONS = "openalex-publications" + + CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" + CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" + CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index dd75726f..ed58fe8e 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -22,6 +22,15 @@ class ProjectsSortBy(StrEnum): FUNDING_END = "funding_end" FUNDING_AMOUNT = "funding_amount" + def to_cordis_eu_project_sort_field(self) -> str: + mapping = { + self.TITLE: "title.keyword", + self.FUNDING_START: "startDate", + self.FUNDING_END: "endDate", + self.FUNDING_AMOUNT: "ecMaxContribution", + } + return mapping.get(self, "title.keyword") + class SortDirection(StrEnum): ASC = "asc" @@ -225,3 +234,58 @@ class FundingProjectPage(Page): elements: List[FundingProject] = Field( default_factory=list, description="The funding projects on this page." ) + + +class EuOrganizationShort(BaseModel): + project_id: str = Field(description="The unique identifier of the project.") + organization_id: str = Field( + description="The unique identifier of the organization." + ) + ec_contribution: Optional[float] = Field( + default=None, + description="The EC contribution amount for the organization in the project.", + ) + + +class EuProjectShort(BaseModel): + id: str = Field(description="The unique identifier of the EU project.") + title: Optional[str] = Field( + default=None, description="The title of the EU project." + ) + start_date: Optional[date] = Field( + default=None, description="The funding start date of the EU project." + ) + end_date: Optional[date] = Field( + default=None, description="The funding end date of the EU project." + ) + acronym: Optional[str] = Field( + default=None, description="The acronym of the EU project." + ) + + +class EuOrganizationProjectSummary(BaseModel): + organization_id: str = Field( + description="The unique identifier of the organization." + ) + project_id: str = Field(description="The unique identifier of the project.") + title: Optional[str] = Field(default=None, description="The title of the project.") + start_date: Optional[date] = Field( + default=None, description="The funding start date of the project." + ) + end_date: Optional[date] = Field( + default=None, description="The funding end date of the project." + ) + acronym: Optional[str] = Field( + default=None, description="The acronym of the project." + ) + ec_contribution: Optional[float] = Field( + default=None, + description="The EC contribution amount for the organization in the project.", + ) + + +class EuOrganizationProjectSummaryPage(Page): + elements: List[EuOrganizationProjectSummary] = Field( + default_factory=list, + description="The organization project summaries on this page.", + ) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3347fc3c..d11dd659 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -1,6 +1,6 @@ import json import logging -from typing import Any, Dict, List, Optional, Set +from typing import Any, Dict, List, Optional, Set, Tuple import httpx @@ -11,7 +11,10 @@ from inse.projects.model import ( CordisEuProjectPage, DfgProjectPage, DfgProjectSummary, - EuProjectPage, + EuOrganizationProjectSummary, + EuOrganizationProjectSummaryPage, + EuOrganizationShort, + EuProjectShort, FundingProject, FundingProjectPage, ProjectType, @@ -19,11 +22,12 @@ from inse.projects.model import ( ProjectsSortBy, SortDirection, ) -from inse.models.eu_project import EuProject + from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex settings = get_settings() @@ -494,7 +498,9 @@ class EuProjectsSearchClient(ProjectsSearchClient): query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} response = elasticsearch.search( - query=query, index="cordis_eu_*_publications", cluster="inse" + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, ) logger.debug( @@ -528,7 +534,9 @@ class EuProjectsSearchClient(ProjectsSearchClient): query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} response = elasticsearch.search( - query=query, index="cordis_eu_*_projects", cluster="inse" + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, ) hits_block = response.get("hits", {}) @@ -903,3 +911,207 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: raise ValueError( "The provided hit does not belong to a recognized project index." ) + + +def get_organization_project_contributions_foo( + organization_names: List[str], + projects_filtering_properties: ProjectsFilteringProperties, +) -> EuOrganizationProjectSummaryPage: + # Pagination depending on sorting criteria + # For FUNDING_AMOUNT before on the organization project contributions + # For the rest after the contributions are known on the real projects + + organization_project_contributions = get_organization_project_contributions( + organization_names=organization_names, + ) + + total_projects, projects = get_projects( + project_contributions=list(organization_project_contributions.values()), + projects_filtering_properties=projects_filtering_properties, + ) + + elements: List[EuOrganizationProjectSummary] = _merge_project_data( + projects=projects, contributions=organization_project_contributions + ) + + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + elements.sort( + key=lambda x: x.ec_contribution or 0, + reverse=projects_filtering_properties.sort_direction == SortDirection.DESC, + ) + start = projects_filtering_properties.page * projects_filtering_properties.size + end = start + projects_filtering_properties.size + elements = elements[start:end] + + return EuOrganizationProjectSummaryPage( + elements=elements, + total=total_projects, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, + ) + + +def get_organization_project_contributions( + organization_names: List[str], +) -> Dict[str, EuOrganizationShort]: + + source = ["projectID", "organisationID", "ecContribution"] + + query = { + "terms": { + "name.keyword": [ + name.upper() for name in organization_names if name.strip() + ], + } + } + + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + size=10000, + query=query, + ) + + logger.debug( + f"Received organization project contributions response: {json.dumps(response, indent=2)}" + ) + + organization_project_contributions = _process_organization_project_contributions( + response + ) + + logger.debug( + f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}" + ) + + return organization_project_contributions + + +def _process_organization_project_contributions( + response: Dict[str, Any], +) -> Dict[str, EuOrganizationShort]: + hits_block = response.get("hits", {}) + project_contributions: Dict[str, EuOrganizationShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + organization_id = source.get("organisationID") + ec_contribution = source.get("ecContribution") + if project_id and organization_id: + project_contributions[project_id] = EuOrganizationShort( + project_id=project_id, + organization_id=organization_id, + ec_contribution=ec_contribution, + ) + return project_contributions + + +def get_projects( + project_contributions: List[EuOrganizationShort], + projects_filtering_properties: ProjectsFilteringProperties, +) -> Tuple[int, Dict[str, EuProjectShort]]: + project_ids = [contribution.project_id for contribution in project_contributions] + + source = ["id", "title", "startDate", "endDate", "acronym"] + + query = { + "terms": { + "id": project_ids, + } + } + + if ( + projects_filtering_properties.query + and projects_filtering_properties.query.strip() + ): + query = { + "bool": { + "must": [ + { + "match_phrase_prefix": { + "title": { + "query": projects_filtering_properties.query, + "max_expansions": 50, + } + } + } + ], + "filter": query, + } + } + + # Project contributions have been filtered before based on ecContribution + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=10000, + ) + else: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=projects_filtering_properties.size, + offset=projects_filtering_properties.page + * projects_filtering_properties.size, + sort=[ + { + projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): { + "order": projects_filtering_properties.sort_direction + } + } + ], + ) + + return _process_projects_response(response) + + +def _process_projects_response( + response: Dict[str, Any], +) -> Tuple[int, Dict[str, EuProjectShort]]: + hits_block = response.get("hits", {}) + total = hits_block.get("total", {}).get("value", 0) + projects: Dict[str, EuProjectShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("id") + title = source.get("title") + start_date = source.get("startDate") + end_date = source.get("endDate") + acronym = source.get("acronym") + if not project_id: + continue + projects[project_id] = EuProjectShort( + id=project_id, + title=title, + start_date=start_date, + end_date=end_date, + acronym=acronym, + ) + + return total, projects + + +def _merge_project_data( + projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort] +) -> List[EuOrganizationProjectSummary]: + merged_data = [] + for project_id, project_info in projects.items(): + contribution_info = contributions.get(project_id) + if contribution_info: + merged_entry = EuOrganizationProjectSummary( + project_id=project_id, + title=project_info.title, + start_date=project_info.start_date, + end_date=project_info.end_date, + acronym=project_info.acronym, + organization_id=contribution_info.organization_id, + ec_contribution=contribution_info.ec_contribution, + ) + merged_data.append(merged_entry) + return merged_data diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 7d6e45f9..568abeae 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -8,6 +8,7 @@ from inse.projects.model import ( BundProjectPage, CordisEuProjectPage, DfgProjectPage, + EuOrganizationProjectSummaryPage, FundingProjectPage, InstitutionFunderSummary, ProjectType, @@ -211,7 +212,7 @@ async def get_institution_bund_projects_funding_over_time( responses={ status.HTTP_200_OK: { "description": "Successful Response", - "model": CordisEuProjectPage, + "model": EuOrganizationProjectSummaryPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, }, @@ -226,9 +227,8 @@ async def search_cordis_eu_projects( ProjectsFilteringProperties, Body(description="The filtering properties for the projects search."), ], -) -> CordisEuProjectPage: - return await projects_service.search_cordis_eu_projects( - eu_search_client=eu_search_client, +) -> EuOrganizationProjectSummaryPage: + return projects_service.search_cordis_eu_projects( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 9dde9e87..a725f0fa 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -7,12 +7,13 @@ from inse.projects.projects_search_client import ( CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, + get_organization_project_contributions_foo, ) from inse.projects.model import ( BundProjectPage, CordisEuProjectPage, DfgProjectPage, - EuProjectPage, + EuOrganizationProjectSummaryPage, FundingProjectPage, InstitutionFunderSummary, ProjectType, @@ -99,28 +100,25 @@ async def get_bund_projects_by_institution_id( return response -async def search_cordis_eu_projects( - eu_search_client: EuProjectsSearchClient, +def search_cordis_eu_projects( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, -) -> CordisEuProjectPage: +) -> EuOrganizationProjectSummaryPage: if projects_filtering_properties.project_type != "eu": raise ValueError( f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'." ) - return await get_cordis_eu_projects_by_institution_id( - eu_search_client=eu_search_client, + return get_cordis_eu_projects_by_institution_id( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) -async def get_cordis_eu_projects_by_institution_id( - eu_search_client: EuProjectsSearchClient, +def get_cordis_eu_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, -) -> CordisEuProjectPage: +) -> EuOrganizationProjectSummaryPage: if not projects_filtering_properties.raw_oa_institution_id: raise ValueError( "raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID" @@ -138,28 +136,14 @@ async def get_cordis_eu_projects_by_institution_id( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - institution_eu_organisation_ids = ( - institutions_search_client.get_cordis_eu_organisation_ids_by_oa_institution_id( - projects_filtering_properties.raw_oa_institution_id - ) - ) - if not institution_eu_organisation_ids: - logger.debug( - f"No EU organization IDs found for institution_id={projects_filtering_properties.raw_oa_institution_id}" - ) - return CordisEuProjectPage( - elements=[], - total=0, - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - - cordis_eu_project_page = await eu_search_client.search_eu_projects( - eu_organisation_ids=institution_eu_organisation_ids, + page = get_organization_project_contributions_foo( + organization_names=institution_aliases, projects_filtering_properties=projects_filtering_properties, ) - return cordis_eu_project_page + logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}") + + return page async def get_dfg_projects_by_author_id( @@ -199,12 +183,26 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id: str, ) -> InstitutionFunderSummary: - cordis_eu_project_page = await search_cordis_eu_projects( - eu_search_client, - institutions_search_client, - ProjectsFilteringProperties( + # cordis_eu_project_page = await search_cordis_eu_projects( + # eu_search_client, + # institutions_search_client, + # ProjectsFilteringProperties( + # project_type=ProjectType.EU, + # raw_oa_institution_id=raw_oa_institution_id, + # page=0, + # size=10000, + # ), + # ) + + institution_aliases = ( + institutions_search_client.get_institution_aliases_by_oa_institution_id( + raw_oa_institution_id + ) + ) + page = get_organization_project_contributions_foo( + organization_names=institution_aliases, + projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, - raw_oa_institution_id=raw_oa_institution_id, page=0, size=10000, ), @@ -212,10 +210,10 @@ async def get_institution_cordis_eu_projects_funding_over_time( return _calculate_funding_over_time( project_type=ProjectType.EU, - projects=cordis_eu_project_page.elements, - funding_start_attr="startDate", - funding_end_attr="endDate", - funding_amount_attr="totalCost", + projects=page.elements, + funding_start_attr="start_date", + funding_end_attr="end_date", + funding_amount_attr="ec_contribution", ) diff --git a/ude_person.http b/ude_person.http index f4691a10..9354020f 100644 --- a/ude_person.http +++ b/ude_person.http @@ -161,6 +161,26 @@ GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json +{ + "size": 1000, + "query": { + "bool": { + "filter": [ + { + "term": { + "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" + } + } + ] + } + } +} + +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + { "size": 0, "query": { @@ -183,26 +203,38 @@ Content-Type: application/json } } +### +GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_mapping +Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +Content-Type: application/json + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== Content-Type: application/json { - "size": 10, "query": { - "bool": { - "filter": [ - { - "term": { - "name.keyword": "UNIVERSITAET DUISBURG-ESSEN" - } - } + "terms": { + "name": [ + "UNIVERSITÄT DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG-ESSEN", + "UNIVERSITAT DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG ESSEN", + "UNIVERSITAT DUISBURG-ESSEN", + "UNIVERSITAET DUISBURG ESSEN", + "UNIVERSITÄT DUISBURG ESSEN", + "UNIVERSITAT DUISBURG ESSEN", + "UNIVERSITÄT DUISBURG-ESSEN", + "UNIVERSITAET DUISBURG-ESSEN", + "UNIVERSITY OF DUISBURG-ESSEN" ] } - } + }, + "_source": ["projectID", "organisationID", "ecContribution"] } + ### GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index a8e4f29f..d188cd69 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -59,6 +59,8 @@ model/dehydratedSource.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/euOrganizationProjectSummary.ts +model/euOrganizationProjectSummaryPage.ts model/filterInformation.ts model/filterProperties.ts model/funderByAuthor.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index b3b91911..9edfb7fe 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -27,6 +27,8 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails'; // @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore +import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage'; +// @ts-ignore import { FundingProjectPage } from '../model/fundingProjectPage'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -497,9 +499,9 @@ export class ProjectsService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) { throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.'); @@ -541,7 +543,7 @@ export class ProjectsService extends BaseService { let localVarPath = `/api/projects/institution/eu/search`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: projectsFilteringProperties, diff --git a/webapp/src/app/api/model/euOrganizationProjectSummary.ts b/webapp/src/app/api/model/euOrganizationProjectSummary.ts new file mode 100644 index 00000000..3cc10f0a --- /dev/null +++ b/webapp/src/app/api/model/euOrganizationProjectSummary.ts @@ -0,0 +1,27 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface EuOrganizationProjectSummary { + /** + * The unique identifier of the organization. + */ + organization_id: string; + /** + * The unique identifier of the project. + */ + project_id: string; + title?: string | null; + start_date?: string | null; + end_date?: string | null; + acronym?: string | null; + ec_contribution?: number | null; +} + diff --git a/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts b/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts new file mode 100644 index 00000000..9d57d5b4 --- /dev/null +++ b/webapp/src/app/api/model/euOrganizationProjectSummaryPage.ts @@ -0,0 +1,31 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary'; + + +export interface EuOrganizationProjectSummaryPage { + /** + * The current page number. + */ + page?: number; + /** + * The requested page size. + */ + size?: number; + /** + * The total number of items. + */ + total?: number; + /** + * The organization project summaries on this page. + */ + elements?: Array; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 60006d17..0dd39ede 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -38,6 +38,8 @@ export * from './dehydratedSource'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './euOrganizationProjectSummary'; +export * from './euOrganizationProjectSummaryPage'; export * from './filterInformation'; export * from './filterProperties'; export * from './funderByAuthor'; diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index e4982ec6..ce7c7648 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -75,7 +75,9 @@ undefined " /> + open_in_new + + + + + open_in_new + + diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index 4f547c61..42631284 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -8,12 +8,12 @@ import { TemplateRef, viewChild, } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { BundProject, BundProjectPage, - CordisEuProject, - CordisEuProjectPage, + EuOrganizationProjectSummary, + EuOrganizationProjectSummaryPage, InstitutionFunderSummary, } from '../../api'; import { MatCardModule } from '@angular/material/card'; @@ -36,6 +36,7 @@ import { InstitutionProjectsFundingGraphComponent } from '../institution-project import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; type BundProjectRow = { + id: string; topic: string; funding_start: Date; funding_end: Date; @@ -44,6 +45,7 @@ type BundProjectRow = { }; type EuProjectRow = { + id: string; topic: string; funding_start: Date; funding_end: Date; @@ -67,6 +69,7 @@ type EuProjectRow = { MatButtonModule, InstitutionProjectsFundingGraphComponent, PersonNetworkInfoCardComponent, + RouterModule, ], templateUrl: './institution-projects.component.html', styleUrl: './institution-projects.component.scss', @@ -76,13 +79,19 @@ export class InstitutionProjectsComponent implements OnInit { fundingEndTmp = viewChild.required>('fundingEndTmp'); fundingAmountTmp = viewChild.required>('fundingAmountTmp'); - cordisEuProjectPage = input.required(); + cordisEuProjectPage = input.required(); euProjectColumns: GenericColumn[] = []; euProjectData: EuProjectRow[] = []; + euProjectActionsTmp = viewChild.required>( + 'euProjectActionsTmp', + ); bundProjectPage = input.required(); bundProjectColumns: GenericColumn[] = []; bundProjectData: BundProjectRow[] = []; + bundProjectActionsTmp = viewChild.required>( + 'bundProjectActionsTmp', + ); bundProjectsFunding = input.required(); bundTotalFunding = computed(() => { @@ -221,6 +230,12 @@ export class InstitutionProjectsComponent implements OnInit { accessorKey: 'funding_amount', cellTemplate: this.fundingAmountTmp(), }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.euProjectActionsTmp(), + }, ]; this.bundProjectColumns = [ { @@ -250,22 +265,30 @@ export class InstitutionProjectsComponent implements OnInit { accessorKey: 'funding_amount', cellTemplate: this.fundingAmountTmp(), }, + { + id: 'actions', + header: '', + type: 'display', + cellTemplate: this.bundProjectActionsTmp(), + }, ]; } - transformEuRow(project: CordisEuProject): EuProjectRow { + transformEuRow(project: EuOrganizationProjectSummary): EuProjectRow { return { + id: project.project_id, topic: project.title || '', - funding_start: project.startDate - ? new Date(project.startDate) + funding_start: project.start_date + ? new Date(project.start_date) : new Date(0), - funding_end: project.endDate ? new Date(project.endDate) : new Date(0), - funding_amount: Number(project.totalCost) || 0, + funding_end: project.end_date ? new Date(project.end_date) : new Date(0), + funding_amount: Number(project.ec_contribution) || 0, }; } transformBundRow(project: BundProject): BundProjectRow { return { + id: project.funding_code || '', topic: project.topic || '', funding_start: project.funding_start ? new Date(project.funding_start) diff --git a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts index 2508fa68..b6a9cfb5 100644 --- a/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts +++ b/webapp/src/app/resolvers/cordis-eu-project-page.resolver.ts @@ -1,13 +1,13 @@ import { ResolveFn } from '@angular/router'; import { - CordisEuProjectPage, + EuOrganizationProjectSummaryPage, ProjectsService, ProjectsSortBy, SortDirection, } from '../api'; import { inject } from '@angular/core'; -export const cordisEuProjectPageResolver: ResolveFn = ( +export const cordisEuProjectPageResolver: ResolveFn = ( route, state, ) => { From 9cd109fc1717aeeed968940096a727dea2ce08e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 14:44:21 +0200 Subject: [PATCH 20/53] Moved all projects search client out of class --- .../main/inse/integrations/elasticsearch.py | 58 ++++-- service/src/main/inse/model.py | 3 + service/src/main/inse/persons/logic.py | 31 +-- service/src/main/inse/projects/model.py | 25 +++ .../inse/projects/projects_search_client.py | 182 +++++++----------- service/src/main/inse/projects/router.py | 14 +- service/src/main/inse/projects/service.py | 21 +- 7 files changed, 171 insertions(+), 163 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index bd32501a..00f9d241 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -47,7 +47,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')") -def _index_to_cluster(index: ESIndex) -> ESCluster: +def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: """Determines the Elasticsearch cluster to use based on the specified index. Args: @@ -68,18 +68,19 @@ def _index_to_cluster(index: ESIndex) -> ESCluster: }: return ESCluster.NES elif index in { + ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, ESIndex.CORDIS_EU_PROJECTS_WILDCARD, ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + ESIndex.PROJECTS_BUND_V1, + ESIndex.PROJECTS_DFG_ALL, }: return ESCluster.INSE else: - raise ValueError(f"Unknown index: {index!r}") + return None def search( - index: ESIndex, - query_field: Optional[str] = None, - query_value: Optional[str] = None, + index: ESIndex | List[ESIndex], query: Optional[Dict] = None, source: Optional[List] = None, size: Optional[int] = None, @@ -93,8 +94,6 @@ def search( Args: index (ElasticsearchIndex): The Elasticsearch index to search. - query_field (Optional[str], optional): The field to search in. Defaults to None. - query_value (Optional[str], optional): The value to search for. Defaults to None. query (Optional[Dict], optional): The full query body. Defaults to None. source (Optional[List], optional): The fields to include in the response. Defaults to None. size (Optional[int], optional): The maximum number of results to return. Defaults to None. @@ -108,16 +107,35 @@ def search( Dict[str, Any]: The search results. """ + clusters = set() + if isinstance(index, list): + for idx in index: + cluster_for_index = _index_to_cluster(idx) + if cluster_for_index is not None: + clusters.add(cluster_for_index) + else: + cluster_for_index = _index_to_cluster(index) + if cluster_for_index is not None: + clusters.add(cluster_for_index) + + if len(clusters) > 1: + raise ValueError( + f"All indices in the search request must belong to the same cluster, but found clusters: {clusters}" + ) + elif len(clusters) == 1: + cluster = clusters.pop() + elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - payload: Dict[str, Any] + payload: Dict[str, Any] = {} if body is not None: payload = body - elif query is not None: - payload = {"query": query} + else: + if query is not None: + payload["query"] = query if source is not None: payload["_source"] = source if size is not None: @@ -128,19 +146,23 @@ def search( payload["sort"] = sort if track_total_hits: payload["track_total_hits"] = True - else: - payload = { - "query": { - "query_string": {"default_field": query_field, "query": query_value} - } - } + + if len(payload) == 0: + raise ValueError( + "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided" + ) with httpx.Client(timeout=httpx.Timeout(30.0)) as client: logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} with payload: {payload}" + f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {payload}" ) + if isinstance(index, list): + index_str = ",".join(index) + else: + index_str = index + response = client.post( - f"{elasticsearch_url}/{index}/_search", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers ) response.raise_for_status() return response.json() diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 55d556eb..fd06db11 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -59,3 +59,6 @@ class ESIndex(StrEnum): CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" + + PROJECTS_BUND_V1 = "projects_bund_v1" + PROJECTS_DFG_ALL = "projects_dfg_all" \ No newline at end of file diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 76db43c7..ca1e09e5 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -13,6 +13,8 @@ from elasticsearch import ApiError, NotFoundError import hashlib import httpx from fastapi import HTTPException + +from inse.model import ESIndex from .. import config from .. import util from ..integrations import llm @@ -28,6 +30,7 @@ from inse.persons.model import ( PersonSearchRequest, CareerMetrics, ) + logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" @@ -55,20 +58,26 @@ def get_author_name_by_id(author_id: str) -> Optional[str]: def search_persons( author_id: Optional[str] = None, query: Optional[str] = None, - include: Optional[set[str]] = None, ) -> AuthorsListResponse: if author_id: - query_field = "_id" - query_value = author_id + query_ = { + "query_string": { + "default_field": "_id", + "query": author_id, + } + } + elif query: - query_field = "display_name" - query_value = query + query_ = { + "query_string": { + "default_field": "display_name", + "query": query, + } + } else: return AuthorsListResponse(results=[], meta=Meta(count=0)) - data = elasticsearch.search( - index="openalex-authors", query_field=query_field, query_value=query_value - ) + data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_) authors = [] for hit in data.get("hits", {}).get("hits", []): @@ -221,9 +230,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: ) buckets = ( - response.get("aggregations", {}) - .get("publication_years", {}) - .get("buckets", []) + response.get("aggregations", {}).get("publication_years", {}).get("buckets", []) ) publication_years: list[int] = [] @@ -237,6 +244,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: return publication_years + def _classify_career_stage(active_years: int) -> str: if active_years <= 0: return "unknown" @@ -399,7 +407,6 @@ def get_person_by_id( return CustomAuthorsListResponse(results=[custom_author]) - def search_persons_by_name( author_name: str, limit: Optional[int] = 10, diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index ed58fe8e..d0957d4d 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -8,6 +8,7 @@ from pydantic import BaseModel, Field, field_validator from inse.models.bund_project import BundProject from inse.models.eu_project import EuProject from inse.models.cordis_eu_project import CordisEuProject +from inse.model import ESIndex class ProjectType(StrEnum): @@ -15,6 +16,17 @@ class ProjectType(StrEnum): EU = "eu" DFG = "dfg" + def to_es_index(self) -> ESIndex: + mapping = { + self.BUND: ESIndex.PROJECTS_BUND_V1, + self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + self.DFG: ESIndex.PROJECTS_DFG_ALL, + } + index = mapping.get(self) + if index is None: + raise ValueError(f"Unsupported project type: {self}") + return index + class ProjectsSortBy(StrEnum): TITLE = "title" @@ -31,6 +43,15 @@ class ProjectsSortBy(StrEnum): } return mapping.get(self, "title.keyword") + def to_bund_project_sort_field(self) -> str: + mapping = { + self.TITLE: "Thema.keyword", + self.FUNDING_START: "funding_start", + self.FUNDING_END: "funding_end", + self.FUNDING_AMOUNT: "Fördersumme", + } + return mapping.get(self, "Thema.keyword") + class SortDirection(StrEnum): ASC = "asc" @@ -151,6 +172,9 @@ class FundingProject(BaseModel): ) id: str = Field(description="The unique identifier of the project.") title: Optional[str] = Field(default=None, description="The title of the project.") + acronym: Optional[str] = Field( + default=None, description="The acronym of the project (if available)." + ) start_date: Optional[date] = Field( default=None, description="The funding start date of the project." ) @@ -227,6 +251,7 @@ class FundingProject(BaseModel): title=source.get("title"), start_date=source.get("funding_start"), end_date=source.get("funding_end"), + acronym=source.get("acronym"), ) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index d11dd659..ed62e84b 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -145,16 +145,6 @@ class BundProjectsSearchClient(ProjectsSearchClient): api_key=settings.elasticsearch_inse_api_key, ) - def _bund_projects_sort_by_field(self, sort_by: ProjectsSortBy) -> str: - if sort_by == ProjectsSortBy.TITLE: - return "Thema.keyword" - elif sort_by == ProjectsSortBy.FUNDING_START: - return "funding_start" - elif sort_by == ProjectsSortBy.FUNDING_END: - return "funding_end" - elif sort_by == ProjectsSortBy.FUNDING_AMOUNT: - return "Fördersumme" - def _bund_projects_query( self, page: int, @@ -210,7 +200,7 @@ class BundProjectsSearchClient(ProjectsSearchClient): query["query"] = {"match_all": {}} query["sort"] = [ - {self._bund_projects_sort_by_field(sort_by): {"order": sort_direction}} + {sort_by.to_bund_project_sort_field(): {"order": sort_direction}} ] query_str = json.dumps(query, indent=2) @@ -781,112 +771,80 @@ class DfgProjectsSearchClient(ProjectsSearchClient): return None -class CompleteProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="cordis_eu_*_projects,projects_bund_v1,projects_dfg_all", - api_key=settings.elasticsearch_inse_api_key, +def search_all_projects( + projects_filtering_properties: ProjectsFilteringProperties, + selected_project_types: Optional[Set[ProjectType]] = None, +): + sort_by = projects_filtering_properties.sort_by + if sort_by != ProjectsSortBy.TITLE: + raise ValueError( + "Currently only sorting by title is supported across all project types." ) - def _build_projects_search_body( - self, - page: int, - size: int, - title: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ) -> Dict[str, Any]: - if sort_by != ProjectsSortBy.TITLE: - raise ValueError("Currently only sorting by title is supported.") + sort_direction = projects_filtering_properties.sort_direction + sort = [ + { + "title.keyword": { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword", + } + }, + { + "Thema.keyword": { + "order": sort_direction, + "missing": "_last", + "unmapped_type": "keyword", + } + }, + ] - query: Dict[str, Any] = { - "size": size, - "from": page * size, - "sort": [ - { - "title.keyword": { - "order": sort_direction, - "missing": "_last", - "unmapped_type": "keyword", - } - }, - { - "Thema.keyword": { - "order": sort_direction, - "missing": "_last", - "unmapped_type": "keyword", - } - }, - ], + query = None + + if ( + projects_filtering_properties.query + and projects_filtering_properties.query.strip() != "" + ): + title_query = projects_filtering_properties.query.strip() + wildcard_title = f"*{title_query}*" + query = { + "bool": { + "should": [ + { + "wildcard": { + "title.keyword": { + "value": wildcard_title, + "case_insensitive": True, + } + } + }, + { + "wildcard": { + "Thema.keyword": { + "value": wildcard_title, + "case_insensitive": True, + } + } + }, + ], + "minimum_should_match": 1, + } } - if title and len(title.strip()) > 0: - title = f"*{title.strip()}*" - query["query"] = { - "bool": { - "should": [ - { - "wildcard": { - "title.keyword": { - "value": title, - "case_insensitive": True, - } - } - }, - { - "wildcard": { - "Thema.keyword": { - "value": title, - "case_insensitive": True, - } - } - }, - ], - "minimum_should_match": 1, - } - } - - return query - - def _project_type_to_index(self, project_type: ProjectType) -> str: - if project_type == ProjectType.BUND: - return "projects_bund_v1" - elif project_type == ProjectType.EU: - return "cordis_eu_*_projects" - elif project_type == ProjectType.DFG: - return "projects_dfg_all" - else: - raise ValueError(f"Unsupported project type: {project_type}") - - async def search_projects( - self, - page: int, - size: int, - selected_project_types: Optional[Set[ProjectType]] = None, - title: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ): - body = self._build_projects_search_body( - page=page, - size=size, - title=title, - sort_by=sort_by, - sort_direction=sort_direction, - ) - if not selected_project_types: - selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG} - index = ",".join( - self._project_type_to_index(pt) for pt in selected_project_types - ) - - projects_response = await self.make_search_request(body, index=index) - return _response_to_funding_project_page(projects_response, page, size) + if not selected_project_types: + selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG} + index = [project_type.to_es_index() for project_type in selected_project_types] + size = projects_filtering_properties.size + page = projects_filtering_properties.page + offset = page * size + response = elasticsearch.search( + index=index, + size=size, + offset=offset, + query=query, + sort=sort, + ) + return _response_to_funding_project_page(response=response, page=page, size=size) def _response_to_funding_project_page( diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 568abeae..8cc1f11e 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -22,7 +22,6 @@ from inse.tags import Tags from inse.projects import service as projects_service from inse.projects.projects_search_client import ( BundProjectsSearchClient, - CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, ) @@ -51,11 +50,6 @@ def get_dfg_search_client() -> DfgProjectsSearchClient: return DfgProjectsSearchClient() -@lru_cache -def get_complete_projects_search_client() -> CompleteProjectsSearchClient: - return CompleteProjectsSearchClient() - - @router.get( "/author/{raw_oa_author_id}/eu", summary="Get EU projects for an author.", @@ -326,10 +320,7 @@ async def get_dfg_projects( }, response_model_by_alias=False, ) -async def search_projects( - complete_projects_search_client: Annotated[ - CompleteProjectsSearchClient, Depends(get_complete_projects_search_client) - ], +def search_projects( page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 10, selected_project_types: Annotated[ @@ -348,8 +339,7 @@ async def search_projects( SortDirection, Query(description="The sort direction (asc or desc).") ] = SortDirection.ASC, ) -> FundingProjectPage: - return await projects_service.search_projects( - projects_search_client=complete_projects_search_client, + return projects_service.search_all_projects( page=page, size=size, selected_project_types=selected_project_types, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index a725f0fa..0e1e58e2 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -2,9 +2,9 @@ import datetime import logging from typing import Any, Dict, List, Optional, Set +from inse.projects import projects_search_client from inse.projects.projects_search_client import ( BundProjectsSearchClient, - CompleteProjectsSearchClient, DfgProjectsSearchClient, EuProjectsSearchClient, get_organization_project_contributions_foo, @@ -30,11 +30,11 @@ from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id from inse.works.logic import get_publication_dois_of_author + logger = logging.getLogger(__name__) -async def search_projects( - projects_search_client: CompleteProjectsSearchClient, +def search_all_projects( page: int, size: int, sort_by: ProjectsSortBy, @@ -42,13 +42,16 @@ async def search_projects( selected_project_types: Optional[Set[ProjectType]] = None, title: Optional[str] = None, ) -> FundingProjectPage: - return await projects_search_client.search_projects( - page=page, - size=size, + return projects_search_client.search_all_projects( + projects_filtering_properties=ProjectsFilteringProperties( + project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + query=title, + ), selected_project_types=selected_project_types, - title=title, - sort_by=sort_by, - sort_direction=sort_direction, ) From f3539e4210cfce0060bc712f7368cb476d40613f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 15:35:56 +0200 Subject: [PATCH 21/53] Moved dfg projects search client out of class --- .../main/inse/integrations/elasticsearch.py | 3 +- service/src/main/inse/persons/service.py | 2 +- .../inse/projects/projects_search_client.py | 923 ++++++------------ service/src/main/inse/projects/router.py | 62 +- service/src/main/inse/projects/service.py | 61 +- 5 files changed, 354 insertions(+), 697 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 00f9d241..da34ed82 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,3 +1,4 @@ +import json import logging from typing import Any, Dict, List, Optional, Tuple import httpx @@ -154,7 +155,7 @@ def search( with httpx.Client(timeout=httpx.Timeout(30.0)) as client: logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {payload}" + f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" ) if isinstance(index, list): index_str = ",".join(index) diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index c6cae176..a1e08f62 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -53,7 +53,7 @@ def search_persons( if include else None ) - return logic.search_persons(author_id, query, include_set) + return logic.search_persons(author_id, query) @router.get( diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index ed62e84b..72620407 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -133,642 +133,365 @@ class ProjectsSearchClient: return response.json() -class BundProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="projects_bund_v1", - api_key=settings.elasticsearch_inse_api_key, - ) +def search_bund_projects( + page: int, + size: int, + institution_names: List[str] = [], + topic: Optional[str] = None, + sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, + sort_direction: SortDirection = SortDirection.ASC, +) -> BundProjectPage: - def _bund_projects_query( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ) -> dict: - from_ = page * size - query: Dict[str, Any] = {"size": size, "from": from_, "query": {}} - - must_clauses: List[Dict[str, Any]] = [] - if id: - must_clauses.append({"match": {"id": id}}) - - if len(institution_names) > 0: - must_clauses.append( - { - "bool": { - "should": [ - { - "match": { - "Zuwendungsempfänger": { - "query": name, - "operator": "and", - } + must_clauses: List[Dict[str, Any]] = [] + if len(institution_names) > 0: + must_clauses.append( + { + "bool": { + "should": [ + { + "match": { + "Zuwendungsempfänger": { + "query": name, + "operator": "and", } } - for name in institution_names - ], - "minimum_should_match": 1, - } - } - ) - - if topic is not None and topic.strip() != "": - must_clauses.append( - { - "match_phrase_prefix": { - "Thema": { - "query": topic, - "max_expansions": 50, } + for name in institution_names + ], + "minimum_should_match": 1, + } + } + ) + + if topic is not None and topic.strip() != "": + must_clauses.append( + { + "match_phrase_prefix": { + "Thema": { + "query": topic, + "max_expansions": 50, } } - ) - - if must_clauses: - query["query"] = {"bool": {"must": must_clauses}} - else: - query["query"] = {"match_all": {}} - - query["sort"] = [ - {sort_by.to_bund_project_sort_field(): {"order": sort_direction}} - ] - - query_str = json.dumps(query, indent=2) - logger.debug(f"Constructed Bund project query: {query_str}") - - return query - - def response_to_bund_project_page( - self, response: dict, page: int, size: int - ) -> BundProjectPage: - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - BundProject.model_validate(hit["_source"]) - for hit in hits_block.get("hits", []) - ] - return BundProjectPage( - elements=elements, total=total_hits, page=page, size=size + } ) - async def search_bund_projects( - self, - page: int, - size: int, - id: Optional[str] = None, - institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, - ) -> BundProjectPage: - query = self._bund_projects_query( - page=page, - size=size, - id=id, - institution_names=institution_names, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, - ) - response = await self.make_search_request(query) - return self.response_to_bund_project_page(response, page, size) + query: Optional[Dict[str, Any]] = None + if must_clauses: + query = {"bool": {"must": must_clauses}} - async def get_bund_projects_by_institution_name( - self, - institution_names: List[str], - page: int, - size: int, - sort_by: str = "topic", - sort_direction: str = "asc", - ) -> BundProjectPage: - query = self._bund_projects_query( - page=page, - size=size, - institution_names=institution_names, - sort_by=sort_by, - sort_direction=sort_direction, - ) - response = await self.make_search_request(query) - return self.response_to_bund_project_page(response, page, size) + sort = [{sort_by.to_bund_project_sort_field(): {"order": sort_direction.value}}] - async def get_bund_project_by_id( - self, project_id: str - ) -> Optional[BundProjectDetails]: + response = elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + query=query, + sort=sort, + size=size, + offset=page * size, + ) - query = { - "query": {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}, - "_source": True, - } - - response = await self.make_search_request(query) - hits = response.get("hits", {}).get("hits", []) - if hits: - hit = hits[0] - print(hit) - details = BundProjectDetails.from_elastic_hit(hit=hit) - return details - return None + return _complete_response_to_bund_project_page( + response=response, page=page, size=size + ) -class EuProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="projects_eu_all", - api_key=settings.elasticsearch_inse_api_key, - ) +def _complete_response_to_bund_project_page( + response: Dict[str, Any], page: int, size: int +) -> BundProjectPage: + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [ + BundProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", []) + ] + return BundProjectPage(elements=elements, total=total_hits, page=page, size=size) - def _eu_projects_id_body(self, eu_organisation_ids: List[str]) -> Dict[str, Any]: - """Constructs the Elasticsearch query body to retrieve project IDs associated with the given list of EU organisation IDs. - Args: - eu_organisation_ids (List[str]): A list of EU organisation IDs for which to retrieve associated project IDs. +def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: + query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}} - Returns: - Dict[str, Any]: The Elasticsearch query body. - """ - body: Dict[str, Any] = { - "size": 0, - "query": { - "bool": {"filter": [{"terms": {"organisationID": eu_organisation_ids}}]} - }, - "aggs": { - "associated_project_ids": { - "terms": {"field": "projectID", "size": 10000} + response = elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + query=query, + size=1, + ) + + hits = response.get("hits", {}).get("hits", []) + if hits: + hit = hits[0] + details = BundProjectDetails.from_elastic_hit(hit=hit) + return details + return None + + +def _get_raw_doi(doi: str) -> str: + """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. + + Args: + doi (str): The DOI string to process. + + Returns: + str: The raw DOI string. + """ + if doi.startswith("https://doi.org/"): + return doi[len("https://doi.org/") :] + elif doi.startswith("http://dx.doi.org/"): + return doi[len("http://dx.doi.org/") :] + else: + return doi + + +def get_cordis_eu_publications_by_dois(dois: List[str]): + """Retrieves Cordis EU publications associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve publications. + + Returns: + _type_: The retrieved publications. + """ + raw_dois = [_get_raw_doi(doi) for doi in dois] + query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} + + response = elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + cluster=ESCluster.INSE, + ) + + logger.debug(f"Received publications response: {json.dumps(response, indent=2)}") + + return response + + +def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: + """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. + + Args: + dois (List[str]): The list of DOIs for which to retrieve project IDs. + + Returns: + List[str]: The list of project IDs. + """ + response = get_cordis_eu_publications_by_dois(dois=dois) + hits_block = response.get("hits", {}) + project_ids = set() + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + if project_id: + project_ids.add(project_id) + return list(project_ids) + + +def get_cordis_eu_projects_by_project_ids( + project_ids: List[str], +) -> CordisEuProjectPage: + query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} + + response = elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + ) + + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [ + CordisEuProject.model_validate(hit["_source"]) + for hit in hits_block.get("hits", []) + ] + return CordisEuProjectPage( + elements=elements, total=total_hits, page=0, size=len(elements) + ) + + +def search_dfg_projects( + page: int, + size: int, + names: Optional[List[str]] = None, + topic: Optional[str] = None, + sort_by: str = "id", + sort_direction: str = "asc", +): + from_ = page * size + + painless_fields_string = ", ".join([f"'{f}.keyword'" for f in DFG_PERSON_FIELDS]) + + body: Dict[str, Any] = { + "size": size, + "from": from_, + "_source": [ + "id", + "link", + "title", + "funding_start", + "funding_end", + "Fachliche Zuordnung", + ], + "query": {}, + "script_fields": { + "all_found_names": { + "script": { + "lang": "painless", + "source": ( + f"def names = new HashSet(); " + f"def fields = [{painless_fields_string}]; " + f"for (field in fields) {{ " + f" if (doc.containsKey(field) && !doc[field].empty) {{ " + f" for (value in doc[field]) {{ " + f" if (value.contains(';')) {{ " + f" def splitNames = value.splitOnToken(';'); " + f" for (sn in splitNames) {{ names.add(sn.trim()); }} " + f" }} else {{ " + f" names.add(value.trim()); " + f" }} " + f" }} " + f" }} " + f"}} " + f"return new ArrayList(names);" + ), } - }, - } + } + }, + } - query_str = json.dumps(body, indent=2) - logger.debug(f"Constructed EU project ID query: {query_str}") - return body + must_clauses: List[Dict[str, Any]] = [] + filter_clauses: List[Dict[str, Any]] = [] - def _eu_projects_id_response_to_ids(self, response: Dict[str, Any]) -> List[str]: - """Converts the Elasticsearch aggregation response to a list of project IDs. - - Args: - response (Dict[str, Any]): The Elasticsearch aggregation response. - - Returns: - List[str]: A list of project IDs. - """ - buckets = ( - response.get("aggregations", {}) - .get("associated_project_ids", {}) - .get("buckets", []) - ) - ids = [bucket.get("key") for bucket in buckets if "key" in bucket] - logger.debug(f"Extracted project IDs from response: {ids}") - return ids - - def _eu_project_sort_by_field(self, sort_by: ProjectsSortBy) -> str: - """Maps the ProjectsSortBy enum to the corresponding Elasticsearch field for sorting EU projects. - - Args: - sort_by (ProjectsSortBy): The sorting criterion specified as a ProjectsSortBy enum value. - - Returns: - str: The corresponding Elasticsearch field for sorting. - """ - if sort_by == ProjectsSortBy.TITLE: - return "title.keyword" - elif sort_by == ProjectsSortBy.FUNDING_START: - return "startDate" - elif sort_by == ProjectsSortBy.FUNDING_END: - return "endDate" - elif sort_by == ProjectsSortBy.FUNDING_AMOUNT: - return "totalCost" - else: - return "id.keyword" - - def _eu_projects_body( - self, - project_ids: List[str], - projects_filtering_properties: ProjectsFilteringProperties, - ) -> Dict[str, Any]: - bool_query: Dict[str, Any] = {"filter": [{"terms": {"id": project_ids}}]} - - if ( - projects_filtering_properties.query is not None - and projects_filtering_properties.query.strip() != "" - ): - bool_query["must"] = [ - { - "match_phrase_prefix": { - "title": { - "query": projects_filtering_properties.query, - "max_expansions": 50, - } + if topic is not None and topic.strip() != "": + must_clauses.append( + { + "match_phrase_prefix": { + "title": { + "query": topic, + "max_expansions": 100, } } + } + ) + + if names: + name_should_clauses = [] + script_conditions = [] + + for full_name in names: + name_parts = full_name.strip().split() + if not name_parts: + continue + + match_musts = [] + for part in name_parts: + match_musts.append( + {"multi_match": {"query": part, "fields": DFG_PERSON_FIELDS}} + ) + + name_should_clauses.append({"bool": {"must": match_musts}}) + + script_parts = [ + f"singlePerson.contains('{part.lower()}')" for part in name_parts ] + script_conditions.append(f"({' && '.join(script_parts)})") - body: Dict[str, Any] = { - "from": projects_filtering_properties.page - * projects_filtering_properties.size, - "size": projects_filtering_properties.size, - "query": {"bool": bool_query}, - "sort": [ - { - self._eu_project_sort_by_field( - projects_filtering_properties.sort_by - ): { - "order": projects_filtering_properties.sort_direction, - } - } - ], - } - - query_str = json.dumps(body, indent=2) - logger.debug(f"Constructed EU project details query: {query_str}") - return body - - async def search_eu_projects( - self, - eu_organisation_ids: List[str], - projects_filtering_properties: ProjectsFilteringProperties, - ) -> CordisEuProjectPage: - projects_id_body = self._eu_projects_id_body(eu_organisation_ids) - id_response = await self.make_search_request( - projects_id_body, index="cordis_eu_*_organizations" - ) - project_ids = self._eu_projects_id_response_to_ids(id_response) - logger.debug( - f"Found project IDs for organization IDs {eu_organisation_ids}: {project_ids}" - ) - if not project_ids: - logger.debug( - f"No project IDs found for organization IDs {eu_organisation_ids}" - ) - return CordisEuProjectPage( - elements=[], - total=0, - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - projects_body = self._eu_projects_body( - project_ids=project_ids, - projects_filtering_properties=projects_filtering_properties, - ) - projects_response = await self.make_search_request( - projects_body, index="cordis_eu_*_projects" - ) - logger.debug( - f"Received projects response: {json.dumps(projects_response, indent=2)}" - ) - return self._response_to_cordis_eu_project_page( - projects_response, - projects_filtering_properties.page, - projects_filtering_properties.size, - ) - - def _response_to_cordis_eu_project_page( - self, response: Dict[str, Any], page: int, size: int - ) -> CordisEuProjectPage: - """Converts the Elasticsearch response to a CordisEuProjectPage containing CordisEuProject elements. - - Args: - response (Dict[str, Any]): The Elasticsearch response. - page (int): The page number. - size (int): The number of items per page. - - Returns: - CordisEuProjectPage: The converted project page. - """ - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - CordisEuProject.model_validate(hit["_source"]) - for hit in hits_block.get("hits", []) - ] - return CordisEuProjectPage( - elements=elements, total=total_hits, page=page, size=size - ) - - def _get_raw_doi(self, doi: str) -> str: - """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. - - Args: - doi (str): The DOI string to process. - - Returns: - str: The raw DOI string. - """ - if doi.startswith("https://doi.org/"): - return doi[len("https://doi.org/") :] - elif doi.startswith("http://dx.doi.org/"): - return doi[len("http://dx.doi.org/") :] - else: - return doi - - def get_cordis_eu_publications_by_dois(self, dois: List[str]): - """Retrieves Cordis EU publications associated with the given list of DOIs. - - Args: - dois (List[str]): The list of DOIs for which to retrieve publications. - - Returns: - _type_: The retrieved publications. - """ - raw_dois = [self._get_raw_doi(doi) for doi in dois] - query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} - - response = elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, - cluster=ESCluster.INSE, - ) - - logger.debug( - f"Received publications response: {json.dumps(response, indent=2)}" - ) - - return response - - def get_cordis_eu_project_ids_by_dois(self, dois: List[str]) -> List[str]: - """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. - - Args: - dois (List[str]): The list of DOIs for which to retrieve project IDs. - - Returns: - List[str]: The list of project IDs. - """ - response = self.get_cordis_eu_publications_by_dois(dois=dois) - hits_block = response.get("hits", {}) - project_ids = set() - for hit in hits_block.get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - if project_id: - project_ids.add(project_id) - return list(project_ids) - - def get_cordis_eu_projects_by_project_ids( - self, project_ids: List[str] - ) -> CordisEuProjectPage: - query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} - - response = elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - ) - - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - CordisEuProject.model_validate(hit["_source"]) - for hit in hits_block.get("hits", []) - ] - return CordisEuProjectPage( - elements=elements, total=total_hits, page=0, size=len(elements) - ) - - -class DfgProjectsSearchClient(ProjectsSearchClient): - def __init__(self): - if not settings.elasticsearch_inse_url: - raise ValueError("Elasticsearch INSE URL is missing in settings.") - if not settings.elasticsearch_inse_api_key: - raise ValueError("Elasticsearch INSE API key is missing in settings.") - super().__init__( - base_url=settings.elasticsearch_inse_url, - index="projects_dfg_all", - api_key=settings.elasticsearch_inse_api_key, - ) - - def dfg_projects_query( - self, - page: int, - size: int, - names: Optional[List[str]] = None, - topic: Optional[str] = None, - sort_by: str = "id", - sort_direction: str = "asc", - ) -> dict: - - from_ = page * size - - painless_fields_string = ", ".join( - [f"'{f}.keyword'" for f in DFG_PERSON_FIELDS] - ) - - query: Dict[str, Any] = { - "size": size, - "from": from_, - "_source": [ - "id", - "link", - "title", - "funding_start", - "funding_end", - "Fachliche Zuordnung", - ], - "query": {}, - "script_fields": { - "all_found_names": { - "script": { - "lang": "painless", - "source": ( - f"def names = new HashSet(); " - f"def fields = [{painless_fields_string}]; " - f"for (field in fields) {{ " - f" if (doc.containsKey(field) && !doc[field].empty) {{ " - f" for (value in doc[field]) {{ " - f" if (value.contains(';')) {{ " - f" def splitNames = value.splitOnToken(';'); " - f" for (sn in splitNames) {{ names.add(sn.trim()); }} " - f" }} else {{ " - f" names.add(value.trim()); " - f" }} " - f" }} " - f" }} " - f"}} " - f"return new ArrayList(names);" - ), - } - } - }, - } - - must_clauses: List[Dict[str, Any]] = [] - filter_clauses: List[Dict[str, Any]] = [] - - if topic is not None and topic.strip() != "": + if name_should_clauses: must_clauses.append( - { - "match_phrase_prefix": { - "title": { - "query": topic, - "max_expansions": 100, - } - } - } + {"bool": {"should": name_should_clauses, "minimum_should_match": 1}} ) - if names: - name_should_clauses = [] - script_conditions = [] + combined_script_condition = " || ".join(script_conditions) + painless_source = ( + f"def fields = [{painless_fields_string}]; " + f"for (field in fields) {{ " + f" if (doc.containsKey(field) && !doc[field].empty) {{ " + f" for (value in doc[field]) {{ " + f" if (value.contains(';')) {{ " + f" def splitValues = value.splitOnToken(';'); " + f" for (singlePersonRaw in splitValues) {{ " + f" def singlePerson = singlePersonRaw.toLowerCase(); " + f" if ({combined_script_condition}) {{ return true; }} " + f" }} " + f" }} else {{ " + f" def singlePerson = value.toLowerCase(); " + f" if ({combined_script_condition}) {{ return true; }} " + f" }} " + f" }} " + f" }} " + f"}} " + f"return false;" + ) - for full_name in names: - name_parts = full_name.strip().split() - if not name_parts: - continue + filter_clauses.append( + {"script": {"script": {"lang": "painless", "source": painless_source}}} + ) - match_musts = [] - for part in name_parts: - match_musts.append( - {"multi_match": {"query": part, "fields": DFG_PERSON_FIELDS}} - ) + if must_clauses or filter_clauses: + body["query"] = {"bool": {}} + if must_clauses: + body["query"]["bool"]["must"] = must_clauses + if filter_clauses: + body["query"]["bool"]["filter"] = filter_clauses + else: + body["query"] = {"match_all": {}} - name_should_clauses.append({"bool": {"must": match_musts}}) + sort_by = sort_by.strip().lower() + sort_direction = sort_direction.strip().lower() + if sort_direction not in ["asc", "desc"]: + sort_direction = "asc" + logger.debug(f"Sorting DFG projects by {sort_by} with direction {sort_direction}") - script_parts = [ - f"singlePerson.contains('{part.lower()}')" for part in name_parts - ] - script_conditions.append(f"({' && '.join(script_parts)})") - - if name_should_clauses: - must_clauses.append( - {"bool": {"should": name_should_clauses, "minimum_should_match": 1}} - ) - - combined_script_condition = " || ".join(script_conditions) - painless_source = ( - f"def fields = [{painless_fields_string}]; " - f"for (field in fields) {{ " - f" if (doc.containsKey(field) && !doc[field].empty) {{ " - f" for (value in doc[field]) {{ " - f" if (value.contains(';')) {{ " - f" def splitValues = value.splitOnToken(';'); " - f" for (singlePersonRaw in splitValues) {{ " - f" def singlePerson = singlePersonRaw.toLowerCase(); " - f" if ({combined_script_condition}) {{ return true; }} " - f" }} " - f" }} else {{ " - f" def singlePerson = value.toLowerCase(); " - f" if ({combined_script_condition}) {{ return true; }} " - f" }} " - f" }} " - f" }} " - f"}} " - f"return false;" - ) - - filter_clauses.append( - { - "script": { - "script": {"lang": "painless", "source": painless_source} - } - } - ) - - if must_clauses or filter_clauses: - query["query"] = {"bool": {}} - if must_clauses: - query["query"]["bool"]["must"] = must_clauses - if filter_clauses: - query["query"]["bool"]["filter"] = filter_clauses - else: - query["query"] = {"match_all": {}} - - sort_by = sort_by.strip().lower() - sort_direction = sort_direction.strip().lower() - if sort_direction not in ["asc", "desc"]: - sort_direction = "asc" + if sort_by in ["topic", "title"]: + logger.debug(f"Sorting DFG projects by title with direction {sort_direction}") + sort_config = {"title.keyword": {"order": sort_direction}} + elif sort_by == "funding_start": logger.debug( - f"Sorting DFG projects by {sort_by} with direction {sort_direction}" + f"Sorting DFG projects by funding_start with direction {sort_direction}" ) - - if sort_by in ["topic", "title"]: - logger.debug( - f"Sorting DFG projects by title with direction {sort_direction}" - ) - sort_config = {"title.keyword": {"order": sort_direction}} - elif sort_by == "funding_start": - logger.debug( - f"Sorting DFG projects by funding_start with direction {sort_direction}" - ) - sort_config = {"funding_start.keyword": {"order": sort_direction}} - elif sort_by == "funding_end": - logger.debug( - f"Sorting DFG projects by funding_end with direction {sort_direction}" - ) - sort_config = {"funding_end.keyword": {"order": sort_direction}} - elif sort_by == "professional_classification": - logger.debug( - f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}" - ) - sort_config = {"Fachliche Zuordnung.keyword": {"order": sort_direction}} - else: - logger.debug(f"Sorting DFG projects by id with direction {sort_direction}") - sort_config = {"id.keyword": {"order": sort_direction}} - - query["sort"] = [sort_config] - - query_str = json.dumps(query, indent=2) - logger.debug(f"Constructed DFG project query: {query_str}") - - return query - - def response_to_dfg_project_page( - self, response: dict, page: int, size: int - ) -> DfgProjectPage: - hits_block = response.get("hits", {}) - total_hits = hits_block.get("total", {}).get("value", 0) - elements = [ - DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", []) - ] - return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) - - async def search_dfg_projects( - self, - page: int, - size: int, - names: Optional[List[str]] = None, - topic: Optional[str] = None, - sort_by: str = "id", - sort_direction: str = "asc", - ) -> DfgProjectPage: - query = self.dfg_projects_query( - page=page, - size=size, - names=names, - topic=topic, - sort_by=sort_by, - sort_direction=sort_direction, + sort_config = {"funding_start.keyword": {"order": sort_direction}} + elif sort_by == "funding_end": + logger.debug( + f"Sorting DFG projects by funding_end with direction {sort_direction}" ) - response = await self.make_search_request(query) - return self.response_to_dfg_project_page(response, page, size) + sort_config = {"funding_end.keyword": {"order": sort_direction}} + elif sort_by == "professional_classification": + logger.debug( + f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}" + ) + sort_config = {"Fachliche Zuordnung.keyword": {"order": sort_direction}} + else: + logger.debug(f"Sorting DFG projects by id with direction {sort_direction}") + sort_config = {"id.keyword": {"order": sort_direction}} - async def get_dfg_project_by_id( - self, project_id: str - ) -> Optional[DfgProjectDetails]: - query = {"query": {"ids": {"values": [project_id]}}, "_source": True} + body["sort"] = [sort_config] - response = await self.make_search_request(query) - hits = response.get("hits", {}).get("hits", []) + response = elasticsearch.search( + index=ESIndex.PROJECTS_DFG_ALL, + body=body, + ) + return _complete_response_to_dfg_project_page(response, page, size) - if hits: - hit = hits[0] - details = DfgProjectDetails.from_elastic_hit(hit=hit) - return details - return None + +def _complete_response_to_dfg_project_page( + response: dict, page: int, size: int +) -> DfgProjectPage: + hits_block = response.get("hits", {}) + total_hits = hits_block.get("total", {}).get("value", 0) + elements = [DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])] + return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) + + +def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: + query = {"ids": {"values": [project_id]}} + + response = elasticsearch.search( + index=ESIndex.PROJECTS_DFG_ALL, + query=query, + size=1, + ) + hits = response.get("hits", {}).get("hits", []) + + if hits: + hit = hits[0] + details = DfgProjectDetails.from_elastic_hit(hit=hit) + return details + return None def search_all_projects( diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 8cc1f11e..509f5d8b 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -20,11 +20,7 @@ from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.tags import Tags from inse.projects import service as projects_service -from inse.projects.projects_search_client import ( - BundProjectsSearchClient, - DfgProjectsSearchClient, - EuProjectsSearchClient, -) + from inse.institutions.institutions_search_client import ( InstitutionsSearchClient, ) @@ -35,21 +31,6 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS]) -@lru_cache -def get_bund_search_client() -> BundProjectsSearchClient: - return BundProjectsSearchClient() - - -@lru_cache -def get_eu_search_client() -> EuProjectsSearchClient: - return EuProjectsSearchClient() - - -@lru_cache -def get_dfg_search_client() -> DfgProjectsSearchClient: - return DfgProjectsSearchClient() - - @router.get( "/author/{raw_oa_author_id}/eu", summary="Get EU projects for an author.", @@ -65,16 +46,12 @@ def get_dfg_search_client() -> DfgProjectsSearchClient: response_model_by_alias=False, ) def get_eu_projects_for_author( - eu_projects_search_client: Annotated[ - EuProjectsSearchClient, Depends(get_eu_search_client) - ], raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")], ) -> CordisEuProjectPage: logger.debug( f"Received request to get EU projects for author_id={raw_oa_author_id}" ) return projects_service.search_cordis_eu_projects_for_author_id( - eu_projects_search_client=eu_projects_search_client, raw_oa_author_id=raw_oa_author_id, ) @@ -94,9 +71,6 @@ def get_eu_projects_for_author( response_model_by_alias=False, ) async def search_bund_projects( - bund_search_client: Annotated[ - BundProjectsSearchClient, Depends(get_bund_search_client) - ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -105,8 +79,7 @@ async def search_bund_projects( Body(description="The filtering properties for the projects search."), ], ) -> BundProjectPage: - return await projects_service.search_bund_projects( - bund_search_client=bund_search_client, + return projects_service.search_bund_projects( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) @@ -126,15 +99,11 @@ async def search_bund_projects( }, response_model_by_alias=False, ) -async def get_single_dfg_project( - dfg_search_client: Annotated[ - DfgProjectsSearchClient, Depends(get_dfg_search_client) - ], +def get_single_dfg_project( id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")], ) -> DfgProjectDetails: logger.debug(f"Received request to get single DFG project for id={id}") - return await projects_service.get_single_dfg_project( - dfg_search_client=dfg_search_client, + return projects_service.get_single_dfg_project( project_id=id, ) @@ -153,15 +122,11 @@ async def get_single_dfg_project( }, response_model_by_alias=False, ) -async def get_single_bund_project( - bund_search_client: Annotated[ - BundProjectsSearchClient, Depends(get_bund_search_client) - ], +def get_single_bund_project( id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")], ) -> BundProjectDetails: logger.debug(f"Received request to get single BUND project for id={id}") - return await projects_service.get_single_bund_project( - bund_search_client=bund_search_client, + return projects_service.get_single_bund_project( project_id=id, ) @@ -180,10 +145,7 @@ async def get_single_bund_project( }, response_model_by_alias=False, ) -async def get_institution_bund_projects_funding_over_time( - bund_search_client: Annotated[ - BundProjectsSearchClient, Depends(get_bund_search_client) - ], +def get_institution_bund_projects_funding_over_time( institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -191,8 +153,7 @@ async def get_institution_bund_projects_funding_over_time( str, Query(description="The institution ID to filter by.") ], ) -> InstitutionFunderSummary: - return await projects_service.get_institution_bund_projects_funding_over_time( - bund_search_client=bund_search_client, + return projects_service.get_institution_bund_projects_funding_over_time( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, ) @@ -213,7 +174,6 @@ async def get_institution_bund_projects_funding_over_time( response_model_by_alias=False, ) async def search_cordis_eu_projects( - eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -243,7 +203,6 @@ async def search_cordis_eu_projects( response_model_by_alias=False, ) async def get_institution_cordis_eu_projects_funding_over_time( - eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -252,7 +211,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( ], ) -> InstitutionFunderSummary: return await projects_service.get_institution_cordis_eu_projects_funding_over_time( - eu_search_client=eu_search_client, institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, ) @@ -273,9 +231,6 @@ async def get_institution_cordis_eu_projects_funding_over_time( response_model_by_alias=False, ) async def get_dfg_projects( - dfg_search_client: Annotated[ - DfgProjectsSearchClient, Depends(get_dfg_search_client) - ], author_id: Annotated[str, Query(description="The author ID to filter by.")], topic: Annotated[ Optional[str], Query(description="The topic to filter by.") @@ -297,7 +252,6 @@ async def get_dfg_projects( sort_direction, ) return await projects_service.get_dfg_projects_by_author_id( - dfg_search_client=dfg_search_client, author_id=author_id, topic=topic, page=page, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 0e1e58e2..4f35c69b 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -4,9 +4,6 @@ from typing import Any, Dict, List, Optional, Set from inse.projects import projects_search_client from inse.projects.projects_search_client import ( - BundProjectsSearchClient, - DfgProjectsSearchClient, - EuProjectsSearchClient, get_organization_project_contributions_foo, ) from inse.projects.model import ( @@ -55,8 +52,7 @@ def search_all_projects( ) -async def search_bund_projects( - bund_search_client: BundProjectsSearchClient, +def search_bund_projects( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -65,15 +61,17 @@ async def search_bund_projects( f"Invalid project type: {filtering_properties.project_type}. Expected 'bund'." ) - return await get_bund_projects_by_institution_id( - bund_search_client=bund_search_client, + logger.debug( + f"search_bund_projects called with filtering_properties: {filtering_properties}" + ) + + return get_bund_projects_by_institution_id( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) -async def get_bund_projects_by_institution_id( - bund_search_client: BundProjectsSearchClient, +def get_bund_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -89,9 +87,9 @@ async def get_bund_projects_by_institution_id( ) ) logger.debug( - f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" + f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - response = await bund_search_client.search_bund_projects( + response = projects_search_client.search_bund_projects( page=filtering_properties.page, size=filtering_properties.size, institution_names=institution_aliases, @@ -150,7 +148,6 @@ def get_cordis_eu_projects_by_institution_id( async def get_dfg_projects_by_author_id( - dfg_search_client: DfgProjectsSearchClient, author_id: str, topic: Optional[str], page: int, @@ -169,7 +166,7 @@ async def get_dfg_projects_by_author_id( ) logger.debug(f"Found author name for author_id={author_id}: {name}") - response = await dfg_search_client.search_dfg_projects( + response = projects_search_client.search_dfg_projects( page=page, size=size, names=[name], @@ -181,22 +178,9 @@ async def get_dfg_projects_by_author_id( async def get_institution_cordis_eu_projects_funding_over_time( - eu_search_client: EuProjectsSearchClient, institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, ) -> InstitutionFunderSummary: - - # cordis_eu_project_page = await search_cordis_eu_projects( - # eu_search_client, - # institutions_search_client, - # ProjectsFilteringProperties( - # project_type=ProjectType.EU, - # raw_oa_institution_id=raw_oa_institution_id, - # page=0, - # size=10000, - # ), - # ) - institution_aliases = ( institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id @@ -220,8 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -async def get_institution_bund_projects_funding_over_time( - bund_search_client: BundProjectsSearchClient, +def get_institution_bund_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, ) -> InstitutionFunderSummary: @@ -236,7 +219,7 @@ async def get_institution_bund_projects_funding_over_time( logger.debug( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) - response = await bund_search_client.search_bund_projects( + response = projects_search_client.search_bund_projects( page=0, size=10000, institution_names=institution_aliases, @@ -319,32 +302,30 @@ def _calculate_funding_over_time( ) -async def get_single_dfg_project( - dfg_search_client: DfgProjectsSearchClient, +def get_single_dfg_project( project_id: str, ) -> DfgProjectDetails: logger.debug(f"Fetching single DFG project for id={project_id}") - project = await dfg_search_client.get_dfg_project_by_id(project_id) + project = projects_search_client.get_dfg_project_by_id(project_id) if not project: raise NotFoundException(f"DFG project with id {project_id} not found") return project -async def get_single_bund_project( - bund_search_client: BundProjectsSearchClient, +def get_single_bund_project( project_id: str, ) -> BundProjectDetails: logger.debug(f"Fetching single BUND project for id={project_id}") - project = await bund_search_client.get_bund_project_by_id(project_id) + project = projects_search_client.get_bund_project_by_id(project_id) if not project: raise NotFoundException(f"BUND project with id {project_id} not found") return project def search_cordis_eu_projects_for_author_id( - eu_projects_search_client: EuProjectsSearchClient, raw_oa_author_id: str + raw_oa_author_id: str, ) -> CordisEuProjectPage: # Direct search not possible -> multi stage search @@ -356,16 +337,14 @@ def search_cordis_eu_projects_for_author_id( logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}") - project_ids = eu_projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) + project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) logger.debug( f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}" ) - funding_project_page = ( - eu_projects_search_client.get_cordis_eu_projects_by_project_ids( - project_ids=project_ids - ) + funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids( + project_ids=project_ids ) return funding_project_page From a0477fcdb153f86c7eddc8b4f59e477fab1d0cfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 15:50:54 +0200 Subject: [PATCH 22/53] Added documentation for projects search client --- .../inse/projects/projects_search_client.py | 627 +++++++++++------- service/src/main/inse/projects/service.py | 19 +- 2 files changed, 382 insertions(+), 264 deletions(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 72620407..a53c2f1f 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -96,51 +96,22 @@ DFG_PERSON_FIELDS: List[str] = [ "stellvertr. Sprecherinnen / stellvertr. Sprecher", ] - -class ProjectsSearchClient: - def __init__( - self, - base_url: str, - index: str, - api_key: str, - ): - self.base_url = base_url - self.index = index - self.api_key = api_key - self.headers = { - "Content-Type": "application/json", - "Authorization": f"ApiKey {self.api_key}", - } - - async def make_search_request( - self, query: dict, index: Optional[str] = None - ) -> dict: - async with httpx.AsyncClient() as client: - response = await client.post( - f"{self.base_url}/{index or self.index}/_search", - json=query, - headers=self.headers, - ) - - try: - response.raise_for_status() - except httpx.HTTPStatusError as e: - logger.exception( - f"HTTP error occurred: {e.response.status_code} - {e.response.text}" - ) - raise - - return response.json() +# BUND def search_bund_projects( - page: int, - size: int, + filter_properties: ProjectsFilteringProperties, institution_names: List[str] = [], - topic: Optional[str] = None, - sort_by: ProjectsSortBy = ProjectsSortBy.TITLE, - sort_direction: SortDirection = SortDirection.ASC, ) -> BundProjectPage: + """Searches for Bund projects based on the provided filtering properties and institution names. + + Args: + filter_properties (ProjectsFilteringProperties): The properties to filter the projects by. + institution_names (List[str], optional): The names of the institutions to filter by. Defaults to []. + + Returns: + BundProjectPage: The page of Bund projects that match the filtering criteria. + """ must_clauses: List[Dict[str, Any]] = [] if len(institution_names) > 0: @@ -163,12 +134,12 @@ def search_bund_projects( } ) - if topic is not None and topic.strip() != "": + if filter_properties.query is not None and filter_properties.query.strip() != "": must_clauses.append( { "match_phrase_prefix": { "Thema": { - "query": topic, + "query": filter_properties.query, "max_expansions": 50, } } @@ -179,24 +150,40 @@ def search_bund_projects( if must_clauses: query = {"bool": {"must": must_clauses}} - sort = [{sort_by.to_bund_project_sort_field(): {"order": sort_direction.value}}] + sort = [ + { + filter_properties.sort_by.to_bund_project_sort_field(): { + "order": filter_properties.sort_direction.value + } + } + ] response = elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, query=query, sort=sort, - size=size, - offset=page * size, + size=filter_properties.size, + offset=filter_properties.page * filter_properties.size, ) return _complete_response_to_bund_project_page( - response=response, page=page, size=size + response=response, page=filter_properties.page, size=filter_properties.size ) def _complete_response_to_bund_project_page( response: Dict[str, Any], page: int, size: int ) -> BundProjectPage: + """Converts the raw Elasticsearch response into a BundProjectPage object. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + page (int): The page number. + size (int): The number of items per page. + + Returns: + BundProjectPage: The converted BundProjectPage object. + """ hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [ @@ -206,6 +193,14 @@ def _complete_response_to_bund_project_page( def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: + """Fetches the details of a single Bund project based on its project ID. + + Args: + project_id (str): The ID of the project to fetch. + + Returns: + Optional[BundProjectDetails]: The details of the project if found, otherwise None. + """ query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}} response = elasticsearch.search( @@ -222,6 +217,264 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: return None +# EU + + +def get_eu_organization_project_contributions( + organization_names: List[str], + projects_filtering_properties: ProjectsFilteringProperties, +) -> EuOrganizationProjectSummaryPage: + """Fetches the contributions of EU organizations to projects based on the provided organization names and filtering properties, and returns a paginated summary of the projects. + + Args: + organization_names (List[str]): The list of organization names to fetch contributions for. + projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the projects. + + Returns: + EuOrganizationProjectSummaryPage: The paginated summary of the projects. + """ + # Pagination depending on sorting criteria + # For FUNDING_AMOUNT before on the organization project contributions + # For the rest after the contributions are known on the real projects + + organization_project_contributions = get_eu_organization_contributions( + organization_names=organization_names, + ) + + total_projects, projects = get_eu_organization_projects( + project_contributions=list(organization_project_contributions.values()), + projects_filtering_properties=projects_filtering_properties, + ) + + elements: List[EuOrganizationProjectSummary] = _merge_project_data( + projects=projects, contributions=organization_project_contributions + ) + + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + elements.sort( + key=lambda x: x.ec_contribution or 0, + reverse=projects_filtering_properties.sort_direction == SortDirection.DESC, + ) + start = projects_filtering_properties.page * projects_filtering_properties.size + end = start + projects_filtering_properties.size + elements = elements[start:end] + + return EuOrganizationProjectSummaryPage( + elements=elements, + total=total_projects, + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, + ) + + +def get_eu_organization_contributions( + organization_names: List[str], +) -> Dict[str, EuOrganizationShort]: + """Fetches the contributions of EU organizations to projects based on the provided organization names. + + Args: + organization_names (List[str]): The list of organization names to fetch contributions for. + + Returns: + Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions. + """ + + source = ["projectID", "organisationID", "ecContribution"] + + query = { + "terms": { + "name.keyword": [ + name.upper() for name in organization_names if name.strip() + ], + } + } + + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + size=10000, + query=query, + ) + + logger.debug( + f"Received organization project contributions response: {json.dumps(response, indent=2)}" + ) + + organization_project_contributions = _process_organization_project_contributions( + response + ) + + logger.debug( + f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}" + ) + + return organization_project_contributions + + +def _process_organization_project_contributions( + response: Dict[str, Any], +) -> Dict[str, EuOrganizationShort]: + """Processes the raw Elasticsearch response to extract the contributions of EU organizations to projects. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + + Returns: + Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions. + """ + hits_block = response.get("hits", {}) + project_contributions: Dict[str, EuOrganizationShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + organization_id = source.get("organisationID") + ec_contribution = source.get("ecContribution") + if project_id and organization_id: + project_contributions[project_id] = EuOrganizationShort( + project_id=project_id, + organization_id=organization_id, + ec_contribution=ec_contribution, + ) + return project_contributions + + +def get_eu_organization_projects( + project_contributions: List[EuOrganizationShort], + projects_filtering_properties: ProjectsFilteringProperties, +) -> Tuple[int, Dict[str, EuProjectShort]]: + """Fetches the projects associated with the given list of organization contributions, applying the specified filtering properties. + + Args: + project_contributions (List[EuOrganizationShort]): The list of organization contributions to fetch projects for. + projects_filtering_properties (ProjectsFilteringProperties): The filtering properties to apply to the project search. + + Returns: + Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details. + """ + project_ids = [contribution.project_id for contribution in project_contributions] + + source = ["id", "title", "startDate", "endDate", "acronym"] + + query = { + "terms": { + "id": project_ids, + } + } + + if ( + projects_filtering_properties.query + and projects_filtering_properties.query.strip() + ): + query = { + "bool": { + "must": [ + { + "match_phrase_prefix": { + "title": { + "query": projects_filtering_properties.query, + "max_expansions": 50, + } + } + } + ], + "filter": query, + } + } + + # Project contributions have been filtered before based on ecContribution + if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=10000, + ) + else: + response = elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + source=source, + query=query, + size=projects_filtering_properties.size, + offset=projects_filtering_properties.page + * projects_filtering_properties.size, + sort=[ + { + projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): { + "order": projects_filtering_properties.sort_direction + } + } + ], + ) + + return _process_projects_response(response) + + +def _process_projects_response( + response: Dict[str, Any], +) -> Tuple[int, Dict[str, EuProjectShort]]: + """Processes the raw Elasticsearch response to extract the project details and total count. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + + Returns: + Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details. + """ + hits_block = response.get("hits", {}) + total = hits_block.get("total", {}).get("value", 0) + projects: Dict[str, EuProjectShort] = {} + for hit in hits_block.get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("id") + title = source.get("title") + start_date = source.get("startDate") + end_date = source.get("endDate") + acronym = source.get("acronym") + if not project_id: + continue + projects[project_id] = EuProjectShort( + id=project_id, + title=title, + start_date=start_date, + end_date=end_date, + acronym=acronym, + ) + + return total, projects + + +def _merge_project_data( + projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort] +) -> List[EuOrganizationProjectSummary]: + """Merges the project details with the organization contributions to create a list of EuOrganizationProjectSummary objects. + + Args: + projects (Dict[str, EuProjectShort]): The dictionary of project details. + contributions (Dict[str, EuOrganizationShort]): The dictionary of organization contributions. + + Returns: + List[EuOrganizationProjectSummary]: The list of merged project-summary objects. + """ + merged_data = [] + for project_id, project_info in projects.items(): + contribution_info = contributions.get(project_id) + if contribution_info: + merged_entry = EuOrganizationProjectSummary( + project_id=project_id, + title=project_info.title, + start_date=project_info.start_date, + end_date=project_info.end_date, + acronym=project_info.acronym, + organization_id=contribution_info.organization_id, + ec_contribution=contribution_info.ec_contribution, + ) + merged_data.append(merged_entry) + return merged_data + + def _get_raw_doi(doi: str) -> str: """Extracts the raw DOI from a given DOI string, removing any URL prefixes if present. @@ -304,6 +557,9 @@ def get_cordis_eu_projects_by_project_ids( ) +# DFG + + def search_dfg_projects( page: int, size: int, @@ -311,7 +567,20 @@ def search_dfg_projects( topic: Optional[str] = None, sort_by: str = "id", sort_direction: str = "asc", -): +) -> DfgProjectPage: + """Searches for DFG projects based on the provided filtering and sorting criteria. + + Args: + page (int): The page number. + size (int): The number of items per page. + names (Optional[List[str]], optional): The list of names to search for. Defaults to None. + topic (Optional[str], optional): The topic to search for. Defaults to None. + sort_by (str, optional): The field to sort by. Defaults to "id". + sort_direction (str, optional): The direction to sort. Defaults to "asc". + + Returns: + DfgProjectPage: The search results. + """ from_ = page * size painless_fields_string = ", ".join([f"'{f}.keyword'" for f in DFG_PERSON_FIELDS]) @@ -471,6 +740,16 @@ def search_dfg_projects( def _complete_response_to_dfg_project_page( response: dict, page: int, size: int ) -> DfgProjectPage: + """Converts the raw Elasticsearch response into a DfgProjectPage object. + + Args: + response (dict): The raw Elasticsearch response. + page (int): The page number. + size (int): The number of items per page. + + Returns: + DfgProjectPage: The converted project page object. + """ hits_block = response.get("hits", {}) total_hits = hits_block.get("total", {}).get("value", 0) elements = [DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])] @@ -478,6 +757,14 @@ def _complete_response_to_dfg_project_page( def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: + """Fetches the details of a single DFG project based on its project ID. + + Args: + project_id (str): The project ID to fetch. + + Returns: + Optional[DfgProjectDetails]: The project details or None if not found. + """ query = {"ids": {"values": [project_id]}} response = elasticsearch.search( @@ -494,10 +781,25 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: return None +# All + + def search_all_projects( projects_filtering_properties: ProjectsFilteringProperties, selected_project_types: Optional[Set[ProjectType]] = None, -): +) -> FundingProjectPage: + """Searches for projects across all project types based on the provided filtering properties and selected project types. + + Args: + projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the search. + selected_project_types (Optional[Set[ProjectType]], optional): The set of project types to include in the search. Defaults to None -> includes all project types. + + Raises: + ValueError: If the sorting property is not supported across all project types. + + Returns: + FundingProjectPage: The converted project page object. + """ sort_by = projects_filtering_properties.sort_by if sort_by != ProjectsSortBy.TITLE: raise ValueError( @@ -573,6 +875,16 @@ def search_all_projects( def _response_to_funding_project_page( response: Dict[str, Any], page: int, size: int ) -> FundingProjectPage: + """Converts the raw Elasticsearch response into a FundingProjectPage object. + + Args: + response (Dict[str, Any]): The raw Elasticsearch response. + page (int): The current page number. + size (int): The number of projects per page. + + Returns: + FundingProjectPage: The converted project page object. + """ hits = response.get("hits", {}).get("hits", []) projects = [_hit_to_funding_project(hit=hit) for hit in hits] total = response.get("hits", {}).get("total", {}).get("value", 0) @@ -580,219 +892,26 @@ def _response_to_funding_project_page( def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject: + """Converts a single Elasticsearch hit into a FundingProject object based on the index it belongs to. + + Args: + hit (Dict[str, Any]): The Elasticsearch hit to convert. + + Raises: + ValueError: If the hit does not belong to a recognized project index. + + Returns: + FundingProject: The converted funding project object. + """ if hit.get("_index", "").startswith("cordis_eu_") and hit.get( "_index", "" ).endswith("_projects"): return FundingProject.from_cordis_projects_hit(hit=hit) - elif hit.get("_index") == "projects_bund_v1": + elif hit.get("_index") == ESIndex.PROJECTS_BUND_V1.value: return FundingProject.from_bund_projects_hit(hit=hit) - elif hit.get("_index") == "projects_dfg_all": + elif hit.get("_index") == ESIndex.PROJECTS_DFG_ALL.value: return FundingProject.from_dfg_projects_hit(hit=hit) else: raise ValueError( "The provided hit does not belong to a recognized project index." ) - - -def get_organization_project_contributions_foo( - organization_names: List[str], - projects_filtering_properties: ProjectsFilteringProperties, -) -> EuOrganizationProjectSummaryPage: - # Pagination depending on sorting criteria - # For FUNDING_AMOUNT before on the organization project contributions - # For the rest after the contributions are known on the real projects - - organization_project_contributions = get_organization_project_contributions( - organization_names=organization_names, - ) - - total_projects, projects = get_projects( - project_contributions=list(organization_project_contributions.values()), - projects_filtering_properties=projects_filtering_properties, - ) - - elements: List[EuOrganizationProjectSummary] = _merge_project_data( - projects=projects, contributions=organization_project_contributions - ) - - if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: - elements.sort( - key=lambda x: x.ec_contribution or 0, - reverse=projects_filtering_properties.sort_direction == SortDirection.DESC, - ) - start = projects_filtering_properties.page * projects_filtering_properties.size - end = start + projects_filtering_properties.size - elements = elements[start:end] - - return EuOrganizationProjectSummaryPage( - elements=elements, - total=total_projects, - page=projects_filtering_properties.page, - size=projects_filtering_properties.size, - ) - - -def get_organization_project_contributions( - organization_names: List[str], -) -> Dict[str, EuOrganizationShort]: - - source = ["projectID", "organisationID", "ecContribution"] - - query = { - "terms": { - "name.keyword": [ - name.upper() for name in organization_names if name.strip() - ], - } - } - - response = elasticsearch.search( - index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, - cluster=ESCluster.INSE, - source=source, - size=10000, - query=query, - ) - - logger.debug( - f"Received organization project contributions response: {json.dumps(response, indent=2)}" - ) - - organization_project_contributions = _process_organization_project_contributions( - response - ) - - logger.debug( - f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}" - ) - - return organization_project_contributions - - -def _process_organization_project_contributions( - response: Dict[str, Any], -) -> Dict[str, EuOrganizationShort]: - hits_block = response.get("hits", {}) - project_contributions: Dict[str, EuOrganizationShort] = {} - for hit in hits_block.get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("projectID") - organization_id = source.get("organisationID") - ec_contribution = source.get("ecContribution") - if project_id and organization_id: - project_contributions[project_id] = EuOrganizationShort( - project_id=project_id, - organization_id=organization_id, - ec_contribution=ec_contribution, - ) - return project_contributions - - -def get_projects( - project_contributions: List[EuOrganizationShort], - projects_filtering_properties: ProjectsFilteringProperties, -) -> Tuple[int, Dict[str, EuProjectShort]]: - project_ids = [contribution.project_id for contribution in project_contributions] - - source = ["id", "title", "startDate", "endDate", "acronym"] - - query = { - "terms": { - "id": project_ids, - } - } - - if ( - projects_filtering_properties.query - and projects_filtering_properties.query.strip() - ): - query = { - "bool": { - "must": [ - { - "match_phrase_prefix": { - "title": { - "query": projects_filtering_properties.query, - "max_expansions": 50, - } - } - } - ], - "filter": query, - } - } - - # Project contributions have been filtered before based on ecContribution - if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: - response = elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - source=source, - query=query, - size=10000, - ) - else: - response = elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, - source=source, - query=query, - size=projects_filtering_properties.size, - offset=projects_filtering_properties.page - * projects_filtering_properties.size, - sort=[ - { - projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): { - "order": projects_filtering_properties.sort_direction - } - } - ], - ) - - return _process_projects_response(response) - - -def _process_projects_response( - response: Dict[str, Any], -) -> Tuple[int, Dict[str, EuProjectShort]]: - hits_block = response.get("hits", {}) - total = hits_block.get("total", {}).get("value", 0) - projects: Dict[str, EuProjectShort] = {} - for hit in hits_block.get("hits", []): - source = hit.get("_source", {}) - project_id = source.get("id") - title = source.get("title") - start_date = source.get("startDate") - end_date = source.get("endDate") - acronym = source.get("acronym") - if not project_id: - continue - projects[project_id] = EuProjectShort( - id=project_id, - title=title, - start_date=start_date, - end_date=end_date, - acronym=acronym, - ) - - return total, projects - - -def _merge_project_data( - projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort] -) -> List[EuOrganizationProjectSummary]: - merged_data = [] - for project_id, project_info in projects.items(): - contribution_info = contributions.get(project_id) - if contribution_info: - merged_entry = EuOrganizationProjectSummary( - project_id=project_id, - title=project_info.title, - start_date=project_info.start_date, - end_date=project_info.end_date, - acronym=project_info.acronym, - organization_id=contribution_info.organization_id, - ec_contribution=contribution_info.ec_contribution, - ) - merged_data.append(merged_entry) - return merged_data diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 4f35c69b..75c72e0e 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optional, Set from inse.projects import projects_search_client from inse.projects.projects_search_client import ( - get_organization_project_contributions_foo, + get_eu_organization_project_contributions, ) from inse.projects.model import ( BundProjectPage, @@ -90,12 +90,8 @@ def get_bund_projects_by_institution_id( f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) response = projects_search_client.search_bund_projects( - page=filtering_properties.page, - size=filtering_properties.size, institution_names=institution_aliases, - topic=filtering_properties.query, - sort_by=filtering_properties.sort_by, - sort_direction=filtering_properties.sort_direction, + filter_properties=filtering_properties, ) logger.debug(f"get_bund_projects_by_institution_id response: {response}") return response @@ -137,7 +133,7 @@ def get_cordis_eu_projects_by_institution_id( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - page = get_organization_project_contributions_foo( + page = get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=projects_filtering_properties, ) @@ -186,7 +182,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id ) ) - page = get_organization_project_contributions_foo( + page = get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, @@ -220,8 +216,11 @@ def get_institution_bund_projects_funding_over_time( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) response = projects_search_client.search_bund_projects( - page=0, - size=10000, + filter_properties=ProjectsFilteringProperties( + project_type=ProjectType.BUND, + page=0, + size=10000, + ), institution_names=institution_aliases, ) From d89d1ded98092eaac08bdbb72464abee8f4e0256 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 21 Jun 2026 18:51:30 +0200 Subject: [PATCH 23/53] changed k and num_candidates. Low number leads to ignored Keyword vectors --- service/src/main/inse/topics/logic.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index 94646f16..9c460f3f 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -318,20 +318,20 @@ async def vector_search_topics( "knn": { "field": "display_name_vector", "query_vector": query_vector, - "k": limit, - "num_candidates": 100, "similarity": SIMILARITY_THRESHOLD, - "boost": BOOST_DISPLAY_NAME_VECTOR + "boost": BOOST_DISPLAY_NAME_VECTOR, + "k": 500, + "num_candidates": 500 } }, { "knn": { "field": "description_vector", "query_vector": query_vector, - "k": limit, - "num_candidates": 100, "similarity": SIMILARITY_THRESHOLD, - "boost": BOOST_DESCRIPTION_VECTOR + "boost": BOOST_DESCRIPTION_VECTOR, + "k": 500, + "num_candidates": 500 } }, { @@ -341,9 +341,9 @@ async def vector_search_topics( "knn": { "field": "keyword_vectors.vector", "query_vector": query_vector, - "k": limit, - "num_candidates": 100, - "similarity": SIMILARITY_THRESHOLD + "similarity": SIMILARITY_THRESHOLD, + "k": 500, + "num_candidates": 500 } }, "score_mode": "max", From 479c144c8b15600c96e8297b10728d3900d6e890 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 21 Jun 2026 19:01:41 +0200 Subject: [PATCH 24/53] removed logging --- service/src/data/search_scores.json | 114 ------------------- service/src/main/inse/topics/logic.py | 7 -- service/src/main/inse/topics/score_logger.py | 36 ------ 3 files changed, 157 deletions(-) delete mode 100644 service/src/data/search_scores.json delete mode 100644 service/src/main/inse/topics/score_logger.py diff --git a/service/src/data/search_scores.json b/service/src/data/search_scores.json deleted file mode 100644 index 303a117b..00000000 --- a/service/src/data/search_scores.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "query": "localization", - "max_score": 23.237041, - "results": [ - { - "topic_name": "Indoor and Outdoor Localization Technologies", - "score": 23.237041 - }, - { - "topic_name": "Robotics and Sensor-Based Localization", - "score": 21.511477 - }, - { - "topic_name": "Spectral Theory in Mathematical Physics", - "score": 14.039959 - }, - { - "topic_name": "Socioeconomic Development in MENA", - "score": 11.518878 - }, - { - "topic_name": "Electrical Fault Detection and Protection", - "score": 10.770052 - }, - { - "topic_name": "Machine Learning in Bioinformatics", - "score": 10.322677 - }, - { - "topic_name": "Software System Performance and Reliability", - "score": 10.112644 - }, - { - "topic_name": "Quantum many-body systems", - "score": 10.112644 - }, - { - "topic_name": "Random lasers and scattering media", - "score": 10.112644 - }, - { - "topic_name": "Insect Pheromone Research and Control", - "score": 9.910988 - }, - { - "topic_name": "Tactile and Sensory Interactions", - "score": 9.910988 - }, - { - "topic_name": "Handwritten Text Recognition Techniques", - "score": 9.910988 - }, - { - "topic_name": "Integrated Circuits and Semiconductor Failure Analysis", - "score": 9.910988 - }, - { - "topic_name": "Medical Imaging and Analysis", - "score": 9.7172165 - }, - { - "topic_name": "Microwave Imaging and Scattering Analysis", - "score": 9.7172165 - }, - { - "topic_name": "Neurology and Historical Studies", - "score": 9.7172165 - }, - { - "topic_name": "High-Velocity Impact and Material Behavior", - "score": 9.7172165 - }, - { - "topic_name": "Software Engineering Research", - "score": 9.530875 - }, - { - "topic_name": "Software Testing and Debugging Techniques", - "score": 9.530875 - }, - { - "topic_name": "Digital Media Forensic Detection", - "score": 9.530875 - }, - { - "topic_name": "Infrared Thermography in Medicine", - "score": 9.351548 - }, - { - "topic_name": "Explainable Artificial Intelligence (XAI)", - "score": 9.351548 - }, - { - "topic_name": "Underwater Vehicles and Communication Systems", - "score": 9.351548 - }, - { - "topic_name": "Diffusion and Search Dynamics", - "score": 8.8518915 - }, - { - "topic_name": "Direction-of-Arrival Estimation Techniques", - "score": 5.968384 - }, - { - "topic_name": "Retinal Imaging and Analysis", - "score": 5.6107 - }, - { - "topic_name": "Radar Systems and Signal Processing", - "score": 4.721418 - } - ] -} diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index 9c460f3f..ee0972fc 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -380,13 +380,6 @@ async def vector_search_topics( # 3. Format result hits = raw_results.get("hits", {}).get("hits", []) - # Log scores to JSON for threshold analysis TODO: Remove after finetune - try: - from .score_logger import log_scores_to_json - log_scores_to_json(hits, query) - except Exception as exc: - logger.warning(f"Could not log search scores: {exc}") - total = len(hits) results = [hit.get("_source", {}) for hit in hits] diff --git a/service/src/main/inse/topics/score_logger.py b/service/src/main/inse/topics/score_logger.py deleted file mode 100644 index 0493d9ad..00000000 --- a/service/src/main/inse/topics/score_logger.py +++ /dev/null @@ -1,36 +0,0 @@ -import json -from pathlib import Path -from typing import Any, Dict, List - -def log_scores_to_json(hits: List[Dict[str, Any]], query: str) -> None: - """ - Utility function to log the names and scores of all vector search hits to a JSON file. - This helps in debugging and manually tweaking the similarity score thresholds. - """ - scores_data = [] - for hit in hits: - source = hit.get("_source", {}) - topic_name = source.get("display_name") or source.get("name") or "Unknown" - score = hit.get("_score", 0.0) - scores_data.append({ - "topic_name": topic_name, - "score": score - }) - - - data_dir = Path("/data") - - output_file = data_dir / "search_scores.json" - - log_payload = { - "query": query, - "max_score": hits[0].get("_score", 0.0) if hits else 0.0, - "results": scores_data - } - - try: - with open(output_file, "w", encoding="utf-8") as f: - json.dump(log_payload, f, indent=2, ensure_ascii=False) - print(f"DEBUG: Saved search scores for query '{query}' to {output_file}") - except Exception as exc: - print(f"DEBUG: Failed to save search scores: {exc}") From 3249a8569b50ceed5d83cf935f6ff7e0b1f5499e Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 21 Jun 2026 19:43:45 +0200 Subject: [PATCH 25/53] changed topic-hierarchy to use Angular Material tooltip. Fixed Tooltip to also show, when only navigating with tab (no only mouse over) --- .../topic-hierarchy.component.html | 22 +++++--- .../topic-hierarchy.component.scss | 55 +++++++++++++++---- .../topic-hierarchy.component.ts | 2 + 3 files changed, 61 insertions(+), 18 deletions(-) diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html index 08e8e6fd..f6bfaca2 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html @@ -48,8 +48,13 @@ @for (topic of filteredFlatTopics; track topic.id) {
+ (change)="toggleTopic(topic.name)" + [matTooltip]="topic.name" + matTooltipPosition="above" + (focusin)="tooltip.show()" + (focusout)="tooltip.hide()"> {{ topic.name }} {{ @@ -136,13 +141,16 @@
- {{ topic.name }} + (change)="toggleTopic(topic.name)" + [matTooltip]="topic.name" + matTooltipPosition="above" + (focusin)="tooltip.show()" + (focusout)="tooltip.hide()"> + {{ + topic.name + }}
} diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss index 9be6e396..abfa99bc 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss @@ -2,11 +2,13 @@ width: 100%; max-height: 400px; overflow-y: auto; + overflow-x: hidden; border: 1px solid var(--sg-border); border-radius: var(--sg-radius-sm); background: var(--sg-background); - padding: 4px; + padding: 4px 8px 4px 4px; margin-top: 4px; + box-sizing: border-box; } .loading-state { @@ -55,6 +57,11 @@ font-size: 12px; color: var(--sg-text); font-weight: 500; + display: block; + width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .topic-path { @@ -92,7 +99,7 @@ width: 100%; background: transparent; border: none; - padding: 4px 6px; + padding: 4px; text-align: left; cursor: pointer; border-radius: 4px; @@ -122,6 +129,7 @@ white-space: nowrap; text-overflow: ellipsis; overflow: hidden; + min-width: 0; } } @@ -158,37 +166,62 @@ } .domain-children { - padding-left: 12px; + padding-left: 10px; border-left: 1px solid var(--sg-border-soft); margin-left: 12px; margin-bottom: 4px; } .field-children { - padding-left: 14px; + padding-left: 10px; border-left: 1px solid var(--sg-border-soft); - margin-left: 14px; + margin-left: 12px; } .subfield-children { - padding-left: 14px; + padding-left: 10px; border-left: 1px dashed var(--sg-border-soft); - margin-left: 14px; + margin-left: 12px; margin-bottom: 2px; } .tree-leaf { padding: 2px 4px; + width: 100%; + box-sizing: border-box; } .topic-node { + width: 100%; + box-sizing: border-box; + .topic-label { font-size: 11px; color: var(--sg-text); - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; display: block; - max-width: 190px; + width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +mat-checkbox { + display: block !important; + width: 100% !important; + + ::ng-deep { + .mdc-form-field { + width: 100% !important; + display: flex !important; + align-items: center; + } + + .mdc-label { + flex: 1 !important; + min-width: 0 !important; + overflow: hidden; + padding-left: 8px !important; + } } } diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts index 20060484..22c8d34e 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts @@ -11,6 +11,7 @@ import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatRadioModule } from '@angular/material/radio'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { TopicsService } from '../../api/api/topics.service'; import { Subject, of } from 'rxjs'; import { @@ -55,6 +56,7 @@ interface FlatTopic { MatIconModule, MatProgressSpinnerModule, MatRadioModule, + MatTooltipModule, ], templateUrl: './topic-hierarchy.component.html', styleUrl: './topic-hierarchy.component.scss', From 84747b9efb004ae0b8df48449ade3906c8297cb2 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 21 Jun 2026 20:39:04 +0200 Subject: [PATCH 26/53] refactor frontend (changed old decorator Input, Output to modern signals. Added URL parameters to safe topic filer) --- .../person-card/person-card.component.html | 66 ++++----- .../person-card/person-card.component.scss | 22 ++- .../person-card/person-card.component.ts | 125 ++++++++++-------- .../person-list/person-list.component.html | 40 ++++-- .../person-list/person-list.component.scss | 27 +++- .../person-list/person-list.component.ts | 72 +++++++--- .../topic-hierarchy.component.html | 10 +- .../topic-hierarchy.component.ts | 65 +++------ 8 files changed, 256 insertions(+), 171 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index df244ae9..725b6617 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -1,8 +1,8 @@
- + -
- {{ getInitials(person.display_name) }} +
+ {{ initials() }}
@@ -11,41 +11,43 @@ (click)=" toggleBookmark(); $event.stopPropagation(); $event.preventDefault() " - [class.bookmarked]="isBookmarked" + [class.bookmarked]="isBookmarked()" aria-label="Bookmark person"> {{ - isBookmarked ? 'bookmark' : 'bookmark_border' + isBookmarked() ? 'bookmark' : 'bookmark_border' }}

- {{ person.display_name ?? '' }} + [title]="person().display_name ?? ''"> + {{ person().display_name ?? '' }}

-

- {{ getDistinguishingId(person) }} +

+ {{ distinguishingId() }}

-

- {{ getStatsString() }} +

+ {{ statsString() }}

-

- {{ getHIndexString() }} +

+ {{ hIndexString() }}

- @if (institution(person); as inst) { + @if (institution(); as inst) {
- + "> {{ inst.display_name ?? '' }} - @if (inst.country_code && !loading) { + @if (inst.country_code && !loading()) { {{ inst.country_code.toUpperCase() }} } - +
}
- @for (topic of topics(person); track topic.id) { - {{ topic.display_name }} + "> + {{ topic.display_name }} + }
@@ -56,14 +60,18 @@
Sortierung:
- - @@ -132,19 +140,23 @@ @if (topicSearchControl.value) { }
@@ -158,6 +170,7 @@ type="text" [formControl]="institutionControl" [matAutocomplete]="auto" + aria-label="Institution suchen" placeholder="Institution suchen..." (keyup.enter)="applySidebarFilters()" /> + (click)="clearInstitutionFilter()" + aria-label="Institution zurücksetzen"> close } @@ -198,7 +212,8 @@ "> + (change)="applySidebarFilters()" + aria-label="Zusammenarbeit nach Jahr filtern"> Zusammenarbeit nach Jahr filtern + style="display: flex; gap: 16px" + aria-label="Modus für Jahresfilter"> Genau in @if (filterYearControl.hasError('min')) { Jahr muss ≥ 1900 sein @@ -255,7 +272,10 @@ @@ -106,11 +91,7 @@ - - +
diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 95ff7534..47a6389e 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -41,10 +41,6 @@ } } -mat-paginator { - background-color: var(--sg-background); -} - .card { padding: 0.5rem; background-color: var(--sg-background); diff --git a/webapp/src/app/modules/institutions/institutions.component.ts b/webapp/src/app/modules/institutions/institutions.component.ts index e2449349..18eea25f 100644 --- a/webapp/src/app/modules/institutions/institutions.component.ts +++ b/webapp/src/app/modules/institutions/institutions.component.ts @@ -1,26 +1,28 @@ -import { Component, effect, input, signal } from '@angular/core'; +import { Component, input } from '@angular/core'; import { Institution, InstitutionPage } from '../../api'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; -import { MatInputModule } from '@angular/material/input'; -import { ActivatedRoute, Router, RouterModule } from '@angular/router'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { RouterModule } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; -import { DebounceDirective } from '../../directives/debounce.directive'; -import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { MatDividerModule } from '@angular/material/divider'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; @Component({ selector: 'app-institutions', imports: [ MatButtonModule, MatCardModule, - MatInputModule, MatIconModule, - DebounceDirective, - MatPaginator, MatDividerModule, RouterModule, + QueryParamPaginatorComponent, + QueryParamSelectorComponent, + QueryParamInputComponent, ], templateUrl: './institutions.component.html', styleUrl: './institutions.component.scss', @@ -28,74 +30,21 @@ import { MatDividerModule } from '@angular/material/divider'; export class InstitutionsComponent { institutionPage = input.required(); - urlSearchTerm = signal(''); - urlSortBy = signal('relevance'); - urlSortingOrder = signal('desc'); - - constructor( - private readonly activatedRoute: ActivatedRoute, - private readonly router: Router, - ) { - this.activatedRoute.queryParams - .pipe(takeUntilDestroyed()) - .subscribe((params) => { - this.urlSearchTerm.set(params['search'] || ''); - this.urlSortBy.set(params['sort_by'] || 'relevance'); - this.urlSortingOrder.set(params['sorting_order'] || 'desc'); - }); - - effect(() => { - const searchTerm = this.urlSearchTerm(); - this.router.navigate([], { - queryParams: { search: searchTerm }, - queryParamsHandling: 'merge', - }); - }); - } - - handleSearchTermChange(newTerm: string): void { - this.router.navigate([], { - queryParams: { search: newTerm }, - queryParamsHandling: 'merge', - }); - } - - clearSearchTerm(): void { - this.router.navigate([], { - queryParams: { search: null }, - queryParamsHandling: 'merge', - }); - } - - handlePageChange(event: PageEvent): void { - this.router.navigate([], { - queryParams: { page: event.pageIndex, size: event.pageSize }, - queryParamsHandling: 'merge', - }); - } + sortingOptions: SelectorOption[] = [ + { value: 'relevance', display_name: 'Relevanz' }, + { value: 'name', display_name: 'Name' }, + { value: 'works_count', display_name: 'Anzahl Publikationen' }, + { value: 'citations_count', display_name: 'Anzahl Zitationen' }, + ]; + sortingDirectionOptions: SelectorOption[] = [ + { value: 'asc', display_name: 'Aufsteigend' }, + { value: 'desc', display_name: 'Absteigend' }, + ]; extractInstitutionId(institution: Institution): string { return institution.id?.split('/').pop() ?? ''; } - handleSortFieldChange(event: Event): void { - const selectElement = event.target as HTMLSelectElement; - const sortField = selectElement.value; - this.router.navigate([], { - queryParams: { sort_by: sortField }, - queryParamsHandling: 'merge', - }); - } - - handleSortOrderChange(event: Event): void { - const selectElement = event.target as HTMLSelectElement; - const sortOrder = selectElement.value; - this.router.navigate([], { - queryParams: { sorting_order: sortOrder }, - queryParamsHandling: 'merge', - }); - } - getDisplayName(institution: Institution): string { const primary = institution.display_name?.trim(); if (primary && primary.length > 0) return primary; diff --git a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html new file mode 100644 index 00000000..8ce973c0 --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html @@ -0,0 +1,13 @@ + + {{ this.label() }} + + search + + diff --git a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.scss b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts new file mode 100644 index 00000000..85d396f1 --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts @@ -0,0 +1,63 @@ +import { Component, computed, inject, input, output } from '@angular/core'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { DebounceDirective } from '../../../directives/debounce.directive'; +import { MatInputModule } from '@angular/material/input'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { ActivatedRoute, Router } from '@angular/router'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; + +@Component({ + selector: 'app-query-param-input', + imports: [ + FormsModule, + MatInputModule, + MatButtonModule, + MatIconModule, + MatFormFieldModule, + DebounceDirective, + ], + templateUrl: './query-param-input.component.html', + styleUrl: './query-param-input.component.scss', +}) +export class QueryParamInputComponent { + queryParamKey = input.required(); + queryParamPageKey = input('page'); + label = input('Suchen'); + debounceTime = input(300); + handleValueChange = output(); + + private readonly activatedRouter = inject(ActivatedRoute); + private readonly router = inject(Router); + + private readonly queryParams = toSignal( + this.activatedRouter.queryParams.pipe(takeUntilDestroyed()), + ); + + _urlValue = computed(() => { + const params = this.queryParams(); + const key = this.queryParamKey(); + + return params && key ? params[key] || '' : ''; + }); + + clearInput(): void { + this.router.navigate([], { + queryParams: { [this.queryParamKey()]: null }, + queryParamsHandling: 'merge', + }); + } + + _handleValueChange(newValue: string): void { + this.handleValueChange?.emit(newValue); + + this.router.navigate([], { + queryParams: { + [this.queryParamKey()]: newValue || null, + [this.queryParamPageKey()]: 0, + }, + queryParamsHandling: 'merge', + }); + } +} diff --git a/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.html b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.html new file mode 100644 index 00000000..ea5f4947 --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.html @@ -0,0 +1,6 @@ + diff --git a/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.scss b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.scss new file mode 100644 index 00000000..bb582c94 --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.scss @@ -0,0 +1,3 @@ +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts new file mode 100644 index 00000000..63a0bd8f --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts @@ -0,0 +1,52 @@ +import { Component, computed, inject, input, output } from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { ActivatedRoute, Router } from '@angular/router'; + +@Component({ + selector: 'app-query-param-paginator', + imports: [MatPaginatorModule], + templateUrl: './query-param-paginator.component.html', + styleUrl: './query-param-paginator.component.scss', +}) +export class QueryParamPaginatorComponent { + queryParamPageKey = input('page'); + queryParamSizeKey = input('size'); + pageSizeOptions = input([10, 25, 50]); + + total = input.required(); + + handlePageChange = output(); + + private readonly activatedRoute = inject(ActivatedRoute); + private readonly router = inject(Router); + + private readonly queryParams = toSignal( + this.activatedRoute.queryParams.pipe(takeUntilDestroyed()), + ); + + _urlPage = computed(() => { + const params = this.queryParams(); + const key = this.queryParamPageKey(); + + return params && key ? +params[key] || 0 : 0; + }); + + _urlSize = computed(() => { + const params = this.queryParams(); + const key = this.queryParamSizeKey(); + + return params && key ? +params[key] || 10 : 10; + }); + + _handlePageChange(event: PageEvent): void { + this.handlePageChange?.emit(event); + this.router.navigate([], { + queryParams: { + [this.queryParamPageKey()]: event.pageIndex || null, + [this.queryParamSizeKey()]: event.pageSize || null, + }, + queryParamsHandling: 'merge', + }); + } +} diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html new file mode 100644 index 00000000..0f6dcd9b --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html @@ -0,0 +1,5 @@ + diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.scss b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.scss new file mode 100644 index 00000000..d1990896 --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.scss @@ -0,0 +1,10 @@ +select { + padding: 0.75rem; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + font-size: 1rem; +} + +select:hover { + cursor: pointer; +} diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts new file mode 100644 index 00000000..caa3f7bf --- /dev/null +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts @@ -0,0 +1,46 @@ +import { Component, computed, inject, input, output } from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { ActivatedRoute, Router } from '@angular/router'; + +export type SelectorOption = { + value: string; + display_name: string; +}; + +@Component({ + selector: 'app-query-param-selector', + imports: [FormsModule], + templateUrl: './query-param-selector.component.html', + styleUrl: './query-param-selector.component.scss', +}) +export class QueryParamSelectorComponent { + options = input.required(); + queryParamKey = input.required(); + handleSelectionChange = output(); + + private readonly activatedRoute = inject(ActivatedRoute); + private readonly router = inject(Router); + + private readonly queryParams = toSignal( + this.activatedRoute.queryParams.pipe(takeUntilDestroyed()), + ); + + _urlValue = computed(() => { + const params = this.queryParams(); + const key = this.queryParamKey(); + + return params && key ? params[key] || '' : ''; + }); + + _handleSelectionChange(event: Event): void { + const newValue = (event.target as HTMLSelectElement).value; + + this.router.navigate([], { + queryParams: { [this.queryParamKey()]: newValue }, + queryParamsHandling: 'merge', + }); + + this.handleSelectionChange.emit(event); + } +} From 70ed62a220377b7a5db4309b5da2155fbd38c176 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 21 Jun 2026 22:48:04 +0200 Subject: [PATCH 33/53] Updated projects to use query params components --- .../modules/projects/projects.component.html | 43 ++++------ .../modules/projects/projects.component.ts | 78 ++++--------------- 2 files changed, 30 insertions(+), 91 deletions(-) diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 8d2a3884..0ae1e25c 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -4,19 +4,11 @@
- - Suche nach Namen - - search - - + +
- + - +
@@ -102,11 +91,7 @@ - - +
diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts index 4fc6f46d..effdc3f4 100644 --- a/webapp/src/app/modules/projects/projects.component.ts +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -1,33 +1,34 @@ -import { Component, effect, input, signal } from '@angular/core'; +import { Component, input, signal } from '@angular/core'; import { FundingProject, FundingProjectPage, ProjectType } from '../../api'; import { MatDividerModule } from '@angular/material/divider'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { DebounceDirective } from '../../directives/debounce.directive'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; -import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { DatePipe, UpperCasePipe } from '@angular/common'; import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; @Component({ selector: 'app-projects', imports: [ MatDividerModule, - MatFormFieldModule, - DebounceDirective, MatIconModule, MatCardModule, RouterModule, - MatPaginator, - MatInputModule, MatButtonModule, UpperCasePipe, DatePipe, MatChipsModule, + QueryParamInputComponent, + QueryParamPaginatorComponent, + QueryParamSelectorComponent, ], templateUrl: './projects.component.html', styleUrl: './projects.component.scss', @@ -35,11 +36,14 @@ import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; export class ProjectsComponent { fundingProjectPage = input.required(); - urlSearchTerm = signal(''); - urlSortBy = signal('relevance'); - urlSortingOrder = signal('desc'); urlChips = signal(['eu', 'bund', 'dfg']); + sortingOptions: SelectorOption[] = [{ value: 'title', display_name: 'Name' }]; + sortingDirectionOptions: SelectorOption[] = [ + { value: 'asc', display_name: 'Aufsteigend' }, + { value: 'desc', display_name: 'Absteigend' }, + ]; + constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, @@ -47,60 +51,10 @@ export class ProjectsComponent { this.activatedRoute.queryParams .pipe(takeUntilDestroyed()) .subscribe((params) => { - this.urlSearchTerm.set(params['search'] || ''); - this.urlSortBy.set(params['sort_by'] || 'relevance'); - this.urlSortingOrder.set(params['sorting_order'] || 'desc'); this.urlChips.set( (params['selected_project_types'] || 'eu,bund,dfg').split(','), ); }); - - effect(() => { - const searchTerm = this.urlSearchTerm(); - this.router.navigate([], { - queryParams: { search: searchTerm }, - queryParamsHandling: 'merge', - }); - }); - } - - handleSearchTermChange(newTerm: string): void { - this.router.navigate([], { - queryParams: { search: newTerm, page: 0, size: 10 }, - queryParamsHandling: 'merge', - }); - } - - clearSearchTerm(): void { - this.router.navigate([], { - queryParams: { search: null }, - queryParamsHandling: 'merge', - }); - } - - handlePageChange(event: PageEvent): void { - this.router.navigate([], { - queryParams: { page: event.pageIndex, size: event.pageSize }, - queryParamsHandling: 'merge', - }); - } - - handleSortFieldChange(event: Event): void { - const selectElement = event.target as HTMLSelectElement; - const sortField = selectElement.value; - this.router.navigate([], { - queryParams: { sort_by: sortField }, - queryParamsHandling: 'merge', - }); - } - - handleSortOrderChange(event: Event): void { - const selectElement = event.target as HTMLSelectElement; - const sortOrder = selectElement.value; - this.router.navigate([], { - queryParams: { sorting_order: sortOrder }, - queryParamsHandling: 'merge', - }); } handleChipBoxChange(change: MatChipListboxChange): void { From 7e95b46779f0f5d1e12527e1a518ed6c89fee2e4 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 21 Jun 2026 23:03:03 +0200 Subject: [PATCH 34/53] add semantic topic legend to interests --- .../person-interesting.component.html | 20 ++++++ .../person-interesting.component.scss | 57 +++++++++++++++++ .../person-interesting.component.ts | 63 +++++++++++++++++++ 3 files changed, 140 insertions(+) diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index 11b6989a..9c2c9214 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -6,6 +6,26 @@ article Anzahl Publikationen zum Thema + @if (legendGroups().length > 0) { +
+ @for (group of legendGroups(); track group.id) { + + {{ group.name }} + + @for (item of group.items; track item.id) { + + + {{ item.name }} + + } + + + } +
+ } }
diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.scss b/webapp/src/app/modules/person-interesting/person-interesting.component.scss index 1405142c..e7626219 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.scss +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.scss @@ -14,6 +14,7 @@ display: flex; align-items: baseline; gap: 10px; + flex-wrap: wrap; margin: 0 0 18px; } @@ -44,6 +45,62 @@ line-height: 1; } +.interest-legend { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + min-width: 0; +} + +.interest-legend-group { + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + min-height: 22px; + padding: 3px 7px; + border: 1px solid #dbe5f6; + border-radius: 999px; + background: rgba(255, 255, 255, 0.68); +} + +.interest-legend-field { + flex: 0 0 auto; + color: #1b2a4a; + font-size: 10px; + font-weight: 800; + line-height: 1.2; +} + +.interest-legend-items { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 7px; + min-width: 0; +} + +.interest-legend-item { + display: inline-flex; + align-items: center; + gap: 4px; + min-width: 0; + color: #53617e; + font-size: 10px; + font-weight: 600; + line-height: 1.2; +} + +.interest-legend-dot { + flex: 0 0 auto; + width: 7px; + height: 7px; + border: 1px solid rgba(255, 255, 255, 0.85); + border-radius: 50%; + box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.12); +} + .interest-tags .interest-empty { padding: 9px 16px; border: 1px solid #e2e8f0; diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index 2b1ad2d1..1ad7f595 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -12,6 +12,22 @@ interface InterestTag { count: number; description: string; color: string; + subfieldId: string; + subfieldName: string; + fieldId: string; + fieldName: string; +} + +interface InterestLegendGroup { + id: string; + name: string; + items: InterestLegendItem[]; +} + +interface InterestLegendItem { + id: string; + name: string; + color: string; } const MAX_TAGS = 5; @@ -41,12 +57,59 @@ export class PersonInterestingComponent { count: topic.count ?? 0, description: (topic.description ?? '').trim(), color: topicHierarchyColor(topic), + subfieldId: topic.subfield_id ?? '', + subfieldName: (topic.subfield_name ?? '').trim(), + fieldId: topic.field_id ?? '', + fieldName: (topic.field_name ?? '').trim(), }); } return tags.sort((a, b) => b.count - a.count).slice(0, MAX_TAGS); }); + readonly legendGroups = computed(() => { + const groups = new Map(); + + for (const tag of this.tags()) { + if (!tag.subfieldName) { + continue; + } + + const fieldName = tag.fieldName || 'Ohne Field'; + const fieldId = tag.fieldId || fieldName.toLowerCase(); + const subfieldId = tag.subfieldId || tag.subfieldName.toLowerCase(); + + if (!groups.has(fieldId)) { + groups.set(fieldId, { + id: fieldId, + name: fieldName, + items: [], + }); + } + + const group = groups.get(fieldId); + + if (!group || group.items.some((item) => item.id === subfieldId)) { + continue; + } + + group.items.push({ + id: subfieldId, + name: tag.subfieldName, + color: tag.color, + }); + } + + return [...groups.values()] + .map((group) => ({ + ...group, + items: group.items.sort((left, right) => + left.name.localeCompare(right.name), + ), + })) + .sort((left, right) => left.name.localeCompare(right.name)); + }); + onTagClick(tag: InterestTag): void { if (!tag.id) return; this.tagClick.emit({ id: tag.id, name: tag.label }); From f8c7b1daacda78330e8f5ba39377933d1aa82125 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 21 Jun 2026 23:03:13 +0200 Subject: [PATCH 35/53] add grouped subfield legend to timeline --- .../research-timeline.component.html | 39 +++++ .../research-timeline.component.scss | 74 ++++++++ .../research-timeline.component.ts | 158 ++++++++++++++++++ 3 files changed, 271 insertions(+) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index 46eb050e..40624f96 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -7,6 +7,45 @@ (basierend auf Publikationen)

+
+
+ {{ group.name }} + + + + + {{ item.name }} + + +
+ + +
+ - + + @@ -37,11 +28,9 @@ (sortChange)="handleSortChange($event)" /> - +
diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.ts b/webapp/src/app/modules/institution-projects/institution-projects.component.ts index cb1fc8bb..53d38360 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.ts +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.ts @@ -19,7 +19,6 @@ import { import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs'; -import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { FormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { @@ -29,11 +28,12 @@ import { import { CurrencyPipe, DatePipe } from '@angular/common'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { Sort, SortDirection } from '@angular/material/sort'; -import { DebounceDirective } from '../../directives/debounce.directive'; import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component'; import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; type BundProjectRow = { id: string; @@ -58,18 +58,18 @@ type EuProjectRow = { MatCardModule, MatFormFieldModule, MatTabsModule, - MatPaginatorModule, FormsModule, MatInputModule, DataTableComponent, DatePipe, CurrencyPipe, - DebounceDirective, MatIconModule, MatButtonModule, InstitutionProjectsFundingGraphComponent, PersonNetworkInfoCardComponent, RouterModule, + QueryParamPaginatorComponent, + QueryParamInputComponent, ], templateUrl: './institution-projects.component.html', styleUrl: './institution-projects.component.scss', @@ -119,7 +119,6 @@ export class InstitutionProjectsComponent implements OnInit { urlSortKey = signal(''); urlSortDirection = signal(''); - urlSearchTerm = signal(''); constructor( private readonly activatedRoute: ActivatedRoute, @@ -132,7 +131,6 @@ export class InstitutionProjectsComponent implements OnInit { this.urlSortDirection.set( (params['sort_direction'] as SortDirection) ?? '', ); - this.urlSearchTerm.set(params['search'] ?? ''); }); effect(() => { @@ -151,20 +149,6 @@ export class InstitutionProjectsComponent implements OnInit { : []; } }); - - effect(() => { - const searchTerm = this.urlSearchTerm(); - if (searchTerm) { - this.router.navigate([], { - queryParams: { search: searchTerm, page: 0, size: 10 }, - queryParamsHandling: 'merge', - }); - } - }); - - effect(() => { - console.log('Funding over time data:', this.bundProjectsFunding()); - }); } readonly queryParams = toSignal(this.activatedRoute.queryParamMap, { @@ -175,12 +159,6 @@ export class InstitutionProjectsComponent implements OnInit { return this.queryParams()?.get('project_tab') ?? 'eu'; }); - readonly page = computed(() => { - const pageParam = this.queryParams()?.get('page'); - const page = pageParam ? Number.parseInt(pageParam, 10) : 0; - return Number.isNaN(page) ? 0 : page; - }); - readonly selectedPage = computed(() => { if (this.displayedProjects() === 'eu') { return this.cordisEuProjectPage(); @@ -193,14 +171,6 @@ export class InstitutionProjectsComponent implements OnInit { return this.selectedPage()?.total ?? 0; }); - readonly pageSize = computed(() => { - return this.selectedPage()?.size ?? 10; - }); - - readonly pageIndex = computed(() => { - return this.selectedPage()?.page ?? 0; - }); - ngOnInit(): void { this.euProjectColumns = [ { @@ -320,31 +290,10 @@ export class InstitutionProjectsComponent implements OnInit { }); } - handlePageChange(event: PageEvent): void { - this.router.navigate([], { - queryParams: { page: event.pageIndex, size: event.pageSize }, - queryParamsHandling: 'merge', - }); - } - handleSortChange(event: Sort): void { this.router.navigate([], { queryParams: { sort_by: event.active, sort_direction: event.direction }, queryParamsHandling: 'merge', }); } - - handleSearchTermChange(newTerm: string): void { - this.router.navigate([], { - queryParams: { search: newTerm, page: 0, size: 10 }, - queryParamsHandling: 'merge', - }); - } - - clearSearchTerm(): void { - this.router.navigate([], { - queryParams: { search: null, page: 0, size: 10 }, - queryParamsHandling: 'merge', - }); - } } diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 47a6389e..7303fdd7 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -25,22 +25,10 @@ .cards { display: grid; gap: 1.5rem; - grid-template-columns: repeat(4, 1fr); + grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); padding: 0 1rem; } -@media (max-width: 900px) { - .cards { - grid-template-columns: repeat(2, 1fr); - } -} - -@media (max-width: 600px) { - .cards { - grid-template-columns: 1fr; - } -} - .card { padding: 0.5rem; background-color: var(--sg-background); diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index e33bdee6..7faf7c59 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -5,19 +5,7 @@
- - Suche nach Titel - - search - - + - +
diff --git a/webapp/src/app/modules/person-projects/person-projects.component.ts b/webapp/src/app/modules/person-projects/person-projects.component.ts index 9e208870..baf3be30 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.ts +++ b/webapp/src/app/modules/person-projects/person-projects.component.ts @@ -24,12 +24,11 @@ import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; -import { DebounceDirective } from '../../directives/debounce.directive'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { Sort, SortDirection } from '@angular/material/sort'; import { CurrencyPipe, DatePipe } from '@angular/common'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; @Component({ selector: 'app-person-projects', @@ -41,11 +40,11 @@ import { CurrencyPipe, DatePipe } from '@angular/common'; MatTabsModule, MatFormFieldModule, MatInputModule, - DebounceDirective, - MatPaginatorModule, RouterModule, DatePipe, CurrencyPipe, + QueryParamPaginatorComponent, + QueryParamInputComponent, ], templateUrl: './person-projects.component.html', styleUrl: './person-projects.component.scss', @@ -82,7 +81,6 @@ export class PersonProjectsComponent implements OnInit { 'euProjectsActionsTmp', ); - urlSearchTerm = signal(''); urlSortKey = signal(''); urlSortDirection = signal(''); @@ -90,47 +88,18 @@ export class PersonProjectsComponent implements OnInit { return this.dfgProjectPage()?.total ?? 0; }); - readonly pageSize = computed(() => { - return this.dfgProjectPage()?.size ?? 10; - }); - - readonly pageIndex = computed(() => { - return this.dfgProjectPage()?.page ?? 0; - }); - constructor( private readonly router: Router, private readonly activatedRoute: ActivatedRoute, ) { - this.activatedRoute.queryParamMap - .pipe(takeUntilDestroyed()) - .subscribe((params) => { - this.urlSearchTerm.set(params.get('search') || ''); - }); - effect(() => { this.dfgProjectData = this.dfgProjectPage().elements || []; }); effect(() => { - console.log( - 'Updating personCordisEuProjectData with', - this.personCordisEuProjectPage(), - ); - this.personCordisEuProjectData = this.personCordisEuProjectPage().elements || []; }); - - effect(() => { - const searchTerm = this.urlSearchTerm(); - if (searchTerm) { - this.router.navigate([], { - queryParams: { search: searchTerm, page: 0, size: this.pageSize() }, - queryParamsHandling: 'merge', - }); - } - }); } ngOnInit(): void { @@ -197,27 +166,6 @@ export class PersonProjectsComponent implements OnInit { ]; } - handleSearchTermChange(newTerm: string): void { - this.router.navigate([], { - queryParams: { search: newTerm }, - queryParamsHandling: 'merge', - }); - } - - clearSearchTerm(): void { - this.router.navigate([], { - queryParams: { search: null }, - queryParamsHandling: 'merge', - }); - } - - handlePageChange(event: PageEvent): void { - this.router.navigate([], { - queryParams: { page: event.pageIndex, size: event.pageSize }, - queryParamsHandling: 'merge', - }); - } - handleSortChange(event: Sort): void { this.router.navigate([], { queryParams: { sort_by: event.active, sort_direction: event.direction }, diff --git a/webapp/src/app/modules/projects/projects.component.scss b/webapp/src/app/modules/projects/projects.component.scss index e3d0edc0..32a0f31e 100644 --- a/webapp/src/app/modules/projects/projects.component.scss +++ b/webapp/src/app/modules/projects/projects.component.scss @@ -25,22 +25,10 @@ .cards { display: grid; gap: 1.5rem; - grid-template-columns: repeat(4, 1fr); + grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); padding: 0 1rem; } -@media (max-width: 900px) { - .cards { - grid-template-columns: repeat(2, 1fr); - } -} - -@media (max-width: 600px) { - .cards { - grid-template-columns: 1fr; - } -} - mat-paginator { background-color: var(--sg-background); } diff --git a/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts index 63a0bd8f..aa7466bd 100644 --- a/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts +++ b/webapp/src/app/shared/ui/query-param-paginator/query-param-paginator.component.ts @@ -43,8 +43,8 @@ export class QueryParamPaginatorComponent { this.handlePageChange?.emit(event); this.router.navigate([], { queryParams: { - [this.queryParamPageKey()]: event.pageIndex || null, - [this.queryParamSizeKey()]: event.pageSize || null, + [this.queryParamPageKey()]: event.pageIndex || 0, + [this.queryParamSizeKey()]: event.pageSize || 10, }, queryParamsHandling: 'merge', }); From 043db9b7cc4d83fdf304bd3d3838f9ddc91544ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Mon, 22 Jun 2026 15:48:57 +0200 Subject: [PATCH 43/53] Added sort query param manipulation by generic data table --- .../institution-projects.component.html | 10 ++- .../institution-projects.component.ts | 23 +------ .../person-projects.component.html | 9 +-- .../person-projects.component.ts | 19 +----- .../ui/data-table/data-table.component.html | 2 +- .../ui/data-table/data-table.component.ts | 68 ++++++++++++++++--- .../query-param-input.component.ts | 4 +- 7 files changed, 74 insertions(+), 61 deletions(-) diff --git a/webapp/src/app/modules/institution-projects/institution-projects.component.html b/webapp/src/app/modules/institution-projects/institution-projects.component.html index 8d0b6d47..6ad4c8f9 100644 --- a/webapp/src/app/modules/institution-projects/institution-projects.component.html +++ b/webapp/src/app/modules/institution-projects/institution-projects.component.html @@ -15,17 +15,15 @@ + queryParamSortKey="sort_by" + queryParamSortDirectionKey="sort_direction" /> + queryParamSortKey="sort_by" + queryParamSortDirectionKey="sort_direction" /> (''); - urlSortDirection = signal(''); - constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, ) { - this.activatedRoute.queryParams - .pipe(takeUntilDestroyed()) - .subscribe((params) => { - this.urlSortKey.set(params['sort_by'] ?? ''); - this.urlSortDirection.set( - (params['sort_direction'] as SortDirection) ?? '', - ); - }); - effect(() => { const euPage = this.cordisEuProjectPage(); if (euPage) { @@ -289,11 +275,4 @@ export class InstitutionProjectsComponent implements OnInit { queryParamsHandling: 'merge', }); } - - handleSortChange(event: Sort): void { - this.router.navigate([], { - queryParams: { sort_by: event.active, sort_direction: event.direction }, - queryParamsHandling: 'merge', - }); - } } diff --git a/webapp/src/app/modules/person-projects/person-projects.component.html b/webapp/src/app/modules/person-projects/person-projects.component.html index 7faf7c59..ed14000b 100644 --- a/webapp/src/app/modules/person-projects/person-projects.component.html +++ b/webapp/src/app/modules/person-projects/person-projects.component.html @@ -12,14 +12,15 @@ [columns]="dfgProjectColumns" [data]="dfgProjectData" [detailTemplate]="dfgProjectDetailRowTmp" - [activeSortKey]="urlSortKey()" - [sortDirection]="urlSortDirection()" - (sortChange)="handleSortChange($event)" /> + queryParamSortKey="sort_by" + queryParamSortDirectionKey="sort_direction" /> + [data]="personCordisEuProjectData" + queryParamSortKey="sort_by" + queryParamSortDirectionKey="sort_direction" /> (''); - urlSortDirection = signal(''); - readonly pageTotal = computed(() => { return this.dfgProjectPage()?.total ?? 0; }); - constructor( - private readonly router: Router, - private readonly activatedRoute: ActivatedRoute, - ) { + constructor(private readonly router: Router) { effect(() => { this.dfgProjectData = this.dfgProjectPage().elements || []; }); @@ -165,11 +157,4 @@ export class PersonProjectsComponent implements OnInit { }, ]; } - - handleSortChange(event: Sort): void { - this.router.navigate([], { - queryParams: { sort_by: event.active, sort_direction: event.direction }, - queryParamsHandling: 'merge', - }); - } } diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 41347477..babc2916 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -3,7 +3,7 @@ mat-table [dataSource]="dataSource" matSort - (matSortChange)="onSortChange($event)" + (matSortChange)="_handleSortChange($event)" multiTemplateDataRows> @for (col of columns(); track col.id) { diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.ts b/webapp/src/app/shared/ui/data-table/data-table.component.ts index 0e4c9d16..6fa71428 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.ts +++ b/webapp/src/app/shared/ui/data-table/data-table.component.ts @@ -4,12 +4,14 @@ import { Component, computed, effect, + inject, input, output, signal, TemplateRef, viewChild, } from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { MatSort, MatSortModule, @@ -17,6 +19,7 @@ import { SortDirection, } from '@angular/material/sort'; import { MatTableDataSource, MatTableModule } from '@angular/material/table'; +import { ActivatedRoute, Router } from '@angular/router'; export interface BaseColumn { id: string; @@ -55,15 +58,37 @@ export class DataTableComponent implements AfterViewInit { containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); stickyHeader = input(true); - activeSortKey = input(''); - sortDirection = input(''); - sortChange = output(); + queryParamSortKey = input(null); + queryParamSortDirectionKey = input(null); + + _urlSortValue = computed(() => { + const params = this.queryParams(); + const key = this.queryParamSortKey(); + + return params && key ? params[key] || null : null; + }); + + _urlSortDirectionValue = computed(() => { + const params = this.queryParams(); + const key = this.queryParamSortDirectionKey(); + + return params && key ? params[key] || null : null; + }); + + handleSortChange = output(); displayedColumns = computed(() => this.columns().map((col) => col.id)); dataSource = new MatTableDataSource([]); sort = viewChild.required(MatSort); + private readonly activatedRouter = inject(ActivatedRoute); + private readonly router = inject(Router); + + private readonly queryParams = toSignal( + this.activatedRouter.queryParams.pipe(takeUntilDestroyed()), + ); + constructor() { effect(() => { const currentData = this.data(); @@ -86,15 +111,23 @@ export class DataTableComponent implements AfterViewInit { effect(() => { const matSortInstance = this.sort(); - const activeKey = this.activeSortKey(); - const direction = this.sortDirection(); + const activeKey = this._urlSortValue(); + const direction = this._urlSortDirectionValue(); if ( matSortInstance.active !== activeKey || matSortInstance.direction !== direction ) { - matSortInstance.active = activeKey; - matSortInstance.direction = direction; + if (activeKey == null) { + matSortInstance.active = ''; + } else { + matSortInstance.active = activeKey; + } + if (direction == null) { + matSortInstance.direction = ''; + } else { + matSortInstance.direction = direction as SortDirection; + } this.dataSource.sort = matSortInstance; } @@ -105,8 +138,25 @@ export class DataTableComponent implements AfterViewInit { this.dataSource.sort = this.sort(); } - onSortChange(sort: Sort) { - this.sortChange.emit(sort); + _handleSortChange(sort: Sort): void { + this.handleSortChange.emit(sort); + + const sortKey = this.queryParamSortKey(); + const sortDirectionKey = this.queryParamSortDirectionKey(); + if (sortKey != null) { + const queryParams: any = { + [sortKey]: sort.active || null, + }; + + if (sortDirectionKey != null) { + queryParams[sortDirectionKey] = sort.direction || null; + } + + this.router.navigate([], { + queryParams, + queryParamsHandling: 'merge', + }); + } } toggleRow(row: T): void { diff --git a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts index 85d396f1..3a3f62a7 100644 --- a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts +++ b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.ts @@ -28,11 +28,11 @@ export class QueryParamInputComponent { debounceTime = input(300); handleValueChange = output(); - private readonly activatedRouter = inject(ActivatedRoute); + private readonly activatedRoute = inject(ActivatedRoute); private readonly router = inject(Router); private readonly queryParams = toSignal( - this.activatedRouter.queryParams.pipe(takeUntilDestroyed()), + this.activatedRoute.queryParams.pipe(takeUntilDestroyed()), ); _urlValue = computed(() => { From 278e0f529d05f8cc902d7db5c0521e95460aff86 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 22 Jun 2026 22:31:55 +0200 Subject: [PATCH 44/53] improve topic tooltip spacing --- webapp/src/app/shared/utils/topic-tooltip.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/app/shared/utils/topic-tooltip.ts b/webapp/src/app/shared/utils/topic-tooltip.ts index c805d6e0..d8315852 100644 --- a/webapp/src/app/shared/utils/topic-tooltip.ts +++ b/webapp/src/app/shared/utils/topic-tooltip.ts @@ -40,7 +40,7 @@ export function buildTopicHierarchyTooltip( lines.push(`Description: ${description}`); } - return lines.join('\n'); + return lines.join('\n\n'); } function normalizeTooltipValue(value: string | null | undefined): string { From e76a33d28f7d5b7b607781abdc8587de33eda097 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 22 Jun 2026 23:05:26 +0200 Subject: [PATCH 45/53] refine semantic topic color --- webapp/src/app/shared/utils/topic-colors.ts | 92 ++++++++++++++------- 1 file changed, 61 insertions(+), 31 deletions(-) diff --git a/webapp/src/app/shared/utils/topic-colors.ts b/webapp/src/app/shared/utils/topic-colors.ts index 5f281010..7dfbfc9d 100644 --- a/webapp/src/app/shared/utils/topic-colors.ts +++ b/webapp/src/app/shared/utils/topic-colors.ts @@ -10,32 +10,39 @@ export interface TopicHierarchyColorInput { } const FIELD_HUES: Record = { - 'agricultural and biological sciences': 127, - 'arts and humanities': 28, - 'biochemistry, genetics and molecular biology': 154, - 'business, management and accounting': 44, - 'chemical engineering': 188, - chemistry: 174, - 'computer science': 214, - 'decision sciences': 202, - dentistry: 348, - 'earth and planetary sciences': 112, - 'economics, econometrics and finance': 52, + // Life Sciences: green to teal. + 'agricultural and biological sciences': 116, + 'biochemistry, genetics and molecular biology': 172, + 'immunology and microbiology': 152, + neuroscience: 190, + veterinary: 132, + + // Physical Sciences: cool blues plus distinct earth/environment tones. + 'chemical engineering': 194, + chemistry: 184, + 'computer science': 222, + 'earth and planetary sciences': 66, energy: 88, - engineering: 199, - 'environmental science': 142, - 'health professions': 334, - 'immunology and microbiology': 163, - 'materials science': 258, - mathematics: 233, - medicine: 348, - neuroscience: 282, - nursing: 326, - 'pharmacology, toxicology and pharmaceutics': 5, - 'physics and astronomy': 246, - psychology: 302, - 'social sciences': 20, - veterinary: 135, + engineering: 204, + 'environmental science': 96, + 'materials science': 262, + mathematics: 238, + 'physics and astronomy': 250, + + // Health Sciences: red, pink, and magenta. + dentistry: 352, + 'health professions': 326, + medicine: 342, + nursing: 314, + 'pharmacology, toxicology and pharmaceutics': 6, + + // Social Sciences: orange, amber, and violet. + 'arts and humanities': 282, + 'business, management and accounting': 38, + 'decision sciences': 24, + 'economics, econometrics and finance': 52, + psychology: 296, + 'social sciences': 14, }; const DOMAIN_FALLBACK_HUES: Record = { @@ -45,7 +52,30 @@ const DOMAIN_FALLBACK_HUES: Record = { 'social sciences': 24, }; -const SUBFIELD_HUE_OFFSETS = [-18, -12, -7, -3, 3, 7, 12, 18]; +interface SubfieldColorVariant { + hueOffset: number; + saturation: number; + lightness: number; +} + +const SUBFIELD_COLOR_VARIANTS: readonly SubfieldColorVariant[] = [ + { hueOffset: -6, saturation: 92, lightness: 27 }, + { hueOffset: 6, saturation: 82, lightness: 48 }, + { hueOffset: -2, saturation: 90, lightness: 35 }, + { hueOffset: 7, saturation: 78, lightness: 42 }, + { hueOffset: -8, saturation: 86, lightness: 31 }, + { hueOffset: 3, saturation: 94, lightness: 24 }, + { hueOffset: 8, saturation: 84, lightness: 38 }, + { hueOffset: -4, saturation: 80, lightness: 45 }, + { hueOffset: 0, saturation: 92, lightness: 30 }, + { hueOffset: 8, saturation: 76, lightness: 50 }, + { hueOffset: -7, saturation: 88, lightness: 40 }, + { hueOffset: 4, saturation: 80, lightness: 33 }, + { hueOffset: -8, saturation: 82, lightness: 47 }, + { hueOffset: 2, saturation: 96, lightness: 26 }, + { hueOffset: 8, saturation: 86, lightness: 36 }, + { hueOffset: -2, saturation: 78, lightness: 43 }, +]; export function topicHierarchyColor( topic: TopicHierarchyColorInput | undefined | null, @@ -72,11 +102,11 @@ export function topicHierarchyColor( stableHue(fieldIdentity ?? subfieldIdentity); const variantHash = stableHash(subfieldIdentity); - const offset = - SUBFIELD_HUE_OFFSETS[variantHash % SUBFIELD_HUE_OFFSETS.length]; - const hue = normalizeHue(baseHue + offset); - const saturation = 76 + ((variantHash >> 3) % 16); - const lightness = 34 + ((variantHash >> 7) % 9); + const variant = + SUBFIELD_COLOR_VARIANTS[variantHash % SUBFIELD_COLOR_VARIANTS.length]; + const hue = normalizeHue(baseHue + variant.hueOffset); + const saturation = variant.saturation; + const lightness = variant.lightness; return `hsl(${hue} ${saturation}% ${lightness}%)`; } From e8c01444419cc50f3af8aae1dfbb340452d60aa9 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 22 Jun 2026 23:11:48 +0200 Subject: [PATCH 46/53] increase topic chip contrast --- .../ui/topic-chip/topic-chip.component.scss | 23 +++++++++++-------- .../ui/topic-chip/topic-chip.component.ts | 19 +++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss index 0c263aae..e9d57cd5 100644 --- a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss @@ -29,9 +29,9 @@ border: 1px solid var(--topic-border); border-radius: 8px; background: var(--topic-bg); - color: var(--topic-color); + color: var(--topic-text); font-size: 12px; - font-weight: 500; + font-weight: 700; transition: transform 0.15s ease, box-shadow 0.15s ease; @@ -49,11 +49,12 @@ border: 0; border-radius: 7px; background: color-mix(in srgb, var(--topic-color) 15%, #ffffff); - color: color-mix(in srgb, var(--topic-color) 82%, #263653); + color: var(--topic-text); font-size: 11px; + font-weight: 700; &:hover:not(:disabled) { - color: var(--topic-color); + color: var(--topic-text); text-decoration: none; } } @@ -65,7 +66,7 @@ :host(.topic-chip--active.topic-chip--mini) .topic-chip__button { background: color-mix(in srgb, var(--topic-color) 24%, #ffffff); - color: var(--topic-color); + color: var(--topic-text); } .topic-chip__label { @@ -84,10 +85,13 @@ height: 18px; padding: 0 5px; border-radius: 999px; - background: rgba(255, 255, 255, 0.78); - color: inherit; + background: var(--topic-count-bg); + color: var(--topic-count-text); font-size: 11px; - font-weight: 700; + font-weight: 800; + box-shadow: + inset 0 0 0 1px color-mix(in srgb, var(--topic-color) 24%, transparent), + 0 1px 2px rgba(15, 23, 42, 0.08); } :host(.topic-chip--mini) .topic-chip__count { @@ -96,8 +100,9 @@ padding: 0; border-radius: 0; background: transparent; - color: var(--topic-color); + color: var(--topic-count-text); font-size: 10px; + box-shadow: none; } .topic-chip__count-icon { diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts index 6d12a28a..7558584b 100644 --- a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts @@ -116,6 +116,25 @@ export class TopicChipComponent { return this.colorTokens?.color ?? this.color; } + @HostBinding('style.--topic-text') + get topicText(): string { + return this.colorTokens?.color + ? this.colorTokens.color + : `color-mix(in srgb, ${this.topicColor} 38%, #0f172a)`; + } + + @HostBinding('style.--topic-count-bg') + get topicCountBackground(): string { + return this.colorTokens?.background ?? '#ffffff'; + } + + @HostBinding('style.--topic-count-text') + get topicCountText(): string { + return this.colorTokens?.color + ? this.colorTokens.color + : `color-mix(in srgb, ${this.topicColor} 48%, #0f172a)`; + } + get hasCount(): boolean { return ( this.count !== undefined && this.count !== null && `${this.count}` !== '' From 38896304e8db2fc6ab1881690b65ede6d7e55464 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 22 Jun 2026 23:31:27 +0200 Subject: [PATCH 47/53] refine timeline topic legend layout --- .../research-timeline.component.html | 120 +++++++++++------- .../research-timeline.component.scss | 96 +++++++++++--- .../research-timeline.component.ts | 43 ++----- 3 files changed, 162 insertions(+), 97 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index 1038e101..ac4b5a32 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -12,56 +12,71 @@ class="subfield-legend" [class.expanded]="subfieldLegendExpanded" aria-label="Aktuell sichtbare Subfields"> -
- {{ group.name }} +
+
+ Farben nach Subfield + + info_outline + +
- - - - {{ item.name }} +
- -
+
+
+ {{ group.name }} - + + + + {{ item.name }} + + +
+ + +
+ + + +
(); @@ -193,25 +196,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { return groups; } - let remainingItems = this.collapsedSubfieldLegendLimit; - const visibleGroups: TopicFieldLegendGroup[] = []; - - for (const group of groups) { - if (remainingItems <= 0) { - break; - } - - const items = group.items.slice(0, remainingItems); - - if (items.length === 0) { - continue; - } - - visibleGroups.push({ ...group, items }); - remainingItems -= items.length; - } - - return visibleGroups; + return groups.slice(0, this.collapsedSubfieldLegendGroupLimit); } get hiddenSubfieldLegendItemCount(): number { @@ -219,10 +204,9 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { return 0; } - return Math.max( - this.allSubfieldLegendItemCount - this.collapsedSubfieldLegendLimit, - 0, - ); + return this.allSubfieldLegendGroups + .slice(this.collapsedSubfieldLegendGroupLimit) + .reduce((count, group) => count + group.items.length, 0); } get showSubfieldLegendToggle(): boolean { @@ -461,6 +445,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { this.subfieldLegendExpanded = !this.subfieldLegendExpanded; } + toggleSubfieldLegendVisibility(): void { + this.subfieldLegendVisible = !this.subfieldLegendVisible; + } + trackByLegendGroup(_: number, group: TopicFieldLegendGroup): string { return group.id; } @@ -669,13 +657,6 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { .sort((left, right) => left.name.localeCompare(right.name)); } - private get allSubfieldLegendItemCount(): number { - return this.allSubfieldLegendGroups.reduce( - (count, group) => count + group.items.length, - 0, - ); - } - private get visibleLegendTopics(): TopicTimelineTopic[] { if (this.timelineViewMode === 'compact') { return this.compactPhases.flatMap((phase) => [ From 95a9dcceff9c219f1fa77d44b6f7f8257f145138 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 22 Jun 2026 23:35:05 +0200 Subject: [PATCH 48/53] translate openalex labels --- .../research-timeline/research-timeline.component.html | 6 +++--- webapp/src/app/shared/utils/topic-tooltip.ts | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index ac4b5a32..1416ac78 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -11,13 +11,13 @@ *ngIf="subfieldLegendGroups.length > 0" class="subfield-legend" [class.expanded]="subfieldLegendExpanded" - aria-label="Aktuell sichtbare Subfields"> + aria-label="Aktuell sichtbare Themenbereiche">
- Farben nach Subfield + Farben nach Themenbereich info_outline diff --git a/webapp/src/app/shared/utils/topic-tooltip.ts b/webapp/src/app/shared/utils/topic-tooltip.ts index d8315852..87ff4e61 100644 --- a/webapp/src/app/shared/utils/topic-tooltip.ts +++ b/webapp/src/app/shared/utils/topic-tooltip.ts @@ -22,22 +22,22 @@ export function buildTopicHierarchyTooltip( return ''; } - const lines = [`Topic: ${topicName}`]; + const lines = [`Forschungsthema: ${topicName}`]; if (subfieldName) { - lines.push(`Subfield: ${subfieldName}`); + lines.push(`Themenbereich: ${subfieldName}`); } if (fieldName) { - lines.push(`Field: ${fieldName}`); + lines.push(`Fachgebiet: ${fieldName}`); } if (domainName) { - lines.push(`Domain: ${domainName}`); + lines.push(`Wissenschaftsbereich: ${domainName}`); } if (description) { - lines.push(`Description: ${description}`); + lines.push(`Beschreibung: ${description}`); } return lines.join('\n\n'); From 6ea5ac1b172c0def94b5f0e8d3838c242ec7fda9 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 22 Jun 2026 23:54:23 +0200 Subject: [PATCH 49/53] add expandable topic color legend --- .../person-interesting.component.html | 64 +++++++++---- .../person-interesting.component.scss | 91 ++++++++++++++++--- .../person-interesting.component.ts | 26 +++++- 3 files changed, 145 insertions(+), 36 deletions(-) diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index d88ebffc..650677af 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -6,28 +6,52 @@ article Anzahl Publikationen zum Thema - @if (legendGroups().length > 0) { -
- @for (group of legendGroups(); track group.id) { - - {{ group.name }} - - @for (item of group.items; track item.id) { - - - {{ item.name }} - - } - - - } -
- } }
+ @if (visibleLegendGroups().length > 0) { +
+ + info_outline + + +
+ @for (group of visibleLegendGroups(); track group.id) { + + {{ group.name }} + + @for (item of group.items; track item.id) { + + + {{ item.name }} + + } + + + } + + @if (hasHiddenLegendGroups()) { + + } +
+
+ }
@if (tags().length > 0) { @for (tag of tags(); track tag.label) { diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.scss b/webapp/src/app/modules/person-interesting/person-interesting.component.scss index ebd1babb..ec4f6a04 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.scss +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.scss @@ -15,7 +15,7 @@ align-items: baseline; gap: 10px; flex-wrap: wrap; - margin: 0 0 18px; + margin: 0 0 12px; } .interest-card h3 { @@ -46,50 +46,87 @@ } .interest-legend { + display: flex; + align-items: flex-start; + gap: 9px; + width: fit-content; + max-width: 100%; + margin: 0 0 16px; + padding: 8px 10px; + border: 1px solid #dbe5f6; + border-radius: 8px; + background: #ffffff; + box-sizing: border-box; +} + +.interest-legend-content, +.interest-legend-group, +.interest-legend-items, +.interest-legend-item { display: inline-flex; - flex-wrap: wrap; align-items: center; - gap: 6px; +} + +.interest-legend-info { + flex: 0 0 auto; + width: 14px; + height: 14px; + color: #7d8aa8; + font-size: 14px; + line-height: 14px; +} + +.interest-legend-content { + gap: 7px; + flex: 0 1 auto; min-width: 0; + max-width: 100%; + flex-wrap: wrap; } .interest-legend-group { - display: inline-flex; - align-items: center; gap: 6px; + flex: 0 1 auto; + flex-wrap: wrap; + min-width: 0; max-width: 100%; - min-height: 22px; + min-height: 24px; padding: 3px 7px; border: 1px solid #dbe5f6; border-radius: 999px; - background: rgba(255, 255, 255, 0.68); + background: #fbfdff; } .interest-legend-field { - flex: 0 0 auto; - color: #1b2a4a; + flex: 0 1 auto; + min-width: 0; + color: #07163d; font-size: 10px; font-weight: 800; line-height: 1.2; } .interest-legend-items { - display: inline-flex; - flex-wrap: wrap; - align-items: center; + flex: 0 1 auto; gap: 4px 7px; min-width: 0; + flex-wrap: wrap; } .interest-legend-item { - display: inline-flex; - align-items: center; gap: 4px; + flex: 0 0 auto; min-width: 0; color: #53617e; font-size: 10px; font-weight: 600; line-height: 1.2; + white-space: nowrap; + + span:last-child { + overflow: visible; + text-overflow: clip; + } } .interest-legend-dot { @@ -101,6 +138,32 @@ box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2); } +.interest-legend-more { + display: inline-flex; + align-items: center; + flex: 0 0 auto; + min-height: 24px; + padding: 0 2px; + border: 0; + background: transparent; + color: var(--accent, #0057ff); + cursor: pointer; + font: inherit; + font-size: 11px; + font-weight: 700; + white-space: nowrap; + + &:hover { + text-decoration: underline; + } + + &:focus-visible { + outline: 2px solid var(--accent, #0057ff); + outline-offset: 2px; + border-radius: 4px; + } +} + .interest-tags .interest-empty { padding: 9px 16px; border: 1px solid #e2e8f0; diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index 0e0fd749..1a695ead 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -1,5 +1,6 @@ -import { Component, input, computed, output } from '@angular/core'; +import { Component, input, computed, output, signal } from '@angular/core'; import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { CommonModule } from '@angular/common'; import { TopicCount } from '../../api'; @@ -33,15 +34,17 @@ interface InterestLegendItem { } const MAX_TAGS = 5; +const MAX_LEGEND_GROUPS = 3; @Component({ selector: 'app-person-interesting', - imports: [CommonModule, MatIconModule, TopicChipComponent], + imports: [CommonModule, MatIconModule, MatTooltipModule, TopicChipComponent], templateUrl: './person-interesting.component.html', styleUrl: './person-interesting.component.scss', }) export class PersonInterestingComponent { readonly topics = input(null); + readonly legendExpanded = signal(false); readonly tagClick = output<{ id: string; name: string }>(); @@ -114,8 +117,27 @@ export class PersonInterestingComponent { .sort((left, right) => left.name.localeCompare(right.name)); }); + readonly visibleLegendGroups = computed(() => { + const groups = this.legendGroups(); + return this.legendExpanded() ? groups : groups.slice(0, MAX_LEGEND_GROUPS); + }); + + readonly hasHiddenLegendGroups = computed( + () => this.legendGroups().length > MAX_LEGEND_GROUPS, + ); + + readonly hiddenLegendItemCount = computed(() => + this.legendGroups() + .slice(MAX_LEGEND_GROUPS) + .reduce((count, group) => count + group.items.length, 0), + ); + onTagClick(tag: InterestTag): void { if (!tag.id) return; this.tagClick.emit({ id: tag.id, name: tag.label }); } + + toggleLegend(): void { + this.legendExpanded.update((expanded) => !expanded); + } } From ddb3439324c61b9d625010fbd8e17136a2227a8d Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 23 Jun 2026 00:03:38 +0200 Subject: [PATCH 50/53] enlarge topic color markers --- .../research-timeline.component.scss | 14 +++++++------- .../shared/ui/topic-chip/topic-chip.component.ts | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index e9c2aae5..f03956dc 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -411,8 +411,8 @@ } .dot { - width: 14px; - height: 14px; + width: 18px; + height: 18px; border: 3px solid #ffffff; border-radius: 50%; background: var(--timeline-color); @@ -527,9 +527,9 @@ app-topic-chip.timeline-topic-chip { } .phase-marker { - width: 12px; - height: 12px; - margin-top: 5px; + width: 16px; + height: 16px; + margin-top: 3px; border: 3px solid #ffffff; border-radius: 50%; background: var(--timeline-color); @@ -660,8 +660,8 @@ app-topic-chip.timeline-topic-chip { } .note-dot { - width: 10px; - height: 10px; + width: 12px; + height: 12px; border: 3px solid #dce5f5; border-radius: 50%; background: #52627f; diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts index 7558584b..f8d7f81c 100644 --- a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.ts @@ -99,7 +99,7 @@ export class TopicChipComponent { get topicBorder(): string { return ( this.colorTokens?.border ?? - `color-mix(in srgb, ${this.topicColor} 52%, #ffffff)` + `color-mix(in srgb, ${this.topicColor} 72%, #ffffff)` ); } From 03e21fcb3254e61719a1f95b999820e45eedccb3 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 23 Jun 2026 00:21:52 +0200 Subject: [PATCH 51/53] expanded state in URL --- .../person-interesting.component.spec.ts | 2 + .../person-interesting.component.ts | 70 ++++++++++++++++++- .../research-timeline.component.ts | 10 +-- .../person-overview.component.html | 4 ++ .../person-overview.component.ts | 65 ++++++++++++++++- 5 files changed, 143 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.spec.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.spec.ts index 0a056035..c20e79de 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.spec.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.spec.ts @@ -1,4 +1,5 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; import { PersonInterestingComponent } from './person-interesting.component'; @@ -9,6 +10,7 @@ describe('PersonInterestingComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [PersonInterestingComponent], + providers: [provideRouter([])], }).compileComponents(); fixture = TestBed.createComponent(PersonInterestingComponent); diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index 1a695ead..122cda7e 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -1,7 +1,18 @@ -import { Component, input, computed, output, signal } from '@angular/core'; +import { + Component, + DestroyRef, + OnInit, + computed, + inject, + input, + output, + signal, +} from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CommonModule } from '@angular/common'; +import { ActivatedRoute, Router } from '@angular/router'; import { TopicCount } from '../../api'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; @@ -42,7 +53,14 @@ const MAX_LEGEND_GROUPS = 3; templateUrl: './person-interesting.component.html', styleUrl: './person-interesting.component.scss', }) -export class PersonInterestingComponent { +export class PersonInterestingComponent implements OnInit { + private static readonly legendExpandedQueryParam = + 'interesting_legend_expanded'; + + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly destroyRef = inject(DestroyRef); + readonly topics = input(null); readonly legendExpanded = signal(false); @@ -132,12 +150,58 @@ export class PersonInterestingComponent { .reduce((count, group) => count + group.items.length, 0), ); + ngOnInit(): void { + this.route.queryParamMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((queryParams) => { + this.legendExpanded.set( + this.parseBooleanQueryParam( + queryParams.get( + PersonInterestingComponent.legendExpandedQueryParam, + ), + false, + ), + ); + }); + } + onTagClick(tag: InterestTag): void { if (!tag.id) return; this.tagClick.emit({ id: tag.id, name: tag.label }); } toggleLegend(): void { - this.legendExpanded.update((expanded) => !expanded); + const expanded = !this.legendExpanded(); + this.legendExpanded.set(expanded); + + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [PersonInterestingComponent.legendExpandedQueryParam]: expanded + ? 'true' + : null, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + private parseBooleanQueryParam( + value: string | null, + fallback: boolean, + ): boolean { + if (value === null) { + return fallback; + } + + if (value === 'true' || value === '1') { + return true; + } + + if (value === 'false' || value === '0') { + return false; + } + + return fallback; } } diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index 268dc074..60fb616f 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -112,12 +112,16 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { @Input() viewMode: TimelineViewMode = 'years'; @Input() startYear: number | undefined; @Input() endYear: number | undefined; + @Input() subfieldLegendVisible = true; + @Input() subfieldLegendExpanded = false; @Output() viewModeChange = new EventEmitter(); @Output() yearRangeChange = new EventEmitter(); @Output() topicSelect = new EventEmitter(); @Output() yearSelect = new EventEmitter(); @Output() loadEarlierYears = new EventEmitter(); + @Output() subfieldLegendVisibleChange = new EventEmitter(); + @Output() subfieldLegendExpandedChange = new EventEmitter(); timelineViewMode: TimelineViewMode = 'years'; @@ -125,8 +129,6 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { maxYear = 0; selectedStartYear = 0; selectedEndYear = 0; - subfieldLegendVisible = true; - subfieldLegendExpanded = false; private readonly columnWidth = 240; private readonly displayedTopicLimit = 3; @@ -146,12 +148,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { this.timelineViewMode = this.isTimelineViewMode(this.viewMode) ? this.viewMode : 'years'; - this.subfieldLegendExpanded = false; } if (changes['elements']) { this.initializeYearBounds(); - this.subfieldLegendExpanded = false; } if (changes['elements'] || changes['startYear'] || changes['endYear']) { @@ -443,10 +443,12 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { toggleSubfieldLegend(): void { this.subfieldLegendExpanded = !this.subfieldLegendExpanded; + this.subfieldLegendExpandedChange.emit(this.subfieldLegendExpanded); } toggleSubfieldLegendVisibility(): void { this.subfieldLegendVisible = !this.subfieldLegendVisible; + this.subfieldLegendVisibleChange.emit(this.subfieldLegendVisible); } trackByLegendGroup(_: number, group: TopicFieldLegendGroup): string { diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index 31ac9ae8..ae891993 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -9,8 +9,12 @@ [viewMode]="timelineViewMode" [startYear]="timelineStartYear" [endYear]="timelineEndYear" + [subfieldLegendVisible]="timelineLegendVisible" + [subfieldLegendExpanded]="timelineLegendExpanded" (viewModeChange)="onTimelineViewModeChange($event)" (yearRangeChange)="onTimelineYearRangeChange($event)" + (subfieldLegendVisibleChange)="onTimelineLegendVisibleChange($event)" + (subfieldLegendExpandedChange)="onTimelineLegendExpandedChange($event)" (topicSelect)="onTimelineTopicSelect($event)" (yearSelect)="onTimelineYearSelect($event)" (loadEarlierYears)="onTimelineLoadEarlierYears()"> diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index 97fb8c8b..fa76ba7e 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -28,6 +28,10 @@ export class PersonOverviewComponent implements OnInit { private static readonly timelineViewQueryParam = 'timeline_view'; private static readonly timelineStartYearQueryParam = 'timeline_start_year'; private static readonly timelineEndYearQueryParam = 'timeline_end_year'; + private static readonly timelineLegendVisibleQueryParam = + 'timeline_legend_visible'; + private static readonly timelineLegendExpandedQueryParam = + 'timeline_legend_expanded'; private static readonly timelineTopicCountLimit = 4; private static readonly initialTimelineTargetPublications = 250; @@ -49,6 +53,8 @@ export class PersonOverviewComponent implements OnInit { timelineViewMode: TimelineViewMode = 'years'; timelineStartYear: number | undefined; timelineEndYear: number | undefined; + timelineLegendVisible = true; + timelineLegendExpanded = false; wordCloudOptions: EChartsOption | null = null; loadingWordCloud = false; @@ -84,6 +90,18 @@ export class PersonOverviewComponent implements OnInit { this.timelineEndYear = this.parseOptionalYear( queryParams.get(PersonOverviewComponent.timelineEndYearQueryParam), ); + this.timelineLegendVisible = this.parseBooleanQueryParam( + queryParams.get( + PersonOverviewComponent.timelineLegendVisibleQueryParam, + ), + true, + ); + this.timelineLegendExpanded = this.parseBooleanQueryParam( + queryParams.get( + PersonOverviewComponent.timelineLegendExpandedQueryParam, + ), + false, + ); }); } @@ -112,6 +130,32 @@ export class PersonOverviewComponent implements OnInit { ); } + onTimelineLegendVisibleChange(visible: boolean): void { + this.timelineLegendVisible = visible; + + this.updateTimelineQueryParams( + { + [PersonOverviewComponent.timelineLegendVisibleQueryParam]: visible + ? null + : 'false', + }, + true, + ); + } + + onTimelineLegendExpandedChange(expanded: boolean): void { + this.timelineLegendExpanded = expanded; + + this.updateTimelineQueryParams( + { + [PersonOverviewComponent.timelineLegendExpandedQueryParam]: expanded + ? 'true' + : null, + }, + true, + ); + } + onTimelineTopicSelect(selection: TimelineTopicSelection): void { if (!selection.topic.id) { return; @@ -499,8 +543,27 @@ export class PersonOverviewComponent implements OnInit { return year; } + private parseBooleanQueryParam( + value: string | null, + fallback: boolean, + ): boolean { + if (value === null) { + return fallback; + } + + if (value === 'true' || value === '1') { + return true; + } + + if (value === 'false' || value === '0') { + return false; + } + + return fallback; + } + private updateTimelineQueryParams( - queryParams: Record, + queryParams: Record, replaceUrl: boolean, ): void { void this.router.navigate([], { From 9905750d75b9bd3f1fd96edb5d992a1d669151b8 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 23 Jun 2026 00:47:39 +0200 Subject: [PATCH 52/53] show subfields, fields and domains descriptions in tooltips --- .../main/inse/models/openalex/topic_count.py | 12 ++ service/src/main/inse/works/logic.py | 66 ++++++++++- webapp/src/app/api/model/topicCount.ts | 3 + .../person-interesting.component.html | 16 ++- .../person-interesting.component.scss | 2 + .../person-interesting.component.ts | 72 ++++++++++++ .../research-timeline.component.html | 15 ++- .../research-timeline.component.scss | 2 + .../research-timeline.component.ts | 105 ++++++++++++++++++ .../person-overview.component.ts | 3 + 10 files changed, 291 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/models/openalex/topic_count.py b/service/src/main/inse/models/openalex/topic_count.py index 4a5d0c3d..8d6be897 100644 --- a/service/src/main/inse/models/openalex/topic_count.py +++ b/service/src/main/inse/models/openalex/topic_count.py @@ -16,6 +16,10 @@ class TopicCount(BaseModel): default=None, description="The topic subfield display name.", ) + subfield_description: Optional[str] = Field( + default=None, + description="The topic subfield description.", + ) field_id: Optional[str] = Field( default=None, description="The topic field id.", @@ -24,6 +28,10 @@ class TopicCount(BaseModel): default=None, description="The topic field display name.", ) + field_description: Optional[str] = Field( + default=None, + description="The topic field description.", + ) domain_id: Optional[str] = Field( default=None, description="The topic domain id.", @@ -32,3 +40,7 @@ class TopicCount(BaseModel): default=None, description="The topic domain display name.", ) + domain_description: Optional[str] = Field( + default=None, + description="The topic domain description.", + ) diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 070251d4..9d5918cf 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -38,6 +38,17 @@ TOPIC_DETAIL_SOURCE_FIELDS = [ "domain", ] +TOPIC_HIERARCHY_DESCRIPTION_INDICES = { + "subfield": "openalex-subfields", + "field": "openalex-fields", + "domain": "openalex-domains", +} + +TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS = [ + "id", + "description", +] + async def get_author_works( author_id: str, @@ -240,6 +251,8 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: "domain": _extract_topic_hierarchy_item(source, "domain"), } + _enrich_topic_hierarchy_descriptions(details) + return details @@ -247,14 +260,62 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non hierarchy_item = source.get(key) if not isinstance(hierarchy_item, dict): - return {"id": None, "display_name": None} + return {"id": None, "display_name": None, "description": None} return { "id": hierarchy_item.get("id"), "display_name": hierarchy_item.get("display_name"), + "description": hierarchy_item.get("description"), } +def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: + for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items(): + hierarchy_ids = { + item.get(hierarchy_key, {}).get("id") + for item in details.values() + if item.get(hierarchy_key, {}).get("id") + } + + descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids)) + + for item in details.values(): + hierarchy_item = item.get(hierarchy_key) or {} + hierarchy_id = hierarchy_item.get("id") + + if hierarchy_id and hierarchy_id in descriptions: + hierarchy_item["description"] = descriptions[hierarchy_id] + + +def _get_topic_hierarchy_descriptions( + index: str, + hierarchy_ids: list[str], +) -> dict[str, str | None]: + if not hierarchy_ids: + return {} + + try: + response = elasticsearch.search( + index=index, + query={"terms": {"id": hierarchy_ids}}, + source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS, + size=len(hierarchy_ids), + ) + except httpx.HTTPError: + logger.exception("Could not load topic hierarchy details from %s.", index) + return {} + + descriptions = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + hierarchy_id = source.get("id") + + if hierarchy_id: + descriptions[hierarchy_id] = source.get("description") + + return descriptions + + def _topic_hierarchy_fields(topic_details: dict) -> dict[str, str | None]: subfield = topic_details.get("subfield") or {} field = topic_details.get("field") or {} @@ -263,10 +324,13 @@ def _topic_hierarchy_fields(topic_details: dict) -> dict[str, str | None]: return { "subfield_id": subfield.get("id"), "subfield_name": subfield.get("display_name"), + "subfield_description": subfield.get("description"), "field_id": field.get("id"), "field_name": field.get("display_name"), + "field_description": field.get("description"), "domain_id": domain.get("id"), "domain_name": domain.get("display_name"), + "domain_description": domain.get("description"), } diff --git a/webapp/src/app/api/model/topicCount.ts b/webapp/src/app/api/model/topicCount.ts index 720ba500..1d2abe90 100644 --- a/webapp/src/app/api/model/topicCount.ts +++ b/webapp/src/app/api/model/topicCount.ts @@ -21,8 +21,11 @@ export interface TopicCount { description?: string | null; subfield_id?: string | null; subfield_name?: string | null; + subfield_description?: string | null; field_id?: string | null; field_name?: string | null; + field_description?: string | null; domain_id?: string | null; domain_name?: string | null; + domain_description?: string | null; } diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index 650677af..7a9e4e45 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -21,10 +21,22 @@
@for (group of visibleLegendGroups(); track group.id) { - {{ group.name }} + {{ group.name }} @for (item of group.items; track item.id) { - + , + ): string { + const lines: string[] = []; + + for (const entry of entries) { + if (!entry.value && !entry.description) { + continue; + } + + if (lines.length > 0) { + lines.push(''); + } + + if (entry.value) { + lines.push(`${entry.label}: ${entry.value}`); + } + + if (entry.description) { + lines.push(''); + lines.push(`Beschreibung: ${entry.description}`); + } + } + + return lines.join('\n'); + } } diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index 1416ac78..dd8801dc 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -49,12 +49,23 @@ trackBy: trackByLegendGroup " class="subfield-legend-group"> - {{ group.name }} + {{ group.name }} + class="subfield-legend-item" + [matTooltip]="item.tooltip" + [matTooltipDisabled]="!item.tooltip" + matTooltipClass="topic-chip-tooltip" + matTooltipPosition="above"> 0; } + buildLegendTooltip( + entries: Array<{ label: string; value: string; description: string }>, + ): string { + const lines: string[] = []; + + for (const entry of entries) { + if (!entry.value && !entry.description) { + continue; + } + + if (lines.length > 0) { + lines.push(''); + } + + if (entry.value) { + lines.push(`${entry.label}: ${entry.value}`); + } + + if (entry.description) { + lines.push(''); + lines.push(`Beschreibung: ${entry.description}`); + } + } + + return lines.join('\n'); + } + getYearTopicCountTooltip( topic: TopicTimelineTopic, item: TopicTimelineElement, @@ -632,6 +668,21 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { groups.set(fieldKey, { id: fieldKey, name: fieldName, + description: topic.field_description?.trim() ?? '', + domainName: topic.domain_name?.trim() ?? '', + domainDescription: topic.domain_description?.trim() ?? '', + tooltip: this.buildLegendTooltip([ + { + label: 'Fachgebiet', + value: fieldName, + description: topic.field_description?.trim() ?? '', + }, + { + label: 'Wissenschaftsbereich', + value: topic.domain_name?.trim() ?? '', + description: topic.domain_description?.trim() ?? '', + }, + ]), items: [], }); } @@ -645,7 +696,25 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { group.items.push({ id: subfieldKey, name: subfieldName, + description: topic.subfield_description?.trim() ?? '', color: this.getTopicColor(topic), + tooltip: this.buildLegendTooltip([ + { + label: 'Themenbereich', + value: subfieldName, + description: topic.subfield_description?.trim() ?? '', + }, + { + label: 'Fachgebiet', + value: fieldName, + description: topic.field_description?.trim() ?? '', + }, + { + label: 'Wissenschaftsbereich', + value: topic.domain_name?.trim() ?? '', + description: topic.domain_description?.trim() ?? '', + }, + ]), }); } @@ -812,10 +881,13 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { let description = primaryTopic.description; let subfieldId = primaryTopic.subfield_id; let subfieldName = primaryTopic.subfield_name; + let subfieldDescription = primaryTopic.subfield_description; let fieldId = primaryTopic.field_id; let fieldName = primaryTopic.field_name; + let fieldDescription = primaryTopic.field_description; let domainId = primaryTopic.domain_id; let domainName = primaryTopic.domain_name; + let domainDescription = primaryTopic.domain_description; for (const year of years) { for (const topic of year.primary_topics ?? []) { @@ -841,6 +913,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { subfieldName = topic.subfield_name; } + if (!subfieldDescription && topic.subfield_description) { + subfieldDescription = topic.subfield_description; + } + if (!fieldId && topic.field_id) { fieldId = topic.field_id; } @@ -849,6 +925,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { fieldName = topic.field_name; } + if (!fieldDescription && topic.field_description) { + fieldDescription = topic.field_description; + } + if (!domainId && topic.domain_id) { domainId = topic.domain_id; } @@ -856,6 +936,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { if (!domainName && topic.domain_name) { domainName = topic.domain_name; } + + if (!domainDescription && topic.domain_description) { + domainDescription = topic.domain_description; + } } } @@ -866,10 +950,13 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { description, subfield_id: subfieldId, subfield_name: subfieldName, + subfield_description: subfieldDescription, field_id: fieldId, field_name: fieldName, + field_description: fieldDescription, domain_id: domainId, domain_name: domainName, + domain_description: domainDescription, }; } @@ -883,10 +970,13 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { const descriptions = new Map(); const subfieldIds = new Map(); const subfieldNames = new Map(); + const subfieldDescriptions = new Map(); const fieldIds = new Map(); const fieldNames = new Map(); + const fieldDescriptions = new Map(); const domainIds = new Map(); const domainNames = new Map(); + const domainDescriptions = new Map(); for (const year of years) { for (const topic of year.topics ?? []) { @@ -914,6 +1004,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { subfieldNames.set(normalizedName, topic.subfield_name); } + if (topic.subfield_description) { + subfieldDescriptions.set(normalizedName, topic.subfield_description); + } + if (topic.field_id) { fieldIds.set(normalizedName, topic.field_id); } @@ -922,6 +1016,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { fieldNames.set(normalizedName, topic.field_name); } + if (topic.field_description) { + fieldDescriptions.set(normalizedName, topic.field_description); + } + if (topic.domain_id) { domainIds.set(normalizedName, topic.domain_id); } @@ -930,6 +1028,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { domainNames.set(normalizedName, topic.domain_name); } + if (topic.domain_description) { + domainDescriptions.set(normalizedName, topic.domain_description); + } + counts.set( normalizedName, (counts.get(normalizedName) ?? 0) + topic.count, @@ -945,10 +1047,13 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { description: descriptions.get(normalizedName), subfield_id: subfieldIds.get(normalizedName), subfield_name: subfieldNames.get(normalizedName), + subfield_description: subfieldDescriptions.get(normalizedName), field_id: fieldIds.get(normalizedName), field_name: fieldNames.get(normalizedName), + field_description: fieldDescriptions.get(normalizedName), domain_id: domainIds.get(normalizedName), domain_name: domainNames.get(normalizedName), + domain_description: domainDescriptions.get(normalizedName), })) .sort((left, right) => { if (right.count !== left.count) { diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index fa76ba7e..3d30ee16 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -482,10 +482,13 @@ export class PersonOverviewComponent implements OnInit { description: topic.description ?? undefined, subfield_id: topic.subfield_id ?? undefined, subfield_name: topic.subfield_name ?? undefined, + subfield_description: topic.subfield_description ?? undefined, field_id: topic.field_id ?? undefined, field_name: topic.field_name ?? undefined, + field_description: topic.field_description ?? undefined, domain_id: topic.domain_id ?? undefined, domain_name: topic.domain_name ?? undefined, + domain_description: topic.domain_description ?? undefined, })); } From 7a137deb71eb5a6a9c600d16148e7fb272c3de5e Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 23 Jun 2026 00:58:35 +0200 Subject: [PATCH 53/53] network and sidebar fix --- webapp/src/app/app.routes.ts | 47 +++++++++++++++++-- .../person-company-connections.component.scss | 4 +- .../person-network.component.ts | 42 +++++++++++------ .../collaboration-network.resolver.ts | 13 +++-- .../ui/app-layout/app-layout.component.scss | 2 +- .../ui/app-menu/app-menu.component.html | 2 + .../ui/app-menu/app-menu.component.scss | 11 ++++- .../shared/ui/app-menu/app-menu.component.ts | 13 ++++- 8 files changed, 106 insertions(+), 28 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 5bf5ab58..a7d8b279 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -190,7 +190,33 @@ export const routes: Routes = [ collaborationNetwork: collaborationNetworkResolver, }, runGuardsAndResolvers: (from, to) => { - // No need to re-run for different table view or search term + const network = from.data['collaborationNetwork'] as + | { + filter_information?: { + min_possible_year?: number; + max_possible_year?: number; + }; + } + | undefined; + + const filterInformation = network?.filter_information; + + const defaultQueryParams: Record = { + filter_by: 'works', + start_year: filterInformation?.min_possible_year + ? String(filterInformation.min_possible_year) + : '', + end_year: filterInformation?.max_possible_year + ? String(filterInformation.max_possible_year) + : '', + min_contributors: '2', + max_contributors: '10', + min_collaborations: '1', + max_collaborations: '100', + institutions: '', + topics: '', + }; + const keys = [ 'filter_by', 'start_year', @@ -203,9 +229,22 @@ export const routes: Routes = [ 'topics', ]; - return keys.some( - (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), - ); + return keys.some((key) => { + const fromRawValue = from.queryParamMap.get(key); + const toRawValue = to.queryParamMap.get(key); + + const fromValue = + fromRawValue === null || fromRawValue === '' + ? defaultQueryParams[key] + : fromRawValue; + + const toValue = + toRawValue === null || toRawValue === '' + ? defaultQueryParams[key] + : toRawValue; + + return fromValue !== toValue; + }); }, }, diff --git a/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss b/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss index 91824dd7..5fe97475 100644 --- a/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss +++ b/webapp/src/app/modules/person-company-connections/person-company-connections.component.scss @@ -131,8 +131,8 @@ $text-muted: #64718f; right: 12px; z-index: 2; - width: 50px; - height: 50px; + width: 51px; + height: 51px; padding: 0; background: transparent; diff --git a/webapp/src/app/modules/person-network/person-network.component.ts b/webapp/src/app/modules/person-network/person-network.component.ts index 1c96f6eb..ebceeec9 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -299,7 +299,7 @@ export class PersonNetworkComponent implements OnInit { console.log('Form value when opening dialog:', this.filterForm.value); const dialogRef = this.dialog.open(PersonNetworkFilterDialogComponent, { data: { - collaborationNetwork: this.collaborationNetwork, + collaborationNetwork: this.collaborationNetwork(), filterBy: this.filterForm.get('filterBy')?.value || 'works', startYear: this.filterForm.get('startYear')?.value, @@ -407,22 +407,34 @@ export class PersonNetworkComponent implements OnInit { ]; this.filterForm.valueChanges.pipe(debounceTime(300)).subscribe((value) => { - console.log('Form value changed:', value); + const queryParams = { + table: value.displayedTable ?? 'collaborators', + search_term: value.searchTerm ?? '', + filter_by: value.filterBy ?? 'works', + start_year: value.startYear ?? '', + end_year: value.endYear ?? '', + min_contributors: value.minContributors ?? 2, + max_contributors: value.maxContributors ?? 10, + min_collaborations: value.minCollaborations ?? 1, + max_collaborations: value.maxCollaborations ?? 100, + institutions: value.institutions?.join(',') ?? '', + topics: value.topics?.join(',') ?? '', + }; + + const currentQueryParams = this.activatedRoute.snapshot.queryParams; + + const hasChanged = Object.entries(queryParams).some(([key, value]) => { + return String(currentQueryParams[key] ?? '') !== String(value ?? ''); + }); + + if (!hasChanged) { + return; + } + this.router.navigate([], { relativeTo: this.activatedRoute, - queryParams: { - table: value.displayedTable, - search_term: value.searchTerm, - filter_by: value.filterBy, - start_year: value.startYear, - end_year: value.endYear, - min_contributors: value.minContributors, - max_contributors: value.maxContributors, - min_collaborations: value.minCollaborations, - max_collaborations: value.maxCollaborations, - institutions: value.institutions?.join(','), - topics: value.topics?.join(','), - }, + queryParams, + replaceUrl: true, }); }); } diff --git a/webapp/src/app/resolvers/collaboration-network.resolver.ts b/webapp/src/app/resolvers/collaboration-network.resolver.ts index f15ac150..4a8c1f9f 100644 --- a/webapp/src/app/resolvers/collaboration-network.resolver.ts +++ b/webapp/src/app/resolvers/collaboration-network.resolver.ts @@ -8,6 +8,11 @@ import { WorksFilterProperties, } from '../api'; +const DEFAULT_MIN_CONTRIBUTORS = 2; +const DEFAULT_MAX_CONTRIBUTORS = 10; +const DEFAULT_MIN_COLLABORATIONS = 1; +const DEFAULT_MAX_COLLABORATIONS = 100; + export const collaborationNetworkResolver: ResolveFn = ( route, state, @@ -38,10 +43,10 @@ export const collaborationNetworkResolver: ResolveFn = ( end_year: endYear ? Number.parseInt(endYear, 10) : undefined, min_contributors: minContributors ? Number.parseInt(minContributors, 10) - : undefined, + : DEFAULT_MIN_CONTRIBUTORS, max_contributors: maxContributors ? Number.parseInt(maxContributors, 10) - : undefined, + : DEFAULT_MAX_CONTRIBUTORS, allowed_topics: topics ? topics.split(',') : undefined, }; } @@ -49,10 +54,10 @@ export const collaborationNetworkResolver: ResolveFn = ( authorsFilterProperties = { min_collaborations: minCollaborations ? Number.parseInt(minCollaborations, 10) - : undefined, + : DEFAULT_MIN_COLLABORATIONS, max_collaborations: maxCollaborations ? Number.parseInt(maxCollaborations, 10) - : undefined, + : DEFAULT_MAX_COLLABORATIONS, allowed_institutions: institutions ? institutions.split(',') : undefined, }; } diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index adba06a1..1f16e6cf 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -85,7 +85,7 @@ mat-toolbar.main { } .drawer--collapsed { - width: 76px; + width: 64px; } .content { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index f20b8878..ab143d54 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -49,6 +49,7 @@ [routerLink]="item.disabled ? null : item.route" [queryParams]="item.queryParams || null" routerLinkActive="active" + [routerLinkActiveOptions]="navLinkActiveOptions" [class.disabled]="item.disabled" [matTooltip]="item.label" matTooltipPosition="right" @@ -61,6 +62,7 @@ [routerLink]="item.disabled ? null : item.route" [queryParams]="item.queryParams || null" routerLinkActive="active" + [routerLinkActiveOptions]="navLinkActiveOptions" [class.disabled]="item.disabled"> {{ item.icon }} {{ item.label }} diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.scss b/webapp/src/app/shared/ui/app-menu/app-menu.component.scss index 6e8d66bb..70c13978 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.scss +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.scss @@ -11,7 +11,7 @@ .sidebar--collapsed { align-items: center; - padding: 18px 10px 20px; + padding: 18px 8px 20px; } .brand-row { @@ -268,3 +268,12 @@ .loading-indicator { margin-bottom: 16px; } + +.sidebar--collapsed .nav-list, +.sidebar--collapsed .sidebar-actions { + justify-items: center; +} + +.sidebar--collapsed .account-icon { + margin-inline: auto; +} diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index a1ad0c20..3386701a 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -1,6 +1,11 @@ import { Component, computed, inject, input, output } from '@angular/core'; import { CommonModule } from '@angular/common'; -import { Router, RouterLink, RouterLinkActive } from '@angular/router'; +import { + IsActiveMatchOptions, + Router, + RouterLink, + RouterLinkActive, +} from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatListModule } from '@angular/material/list'; import { MatButtonModule } from '@angular/material/button'; @@ -30,6 +35,12 @@ export class AppMenuComponent { collapsed = input(false); canCollapse = input(false); toggleCollapsed = output(); + readonly navLinkActiveOptions: IsActiveMatchOptions = { + paths: 'subset', + queryParams: 'ignored', + matrixParams: 'ignored', + fragment: 'ignored', + }; navItems = [ { label: 'Dashboard',