From 968b7a07234b1f7d48d758da0a1c338b44d71b96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 4 Jun 2026 20:22:44 +0200 Subject: [PATCH 01/33] Added loading indicator while resolving --- .../person-network-graph.component.ts | 3 +- ...person-network-publications.component.html | 27 +-- .../person-network.component.html | 4 +- .../person-network.component.ts | 1 - .../app/modules/person/person.component.html | 162 ++++++++++-------- .../app/modules/person/person.component.scss | 49 +++++- .../app/modules/person/person.component.ts | 115 +++++++++---- .../collaboration-network.resolver.ts | 2 - webapp/src/styles.scss | 18 ++ 9 files changed, 254 insertions(+), 127 deletions(-) diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index c31f74d2..f3e16580 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -112,7 +112,8 @@ export class PersonNetworkGraphComponent { roam: true, force: { repulsion: 10000, - edgeLength: 125, + friction: 0.9, + // edgeLength: 25, gravity: 0.2, }, links: item.links.map((e) => { diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html index a8c4c24b..c9227bb8 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html @@ -41,17 +41,18 @@ -
-
    - @for (collaborator of element.collaborators; track $index) { -
  • - {{ collaborator.name }} - ({{ - collaborator.id - }}) -
  • - } -
-
+ + + + +
diff --git a/webapp/src/app/modules/person-network/person-network.component.html b/webapp/src/app/modules/person-network/person-network.component.html index 33475766..9bb58c92 100644 --- a/webapp/src/app/modules/person-network/person-network.component.html +++ b/webapp/src/app/modules/person-network/person-network.component.html @@ -1,5 +1,7 @@
- + @if (collaborationNetwork.nodes.length < 1000) { + + }
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 45986862..66c9c25d 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -84,7 +84,6 @@ export class PersonNetworkComponent implements OnInit { }); readonly searchTerm = computed(() => { - console.log('Search term computed:', this.debouncedFormValue()?.searchTerm); return this.debouncedFormValue()?.searchTerm || ''; }); diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 04a4c7a9..5aa919c1 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -1,38 +1,36 @@ -@if (isPersonLoading()){ - - -
-
-
{{ initials() }}
-
-
- Person -

{{ displayName() }}

+@if (isPersonLoading()) { +
+
+
{{ initials() }}
+
+
+ Person +

{{ displayName() }}

+
+

{{ institution() }}

+ @if (countryCode()) { + {{ countryCode() }} + } + @if (worksCount() !== null || citedByCount() !== null) { + + @if (worksCount() !== null) { + {{ worksCount() }} Publikationen + } + @if (worksCount() !== null && citedByCount() !== null) { + · + } + @if (citedByCount() !== null) { + {{ citedByCount() }} Zitationen + } + + }
-

{{ institution() }}

- @if (countryCode()) { - {{ countryCode() }} - } - @if (worksCount() !== null || citedByCount() !== null) { - - @if (worksCount() !== null) { - {{ worksCount() }} Publikationen - } - @if (worksCount() !== null && citedByCount() !== null) { - · - } - @if (citedByCount() !== null) { - {{ citedByCount() }} Zitationen - } - - } -
-
-
- mail - uni-email@uni-due.de -
- +
+
+ mail + uni-email@uni-due.de +
+ @if (openAlexId()) {
person @@ -40,45 +38,67 @@
} - @if (orcid()) { -
- verified - {{ orcid() }} -
- } -
- language - - ude.de/anna-becker - + @if (orcid()) { +
+ verified + {{ + orcid() + }} +
+ } +
-
- - -
- + + +
+ } @else { -
- -
+
+ + Person wird geladen... + +
} - - \ No newline at end of file + @if (isNetworkResolving()) { +
+
+ + + graph_3 + +
+ Das Netzwerk wird gebaut, kleinen Moment... +
+ } @else { + + } + diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index fe73494e..1dfbf8d2 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -21,12 +21,16 @@ height: 112px; border-radius: 50%; background: - radial-gradient(circle at 50% 30%, rgba(255, 255, 255, 0.78), transparent 34%), + radial-gradient( + circle at 50% 30%, + rgba(255, 255, 255, 0.78), + transparent 34% + ), linear-gradient(145deg, #c8d9ff, #f7faff 48%, #88a9ee); border: 1px solid var(--sg-border); box-shadow: var(--sg-shadow-sm); color: var(--sg-primary); - font-family: 'Montserrat', 'Open Sans', Arial, sans-serif; + font-family: "Montserrat", "Open Sans", Arial, sans-serif; font-size: 28px; font-weight: 700; } @@ -218,3 +222,44 @@ overflow-x: auto; } } + +.loading-container { + display: flex; + flex-direction: column; + align-items: center; + gap: 16px; + padding: 48px 0; +} + +.spinner-container { + --spinner-size: 60px; + + position: relative; + width: var(--spinner-size); + height: var(--spinner-size); +} + +.spinner-icon { + position: absolute; + inset: 0; + margin: auto; + + font-size: calc(var(--spinner-size) * 0.4); + width: calc(var(--spinner-size) * 0.4); + height: calc(var(--spinner-size) * 0.4); + + animation: pulse 1.2s ease-in-out infinite; +} + +@keyframes pulse { + 0%, + 100% { + transform: scale(1); + opacity: 1; + } + + 50% { + transform: scale(1.2); + opacity: 0.7; + } +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 317a5782..529a7676 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -1,10 +1,21 @@ import { Component, computed, inject, signal, DestroyRef } from '@angular/core'; -import { toSignal, toObservable } from '@angular/core/rxjs-interop'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { + toSignal, + toObservable, + takeUntilDestroyed, +} from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatTabsModule } from '@angular/material/tabs'; -import { ActivatedRoute, RouterModule, RouterOutlet } from '@angular/router'; +import { + ActivatedRoute, + ResolveEnd, + ResolveStart, + Router, + RouterEvent, + RouterModule, + RouterOutlet, +} from '@angular/router'; import { of, switchMap, finalize, map, catchError } from 'rxjs'; import { PersonInterestingComponent } from '../person-interesting/person-interesting.component'; @@ -28,19 +39,51 @@ const PERSON_INCLUDE_TAGS = styleUrl: './person.component.scss', }) export class PersonComponent { - private route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly activatedRoute = inject(ActivatedRoute); + private readonly personsApi = inject(PersonsService); private readonly destroyRef = inject(DestroyRef); - + readonly params = toSignal(this.activatedRoute.paramMap); + readonly routerEvents = toSignal(this.router.events); + + readonly currentUrl = computed(() => this.router.url); + // derive authorID directly from route private readonly authorId = toSignal( - this.route.paramMap.pipe( + this.activatedRoute.paramMap.pipe( map((params) => params.get('id') ?? null), - takeUntilDestroyed(this.destroyRef) - ) + takeUntilDestroyed(this.destroyRef), + ), ); + readonly isNetworkResolving = computed(() => { + 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 + ) { + return false; + } + + if (event instanceof ResolveStart) { + return true; + } + + return false; + }); + + isResolverEvent(event: RouterEvent): boolean { + return event instanceof ResolveStart || event instanceof ResolveEnd; + } + + isNetworkRouterEvent(event: RouterEvent): boolean { + return event.url.startsWith(`/person/${this.authorId()}/network`); + } + // loading states readonly isPersonLoading = signal(false); readonly isBioLoading = signal(false); @@ -56,36 +99,36 @@ export class PersonComponent { console.error('Failed to load person:', err); return of(null); }), - finalize(() => this.isPersonLoading.set(false)) + finalize(() => this.isPersonLoading.set(false)), ); - }) + }), ), - { initialValue: null } + { initialValue: null }, ); // bio data -readonly personBio = toSignal( - toObservable(this.authorId).pipe( - switchMap((id) => { - if (!id) { - this.isBioLoading.set(false); - return of(null); - } - this.isBioLoading.set(true); - return this.personsApi.generatePersonBio(id).pipe( - map((result) => { - this.isBioLoading.set(false); - return result.bio ?? null; - }), - catchError((err) => { - console.error('Failed to load bio:', err); + readonly personBio = toSignal( + toObservable(this.authorId).pipe( + switchMap((id) => { + if (!id) { this.isBioLoading.set(false); return of(null); - }) - ); - }) - ), - { initialValue: null } -); + } + this.isBioLoading.set(true); + return this.personsApi.generatePersonBio(id).pipe( + map((result) => { + this.isBioLoading.set(false); + return result.bio ?? null; + }), + catchError((err) => { + console.error('Failed to load bio:', err); + this.isBioLoading.set(false); + return of(null); + }), + ); + }), + ), + { initialValue: null }, + ); readonly displayName = computed( () => this.person()?.display_name ?? 'Unbekannte Person', ); @@ -94,7 +137,9 @@ readonly personBio = toSignal( () => this.person()?.affiliations?.[0] ?? null, ); readonly institution = computed( - () => this.primaryAffiliation()?.institution?.display_name ?? 'Unbekannte Institution', + () => + this.primaryAffiliation()?.institution?.display_name ?? + 'Unbekannte Institution', ); readonly countryCode = computed( () => this.primaryAffiliation()?.institution?.country_code ?? null, @@ -114,9 +159,7 @@ readonly personBio = toSignal( readonly worksApiUrl = computed(() => this.person()?.works_api_url ?? null); readonly openAlexId = computed(() => this.person()?.id ?? null); - readonly topicsFull = computed( - () => this.person()?.topics ?? [], - ); + readonly topicsFull = computed(() => this.person()?.topics ?? []); links = [ { label: 'Übersicht', path: 'overview', disabled: false }, { label: 'Projekte', path: 'projects', disabled: true }, diff --git a/webapp/src/app/resolvers/collaboration-network.resolver.ts b/webapp/src/app/resolvers/collaboration-network.resolver.ts index e09b8747..b67074b2 100644 --- a/webapp/src/app/resolvers/collaboration-network.resolver.ts +++ b/webapp/src/app/resolvers/collaboration-network.resolver.ts @@ -27,7 +27,6 @@ export const collaborationNetworkResolver: ResolveFn = ( const institutions = route.queryParamMap.get('institutions'); const topics = route.queryParamMap.get('topics'); - console.log('Resolving collaboration network for author ID:', rawAuthorId); const filterProperties: FilterProperties = { start_year: startYear ? Number.parseInt(startYear, 10) : null, end_year: endYear ? Number.parseInt(endYear, 10) : null, @@ -46,7 +45,6 @@ export const collaborationNetworkResolver: ResolveFn = ( allowed_institutions: institutions ? institutions.split(',') : null, allowed_topics: topics ? topics.split(',') : null, }; - console.log('Using filter properties:', filterProperties); return inject(PersonNetworkService).getCollaborationNetwork( rawAuthorId, diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index 17b951de..b938fc0f 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -6,6 +6,8 @@ @include mat.elevation-classes(); @include mat.app-background(); +@import url("https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,200..700,0..1,-50..200"); + @font-face { font-display: swap; font-family: "Montserrat"; @@ -58,6 +60,22 @@ -webkit-font-smoothing: antialiased; } +.material-symbols-outlined { + font-family: "Material Symbols Outlined"; + font-weight: normal; + font-style: normal; + font-size: 24px; + line-height: 1; + letter-spacing: normal; + text-transform: none; + display: inline-block; + white-space: nowrap; + word-wrap: normal; + direction: ltr; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; +} + html { padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); From 736277d6ffcdd98115681bf35f3ebee4a95bf2c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 4 Jun 2026 21:44:16 +0200 Subject: [PATCH 02/33] Moved network filter to dialog component --- .../person-network-graph.component.html | 26 +- .../person-network-graph.component.scss | 10 + .../person-network-graph.component.ts | 39 ++- .../person-network.component.html | 228 +++++------------- .../person-network.component.scss | 58 +++-- .../person-network.component.ts | 45 +++- ...erson-network-filter-dialog.component.html | 107 ++++++++ ...erson-network-filter-dialog.component.scss | 31 +++ .../person-network-filter-dialog.component.ts | 71 ++++++ 9 files changed, 404 insertions(+), 211 deletions(-) create mode 100644 webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.html create mode 100644 webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.scss create mode 100644 webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html index 8a37053e..a80560d8 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html @@ -1,16 +1,18 @@ - - Kollaborations Netzwerk von {{ authorDisplayName }} - -
+ @if (!isValidGraph()) { +
+ warning +

Das Netzwerk ist zu groß für eine detaillierte Darstellung.

+
+ } @else { +
+ }
diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss b/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss index ebdd5e69..93a43f1b 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss @@ -13,6 +13,7 @@ mat-card { mat-card-content { flex: 1 1 auto; min-height: 0; + align-items: center; } .graph { @@ -24,3 +25,12 @@ mat-card-content { user-select: none; cursor: grab; } + +.warning-container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 24px; +} diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index f3e16580..018ee2be 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -1,4 +1,4 @@ -import { Component, effect, input } from '@angular/core'; +import { Component, computed, effect, input } from '@angular/core'; import { MatCardModule } from '@angular/material/card'; import { CollaborationNetwork } from '../../api'; import { NgxEchartsDirective } from 'ngx-echarts'; @@ -8,11 +8,12 @@ import * as echarts from 'echarts/core'; import { GridComponent, TitleComponent } from 'echarts/components'; import { CanvasRenderer } from 'echarts/renderers'; import { GraphChart } from 'echarts/charts'; +import { MatIconModule } from '@angular/material/icon'; echarts.use([GridComponent, CanvasRenderer, GraphChart, TitleComponent]); @Component({ selector: 'app-person-network-graph', - imports: [MatCardModule, NgxEchartsDirective], + imports: [MatCardModule, MatIconModule, NgxEchartsDirective], templateUrl: './person-network-graph.component.html', styleUrl: './person-network-graph.component.scss', }) @@ -23,6 +24,16 @@ export class PersonNetworkGraphComponent { options!: EChartsCoreOption; + readonly isValidGraph = computed(() => { + const network = this.collaborationNetwork(); + return ( + network !== undefined && + network.nodes.length > 0 && + network.nodes.length < 1000 && + network.edges.length > 0 + ); + }); + constructor() { effect(() => { const network = this.collaborationNetwork(); @@ -42,6 +53,12 @@ export class PersonNetworkGraphComponent { return; } + const frequencies = + this.calculateOccurenceFrequencies(collaborationNetwork); + + const minFrequency = Math.min(...Object.values(frequencies)); + const maxFrequency = Math.max(...Object.values(frequencies)); + const datas = [ { nodes: collaborationNetwork.nodes.map((node) => { @@ -73,6 +90,11 @@ export class PersonNetworkGraphComponent { label: { show: true, }, + symbolSize: + 25 + + (((frequencies[node.raw_id] || 0) - minFrequency) / + (maxFrequency - minFrequency)) * + 30, }; }), links: collaborationNetwork.edges.map((edge) => { @@ -134,4 +156,17 @@ export class PersonNetworkGraphComponent { }), }; } + + calculateOccurenceFrequencies( + netork: CollaborationNetwork, + ): Record { + const frequencies: Record = {}; + netork.edges.forEach((edge) => { + frequencies[edge.raw_source_id] = + (frequencies[edge.raw_source_id] || 0) + 1; + frequencies[edge.raw_target_id] = + (frequencies[edge.raw_target_id] || 0) + 1; + }); + return frequencies; + } } diff --git a/webapp/src/app/modules/person-network/person-network.component.html b/webapp/src/app/modules/person-network/person-network.component.html index 9bb58c92..d68d7eee 100644 --- a/webapp/src/app/modules/person-network/person-network.component.html +++ b/webapp/src/app/modules/person-network/person-network.component.html @@ -1,172 +1,72 @@
- @if (collaborationNetwork.nodes.length < 1000) { - - } +
+
+
Netzwerk
+

Zusammenarbeit und Verbindungen im wissenschaftlichen Netzwerk.

+
+ +
-
- - - - Filter - -
- - Startjahr (inklusive) - - - - Endjahr (inklusive) - - -
-
- - Minimale Anzahl von Kollaborierenden (inklusiv) - - - - Maximale Anzahl von Kollaborierenden (exklusiv) - - -
-
- - Minimale Anzahl von Kollaborationen (inklusiv) - - - - Maximale Anzahl von Kollaborationen (inklusiv) - - -
+
+ -
- - Institutionen - - @for ( - institution of collaborationNetwork.filter_information - .institutions; - track institution.raw_id - ) { - - {{ institution.display_name }} - - } - - - - Themen - - @for ( - topic of collaborationNetwork.filter_information.topics; - track topic.raw_topic_id - ) { - - {{ topic.display_name }} - - } - - -
- - - - - Kollaborierende - - Publikationen + + - - - {{ - this.displayedTable() === "collaborators" - ? "Suche Kollaborierende nach Name oder ID" - : "Suche Publikationen nach Titel oder ID" - }} - - search - - + + Kollaborierende + + Publikationen + + + {{ + this.displayedTable() === "collaborators" + ? "Suche Kollaborierende nach Name oder ID" + : "Suche Publikationen nach Titel oder ID" + }} + + search + + -
- - -
- @if (this.displayedTable() === "collaborators") { - - } @else if (this.displayedTable() === "publications") { - - } -
-
-
+
+ + +
+ @if (this.displayedTable() === "collaborators") { + + } @else if (this.displayedTable() === "publications") { + + } +
+
+
+
diff --git a/webapp/src/app/modules/person-network/person-network.component.scss b/webapp/src/app/modules/person-network/person-network.component.scss index 234fc412..b51ee5be 100644 --- a/webapp/src/app/modules/person-network/person-network.component.scss +++ b/webapp/src/app/modules/person-network/person-network.component.scss @@ -1,47 +1,36 @@ .content { display: flex; - flex-direction: row; + flex-direction: column; padding: 40px; gap: 20px; align-items: stretch; } +.top-row { + display: flex; + flex-direction: row; + justify-content: space-between; + align-items: end; + gap: 20px; +} + +.description-container { + display: flex; + flex-direction: column; +} + +.cards { + display: flex; + flex-direction: row; + gap: 20px; +} + .content > app-person-network-graph, .right-card { flex: 1 1 0; min-width: 0; } -.table { - overflow: auto; - width: 100%; - max-height: 70vh; - height: 100%; -} - -.table table { - width: 100%; -} - -.table-area { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; -} - -.scroll-viewport-container { - width: 100%; - height: 100%; -} - -.form-controls { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 10px; -} - .form-field-full { width: 100%; } @@ -67,3 +56,10 @@ .pair-field > mat-form-field { width: 100%; } + +.top-row button { + height: 42px; + border-color: var(--sg-border); + border-radius: var(--sg-radius-sm); + color: var(--sg-text); +} \ No newline at end of file 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 66c9c25d..0c192706 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -29,6 +29,8 @@ import { debounceTime } from 'rxjs'; import { PersonNetworkGraphComponent } from '../person-network-graph/person-network-graph.component'; import { MatSelectModule } from '@angular/material/select'; import { MatExpansionModule } from '@angular/material/expansion'; +import { MatDialog, MatDialogModule } from '@angular/material/dialog'; +import { PersonNetworkFilterDialogComponent } from '../../person-network-filter-dialog/person-network-filter-dialog.component'; @Component({ selector: 'app-person-network', @@ -53,6 +55,7 @@ import { MatExpansionModule } from '@angular/material/expansion'; PersonNetworkGraphComponent, MatSelectModule, MatExpansionModule, + MatDialogModule, ], templateUrl: './person-network.component.html', styleUrl: './person-network.component.scss', @@ -89,13 +92,51 @@ export class PersonNetworkComponent implements OnInit { readonly activatedRouteData = toSignal(this.activatedRoute.data); - formatYearLabel = (value: number) => `${value}`; - constructor( private readonly activatedRoute: ActivatedRoute, private readonly router: Router, + private readonly dialog: MatDialog, ) {} + openFilterDialog() { + const dialogRef = this.dialog.open(PersonNetworkFilterDialogComponent, { + data: { + collaborationNetwork: this.collaborationNetwork, + startYear: this.filterForm.get('startYear')?.value, + endYear: this.filterForm.get('endYear')?.value, + minimumCollaborators: this.filterForm.get('minimumCollaborators') + ?.value, + maximumCollaborators: this.filterForm.get('maximumCollaborators') + ?.value, + minimumCollaborations: this.filterForm.get('minimumCollaborations') + ?.value, + maximumCollaborations: this.filterForm.get('maximumCollaborations') + ?.value, + institutions: this.filterForm.get('institutions')?.value, + topics: this.filterForm.get('topics')?.value, + }, + }); + + dialogRef.afterClosed().subscribe((result) => { + console.log('Dialog result:', result); + if (result) { + this.filterForm.setValue({ + searchTerm: this.filterForm.get('searchTerm')?.value || '', + startYear: result.startYear, + endYear: result.endYear, + minimumCollaborators: result.minimumCollaborators, + maximumCollaborators: result.maximumCollaborators, + minimumCollaborations: result.minimumCollaborations, + maximumCollaborations: result.maximumCollaborations, + institutions: result.institutions, + topics: result.topics, + displayedTable: + this.filterForm.get('displayedTable')?.value || 'collaborators', + }); + } + }); + } + ngOnInit(): void { this.activatedRoute.data.subscribe(({ collaborationNetwork }) => { this.collaborationNetwork = collaborationNetwork; diff --git a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.html b/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.html new file mode 100644 index 00000000..c9bef5f4 --- /dev/null +++ b/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.html @@ -0,0 +1,107 @@ +

Netzwerkfilter

+ + +
+
+ + Startjahr (inklusive) + + + + Endjahr (inklusive) + + +
+ + + Minimale Anzahl von Kollaborierenden (inklusiv) + + + + Maximale Anzahl von Kollaborierenden (exklusiv) + + + + + Minimale Anzahl von Kollaborationen (inklusiv) + + + + Maximale Anzahl von Kollaborationen (inklusiv) + + + + + Institutionen + + @for ( + institution of collaborationNetwork.filter_information.institutions; + track institution.raw_id + ) { + + {{ institution.display_name }} + + } + + + + Themen + + @for ( + topic of collaborationNetwork.filter_information.topics; + track topic.raw_topic_id + ) { + + {{ topic.display_name }} + + } + + +
+
+ + + + diff --git a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.scss b/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.scss new file mode 100644 index 00000000..8a9b4eb9 --- /dev/null +++ b/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.scss @@ -0,0 +1,31 @@ +form { + padding: 20px; + display: flex; + flex-direction: column; + gap: 20px; +} + + + +.form-field-full { + width: 100%; +} + + +.toggle-group { + margin-bottom: 20px; +} + +.toggle-group .mat-button-toggle { + text-transform: none; + width: 100%; +} + +.pair-field { + display: flex; + gap: 20px; +} + +.pair-field > mat-form-field { + width: 100%; +} diff --git a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts b/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts new file mode 100644 index 00000000..f452c4df --- /dev/null +++ b/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts @@ -0,0 +1,71 @@ +import { Component, inject } from '@angular/core'; +import { + FormControl, + FormGroup, + FormsModule, + ReactiveFormsModule, +} from '@angular/forms'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { CollaborationNetwork } from '../api'; +import { MatSelectModule } from '@angular/material/select'; +import { MatInputModule } from '@angular/material/input'; +import { MatButtonModule } from '@angular/material/button'; + +export interface PersonNetworkFilterDialogData { + collaborationNetwork: CollaborationNetwork; + startYear: number; + endYear: number; + minimumCollaborators: number; + maximumCollaborators: number; + minimumCollaborations: number; + maximumCollaborations: number; + institutions: string[]; + topics: string[]; +} + +@Component({ + selector: 'app-person-network-filter-dialog', + imports: [ + FormsModule, + ReactiveFormsModule, + MatFormFieldModule, + MatSelectModule, + MatDialogModule, + MatInputModule, + MatButtonModule + ], + templateUrl: './person-network-filter-dialog.component.html', + styleUrl: './person-network-filter-dialog.component.scss', +}) +export class PersonNetworkFilterDialogComponent { + readonly dialogRef = inject(MatDialogRef); + readonly data = inject(MAT_DIALOG_DATA); + + readonly collaborationNetwork = this.data.collaborationNetwork; + + filterForm = new FormGroup({ + startYear: new FormControl(2000), + endYear: new FormControl(2025), + minimumCollaborators: new FormControl(2), + maximumCollaborators: new FormControl(10), + minimumCollaborations: new FormControl(1), + maximumCollaborations: new FormControl(100), + institutions: new FormControl([]), + topics: new FormControl([]), + }); + + onCancel() { + this.dialogRef.close(); + } + + onApply() { + if (this.filterForm.valid) { + this.dialogRef.close(this.filterForm.value); + } + } +} From fe6f64cc8c833656effdfb3dd564c290bf760ee6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Thu, 4 Jun 2026 23:42:39 +0200 Subject: [PATCH 03/33] Added summary cards for network --- ...erson-network-collaborators.component.scss | 58 +----------- ...erson-network-filter-dialog.component.html | 0 ...erson-network-filter-dialog.component.scss | 0 .../person-network-filter-dialog.component.ts | 25 ++++-- .../person-network-graph.component.html | 7 +- .../person-network-graph.component.scss | 5 +- .../person-network-graph.component.ts | 9 ++ .../person-network-info-card.component.html | 9 ++ .../person-network-info-card.component.scss | 34 +++++++ .../person-network-info-card.component.ts | 15 ++++ ...person-network-publications.component.scss | 55 +----------- .../person-network.component.html | 90 ++++++++++--------- .../person-network.component.scss | 60 ++++++------- .../person-network.component.ts | 53 ++++++++++- webapp/src/styles.scss | 3 + 15 files changed, 232 insertions(+), 191 deletions(-) rename webapp/src/app/{ => modules}/person-network-filter-dialog/person-network-filter-dialog.component.html (100%) rename webapp/src/app/{ => modules}/person-network-filter-dialog/person-network-filter-dialog.component.scss (100%) rename webapp/src/app/{ => modules}/person-network-filter-dialog/person-network-filter-dialog.component.ts (70%) create mode 100644 webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html create mode 100644 webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss create mode 100644 webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss index efec585e..57d2cbf4 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss @@ -1,60 +1,11 @@ -.content { - display: flex; - flex-direction: row; - padding: 40px; - gap: 20px; - max-height: 1000px; -} - -.graph { - width: 75vh; - height: 75vh; -} - .table { overflow: auto; width: 100%; - max-height: 1000px; - height: 1200px; + max-height: 100%; } -.table table { - width: 100%; -} - -.table-area { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; -} - -.scroll-viewport-container { - width: 100%; - height: 100%; -} - -.form-controls { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 10px; -} - -.form-field-full { - width: 100%; -} - -.right-card { - width: 100%; -} - -.toggle-group { - margin-bottom: 20px; -} - -.toggle-group .mat-button-toggle { - text-transform: none; +.mat-mdc-table { + background-color: var(--sg-background); } .element-row { @@ -75,5 +26,4 @@ .detail-row { width: 100%; - -} \ No newline at end of file +} diff --git a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.html b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.html similarity index 100% rename from webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.html rename to webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.html diff --git a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.scss b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss similarity index 100% rename from webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.scss rename to webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss diff --git a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.ts similarity index 70% rename from webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts rename to webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.ts index f452c4df..d69c6570 100644 --- a/webapp/src/app/person-network-filter-dialog/person-network-filter-dialog.component.ts +++ b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.ts @@ -1,4 +1,4 @@ -import { Component, inject } from '@angular/core'; +import { Component, inject, OnInit } from '@angular/core'; import { FormControl, FormGroup, @@ -11,7 +11,7 @@ import { MatDialogRef, } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; -import { CollaborationNetwork } from '../api'; +import { CollaborationNetwork } from '../../api'; import { MatSelectModule } from '@angular/material/select'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; @@ -37,12 +37,12 @@ export interface PersonNetworkFilterDialogData { MatSelectModule, MatDialogModule, MatInputModule, - MatButtonModule + MatButtonModule, ], templateUrl: './person-network-filter-dialog.component.html', styleUrl: './person-network-filter-dialog.component.scss', }) -export class PersonNetworkFilterDialogComponent { +export class PersonNetworkFilterDialogComponent implements OnInit { readonly dialogRef = inject(MatDialogRef); readonly data = inject(MAT_DIALOG_DATA); @@ -55,10 +55,23 @@ export class PersonNetworkFilterDialogComponent { maximumCollaborators: new FormControl(10), minimumCollaborations: new FormControl(1), maximumCollaborations: new FormControl(100), - institutions: new FormControl([]), - topics: new FormControl([]), + institutions: new FormControl([]), + topics: new FormControl([]), }); + ngOnInit() { + this.filterForm.patchValue({ + startYear: this.data.startYear, + endYear: this.data.endYear, + minimumCollaborators: this.data.minimumCollaborators, + maximumCollaborators: this.data.maximumCollaborators, + minimumCollaborations: this.data.minimumCollaborations, + maximumCollaborations: this.data.maximumCollaborations, + institutions: this.data.institutions, + topics: this.data.topics, + }); + } + onCancel() { this.dialogRef.close(); } diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html index a80560d8..ce985536 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html @@ -1,6 +1,11 @@ - @if (!isValidGraph()) { + @if (isEmptyGraph()) { +
+ warning +

Das Netzwerk ist leer.

+
+ } @else if (!isValidGraph()) {
warning

Das Netzwerk ist zu groß für eine detaillierte Darstellung.

diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss b/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss index 93a43f1b..f1ae7054 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.scss @@ -7,13 +7,14 @@ mat-card { display: flex; flex-direction: column; width: 100%; - background: transparent; + background-color: var(--sg-background); } -mat-card-content { +mat-card > mat-card-content { flex: 1 1 auto; min-height: 0; align-items: center; + padding: 0px; } .graph { diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index 018ee2be..3b7b8d31 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -24,6 +24,15 @@ export class PersonNetworkGraphComponent { options!: EChartsCoreOption; + readonly isEmptyGraph = computed(() => { + const network = this.collaborationNetwork(); + return ( + network === undefined || + network.nodes.length === 0 || + network.edges.length === 0 + ); + }); + readonly isValidGraph = computed(() => { const network = this.collaborationNetwork(); return ( diff --git a/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html new file mode 100644 index 00000000..29c0ea8b --- /dev/null +++ b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.html @@ -0,0 +1,9 @@ + + + {{ icon() }} +
+ {{ value() }} + {{ description() }} +
+
+
diff --git a/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss new file mode 100644 index 00000000..13a84cc6 --- /dev/null +++ b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.scss @@ -0,0 +1,34 @@ +.info-card { + --info-card-icon-size: 40px; + + background-color: var(--sg-background); + padding: 10px 20px; +} +.info-card mat-card-content { + display: flex; + align-items: start; + gap: 10px; +} + +.info-card mat-icon { + width: var(--info-card-icon-size); + height: var(--info-card-icon-size); + font-size: var(--info-card-icon-size); + color: var(--sg-blue-highlight); +} + +.info-card div { + display: flex; + flex-direction: column; + gap: 4px; +} + +.info-card .number { + font-weight: var(--sg-default-bold-weight); + font-size: 1.5em; +} + +.info-card .description { + color: var(--sg-text-muted); + font-size: 0.9em; +} diff --git a/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts new file mode 100644 index 00000000..fe5c3913 --- /dev/null +++ b/webapp/src/app/modules/person-network-info-card/person-network-info-card.component.ts @@ -0,0 +1,15 @@ +import { Component, input } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; + +@Component({ + selector: 'app-person-network-info-card', + imports: [MatIconModule, MatCardModule], + templateUrl: './person-network-info-card.component.html', + styleUrl: './person-network-info-card.component.scss', +}) +export class PersonNetworkInfoCardComponent { + readonly icon = input(); + readonly value = input(); + readonly description = input(); +} diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss b/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss index b6462c61..57d2cbf4 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss @@ -1,60 +1,11 @@ -.content { - display: flex; - flex-direction: row; - padding: 40px; - gap: 20px; - max-height: 1000px; -} - -.graph { - width: 75vh; - height: 75vh; -} - .table { overflow: auto; width: 100%; - max-height: 1000px; - height: 1200px; + max-height: 100%; } -.table table { - width: 100%; -} - -.table-area { - width: 100%; - height: 100%; - display: flex; - flex-direction: column; -} - -.scroll-viewport-container { - width: 100%; - height: 100%; -} - -.form-controls { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 10px; -} - -.form-field-full { - width: 100%; -} - -.right-card { - width: 100%; -} - -.toggle-group { - margin-bottom: 20px; -} - -.toggle-group .mat-button-toggle { - text-transform: none; +.mat-mdc-table { + background-color: var(--sg-background); } .element-row { diff --git a/webapp/src/app/modules/person-network/person-network.component.html b/webapp/src/app/modules/person-network/person-network.component.html index d68d7eee..9cd6ab62 100644 --- a/webapp/src/app/modules/person-network/person-network.component.html +++ b/webapp/src/app/modules/person-network/person-network.component.html @@ -1,13 +1,7 @@
-
-
-
Netzwerk
-

Zusammenarbeit und Verbindungen im wissenschaftlichen Netzwerk.

-
- +
+
Netzwerk
+

Zusammenarbeit und Verbindungen im wissenschaftlichen Netzwerk.

@@ -18,21 +12,27 @@
- - - Kollaborierende - - Publikationen + - - + + Kollaborierende + + Publikationen + + +
+ {{ this.displayedTable() === "collaborators" ? "Suche Kollaborierende nach Name oder ID" @@ -48,25 +48,31 @@ -
- - -
- @if (this.displayedTable() === "collaborators") { - - } @else if (this.displayedTable() === "publications") { - - } -
-
-
-
+ + + @if (this.displayedTable() === "collaborators") { + + } @else if (this.displayedTable() === "publications") { + + } + +
+ +
+ @for (summary of this.summaryCards(); track $index) { + + } +
diff --git a/webapp/src/app/modules/person-network/person-network.component.scss b/webapp/src/app/modules/person-network/person-network.component.scss index b51ee5be..36506868 100644 --- a/webapp/src/app/modules/person-network/person-network.component.scss +++ b/webapp/src/app/modules/person-network/person-network.component.scss @@ -1,16 +1,7 @@ .content { display: flex; flex-direction: column; - padding: 40px; - gap: 20px; - align-items: stretch; -} - -.top-row { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: end; + padding: 30px; gap: 20px; } @@ -23,24 +14,26 @@ display: flex; flex-direction: row; gap: 20px; + max-height: 80vh; +} + +form > div { + display: flex; + flex-direction: row; + gap: 20px; +} + +form > div > button, +form > div > mat-button-toggle-group { + margin-top: 20px; + margin-bottom: 20px; + border-radius: var(--sg-radius-sm); + color: var(--sg-text); } .content > app-person-network-graph, .right-card { flex: 1 1 0; - min-width: 0; -} - -.form-field-full { - width: 100%; -} - -.right-card { - width: 100%; -} - -.toggle-group { - margin-bottom: 20px; } .toggle-group .mat-button-toggle { @@ -48,18 +41,21 @@ width: 100%; } -.pair-field { +.summary-container { display: flex; + flex-direction: row; gap: 20px; } -.pair-field > mat-form-field { - width: 100%; +.summary-container app-person-network-info-card { + flex: 1 1 0; } -.top-row button { - height: 42px; - border-color: var(--sg-border); - border-radius: var(--sg-radius-sm); - color: var(--sg-text); -} \ No newline at end of file +.scroll-viewport-container { + height: 50vh; + max-height: 50vh; +} + +mat-card { + background-color: var(--sg-background); +} 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 0c192706..f405bad9 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -1,6 +1,6 @@ import { toSignal } from '@angular/core/rxjs-interop'; -import { Component, computed, OnInit } from '@angular/core'; +import { Component, computed, OnInit, signal } from '@angular/core'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; @@ -30,7 +30,8 @@ import { PersonNetworkGraphComponent } from '../person-network-graph/person-netw import { MatSelectModule } from '@angular/material/select'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; -import { PersonNetworkFilterDialogComponent } from '../../person-network-filter-dialog/person-network-filter-dialog.component'; +import { PersonNetworkFilterDialogComponent } from '../person-network-filter-dialog/person-network-filter-dialog.component'; +import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; @Component({ selector: 'app-person-network', @@ -56,6 +57,7 @@ import { PersonNetworkFilterDialogComponent } from '../../person-network-filter- MatSelectModule, MatExpansionModule, MatDialogModule, + PersonNetworkInfoCardComponent, ], templateUrl: './person-network.component.html', styleUrl: './person-network.component.scss', @@ -77,6 +79,34 @@ export class PersonNetworkComponent implements OnInit { displayedTable: new FormControl('collaborators'), }); + persons = signal(0); + institutions = signal(0); + publications = signal(0); + connections = signal(0); + + readonly summaryCards = computed(() => [ + { + icon: 'person', + value: this.persons(), + description: 'Personen', + }, + { + icon: 'apartment', + value: this.institutions(), + description: 'Institutionen', + }, + { + icon: 'menu_book', + value: this.publications(), + description: 'Gemeinsame Publikationen', + }, + { + icon: 'share', + value: this.connections(), + description: 'Verbindungen im Netzwerk', + }, + ]); + readonly formValue = toSignal(this.filterForm.valueChanges); readonly debouncedFormValue = toSignal( this.filterForm.valueChanges.pipe(debounceTime(300)), @@ -137,10 +167,29 @@ export class PersonNetworkComponent implements OnInit { }); } + calculateSummary(collaborationNetwork: CollaborationNetwork) { + this.persons.set( + collaborationNetwork.nodes.filter((node) => node.category === 'author') + .length, + ); + this.institutions.set( + collaborationNetwork.nodes.filter( + (node) => node.category === 'institution', + ).length, + ); + this.publications.set( + collaborationNetwork.nodes.filter((node) => node.category === 'work') + .length, + ); + this.connections.set(collaborationNetwork.edges.length); + } + ngOnInit(): void { this.activatedRoute.data.subscribe(({ collaborationNetwork }) => { this.collaborationNetwork = collaborationNetwork; + this.calculateSummary(collaborationNetwork); + const currentParams = this.activatedRoute.snapshot.queryParams; const initialStartYear = Number(currentParams['start_year']) || diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index b938fc0f..271f28ac 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -118,6 +118,9 @@ body { --sg-radius-sm: 8px; --sg-radius-md: 12px; --sg-radius-lg: 18px; + + --sg-blue-highlight: #3d7cff; + --sg-default-bold-weight: 900; } * { From e107657318969824e8ab7a40907c1996884976be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 5 Jun 2026 10:52:08 +0200 Subject: [PATCH 04/33] Added legend and clickable nodes to graph --- .../person-network-graph.component.html | 1 + .../person-network-graph.component.ts | 107 +++++++++++++----- .../person-network.component.html | 1 + .../person-network.component.ts | 29 ++++- 4 files changed, 107 insertions(+), 31 deletions(-) diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html index ce985536..d3452f05 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.html +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.html @@ -17,6 +17,7 @@ [options]="options" [autoResize]="true" (wheel)="onGraphWheel($event)" + (chartClick)="onChartEvent($event, 'chartClick')" >
}
diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index 3b7b8d31..7362cb6a 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -1,25 +1,46 @@ -import { Component, computed, effect, input } from '@angular/core'; +import { Component, computed, effect, input, output } from '@angular/core'; import { MatCardModule } from '@angular/material/card'; import { CollaborationNetwork } from '../../api'; import { NgxEchartsDirective } from 'ngx-echarts'; import { EChartsCoreOption } from 'echarts/types/dist/core'; import * as echarts from 'echarts/core'; -import { GridComponent, TitleComponent } from 'echarts/components'; +import { + GridComponent, + LegendComponent, + TitleComponent, +} from 'echarts/components'; import { CanvasRenderer } from 'echarts/renderers'; import { GraphChart } from 'echarts/charts'; import { MatIconModule } from '@angular/material/icon'; -echarts.use([GridComponent, CanvasRenderer, GraphChart, TitleComponent]); +import { ActivatedRoute, Router } from '@angular/router'; +echarts.use([ + GridComponent, + CanvasRenderer, + GraphChart, + TitleComponent, + LegendComponent, +]); + +export type NodeCategory = 'author' | 'collaborator' | 'work'; + +export interface NodeClickEvent { + id: string; + name: string; + category: NodeCategory; +} @Component({ selector: 'app-person-network-graph', imports: [MatCardModule, MatIconModule, NgxEchartsDirective], templateUrl: './person-network-graph.component.html', - styleUrl: './person-network-graph.component.scss', + styleUrls: ['./person-network-graph.component.scss'], }) export class PersonNetworkGraphComponent { collaborationNetwork = input(); + handleNodeClick = output(); + authorDisplayName: string = ''; options!: EChartsCoreOption; @@ -57,6 +78,26 @@ export class PersonNetworkGraphComponent { event.preventDefault(); } + categoryLabels: Record = { + author: 'Autor', + collaborator: 'Kollaborierender', + institution: 'Institution', + work: 'Arbeit', + }; + + onChartEvent(event: any, type: string) { + if (type !== 'chartClick') { + return; + } + const id = event?.data?.id; + const name = event?.data?.name; + const category = event?.data?.category; + if (!id || !name || !category) { + return; + } + this.handleNodeClick.emit({ id, name, category }); + } + private updateGraphOptions(collaborationNetwork: CollaborationNetwork): void { if (!collaborationNetwork) { return; @@ -65,8 +106,11 @@ export class PersonNetworkGraphComponent { const frequencies = this.calculateOccurenceFrequencies(collaborationNetwork); - const minFrequency = Math.min(...Object.values(frequencies)); - const maxFrequency = Math.max(...Object.values(frequencies)); + const freqValues = Object.values(frequencies); + const minFrequency = freqValues.length ? Math.min(...freqValues) : 0; + const maxFrequency = freqValues.length ? Math.max(...freqValues) : 0; + const freqDenominator = + maxFrequency === minFrequency ? 1 : maxFrequency - minFrequency; const datas = [ { @@ -84,26 +128,26 @@ export class PersonNetworkGraphComponent { return 'collaborator'; })(); - if (node.category === 'work') { - return { - id: node.raw_id + '', - name: node.display_name, - category, - }; - } + const baseId = node.raw_id + ''; + const nodeFreq = frequencies[node.raw_id] || 0; + const computedSymbolSize = + 25 + ((nodeFreq - minFrequency) / freqDenominator) * 30; return { - id: node.raw_id + '', + id: baseId, name: node.display_name, category, label: { - show: true, + show: node.category !== 'work', + formatter: '{b}', }, - symbolSize: - 25 + - (((frequencies[node.raw_id] || 0) - minFrequency) / - (maxFrequency - minFrequency)) * - 30, + emphasis: { + label: { + show: true, + formatter: '{b}', + }, + }, + symbolSize: node.category === 'work' ? 15 : computedSymbolSize, }; }), links: collaborationNetwork.edges.map((edge) => { @@ -126,25 +170,29 @@ export class PersonNetworkGraphComponent { }, ]; - this.authorDisplayName = - collaborationNetwork.nodes.find( - (node) => node.raw_id === collaborationNetwork.raw_person_id, - )?.display_name || 'Unknown Author'; + const legendData = datas.length + ? datas[0].categories.map((c) => c.name) + : []; this.options = { + legend: { + data: legendData, + bottom: 0, + orient: 'horizontal', + formatter: (name: string) => this.categoryLabels[name] || name, + itemGap: 20, + }, series: datas.map((item) => { return { - name: this.authorDisplayName, type: 'graph', layout: 'force', - symbolSize: 20, + symbolSize: 15, animation: false, data: item.nodes, roam: true, force: { repulsion: 10000, friction: 0.9, - // edgeLength: 25, gravity: 0.2, }, links: item.links.map((e) => { @@ -165,12 +213,11 @@ export class PersonNetworkGraphComponent { }), }; } - calculateOccurenceFrequencies( - netork: CollaborationNetwork, + network: CollaborationNetwork, ): Record { const frequencies: Record = {}; - netork.edges.forEach((edge) => { + network.edges.forEach((edge) => { frequencies[edge.raw_source_id] = (frequencies[edge.raw_source_id] || 0) + 1; frequencies[edge.raw_target_id] = diff --git a/webapp/src/app/modules/person-network/person-network.component.html b/webapp/src/app/modules/person-network/person-network.component.html index 9cd6ab62..6ed2bd00 100644 --- a/webapp/src/app/modules/person-network/person-network.component.html +++ b/webapp/src/app/modules/person-network/person-network.component.html @@ -7,6 +7,7 @@
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 f405bad9..5dc7902b 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -26,7 +26,11 @@ import { CollaborationNetwork } from '../../api'; import { PersonNetworkCollaboratorsComponent } from '../person-network-collaborators/person-network-collaborators.component'; import { PersonNetworkPublicationsComponent } from '../person-network-publications/person-network-publications.component'; import { debounceTime } from 'rxjs'; -import { PersonNetworkGraphComponent } from '../person-network-graph/person-network-graph.component'; +import { + NodeCategory, + NodeClickEvent, + PersonNetworkGraphComponent, +} from '../person-network-graph/person-network-graph.component'; import { MatSelectModule } from '@angular/material/select'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; @@ -84,6 +88,29 @@ export class PersonNetworkComponent implements OnInit { publications = signal(0); connections = signal(0); + private readonly categoryTableMap: Record = { + author: 'collaborators', + collaborator: 'collaborators', + work: 'publications', + }; + + latestNodeId = signal(null); + + handleNodeClick = ({ id, name, category }: NodeClickEvent): void => { + if (this.latestNodeId() === id) { + this.latestNodeId.set(null); + this.filterForm.patchValue({ searchTerm: '' }); + return; + } + + this.latestNodeId.set(id); + + this.filterForm.patchValue({ + displayedTable: this.categoryTableMap[category], + searchTerm: name, + }); + }; + readonly summaryCards = computed(() => [ { icon: 'person', From f76d63a76c35bdef8d3336c809a4f7ce05ec1634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 5 Jun 2026 14:23:55 +0200 Subject: [PATCH 05/33] Added network table for institutions --- .../person-network-collaborators.component.ts | 4 + .../person-network-graph.component.ts | 3 +- ...person-network-institutions.component.html | 45 +++++++ ...person-network-institutions.component.scss | 29 ++++ .../person-network-institutions.component.ts | 126 ++++++++++++++++++ ...person-network-publications.component.html | 12 -- .../person-network-publications.component.ts | 6 +- .../person-network.component.html | 19 ++- .../person-network.component.ts | 26 +++- 9 files changed, 246 insertions(+), 24 deletions(-) create mode 100644 webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html create mode 100644 webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss create mode 100644 webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts index 6138705f..0860dec1 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts @@ -142,6 +142,10 @@ export class PersonNetworkCollaboratorsComponent implements AfterViewInit { } }); + Object.values(allAuthors).forEach((author) => { + author.works.sort((a, b) => a.title.localeCompare(b.title)); + }); + return new MatTableDataSource( Object.values(allAuthors).filter( (author) => diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index 7362cb6a..8c6235de 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -13,7 +13,6 @@ import { import { CanvasRenderer } from 'echarts/renderers'; import { GraphChart } from 'echarts/charts'; import { MatIconModule } from '@angular/material/icon'; -import { ActivatedRoute, Router } from '@angular/router'; echarts.use([ GridComponent, CanvasRenderer, @@ -22,7 +21,7 @@ echarts.use([ LegendComponent, ]); -export type NodeCategory = 'author' | 'collaborator' | 'work'; +export type NodeCategory = 'author' | 'collaborator' | 'work' | 'institution'; export interface NodeClickEvent { id: string; diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html new file mode 100644 index 00000000..052d4d06 --- /dev/null +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html @@ -0,0 +1,45 @@ +
+ + + + + + + + + + + + + + + + +
ID{{ element.id }}Titel + {{ element.name }} + Mitwirkende + {{ element.collaborators.length }} +
+
+ + + + +
    + @for (collaborator of element.collaborators; track $index) { +
  • + {{ collaborator.name }} + ({{ collaborator.id }}) +
  • + } +
+ + +
diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss new file mode 100644 index 00000000..57d2cbf4 --- /dev/null +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss @@ -0,0 +1,29 @@ +.table { + overflow: auto; + width: 100%; + max-height: 100%; +} + +.mat-mdc-table { + background-color: var(--sg-background); +} + +.element-row { + position: relative; +} + +.element-row:not(.expanded) { + cursor: pointer; +} + +.element-row:not(.expanded):hover { + background: #f5f5f5; +} + +.element-row.expanded { + border-bottom-color: transparent; +} + +.detail-row { + width: 100%; +} diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts new file mode 100644 index 00000000..38df3cbe --- /dev/null +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts @@ -0,0 +1,126 @@ +import { + AfterViewInit, + Component, + effect, + input, + ViewChild, +} from '@angular/core'; +import { CollaborationNetwork } from '../../api'; +import { MatTableDataSource, MatTableModule } from '@angular/material/table'; +import { MatSort, MatSortModule } from '@angular/material/sort'; +import { MatIconModule } from '@angular/material/icon'; +import { RouterModule } from '@angular/router'; +import { CdkDetailRowDirective } from '../../directives/cdk-detail-row.directive'; +import { MatButtonModule } from '@angular/material/button'; + +type Collaborator = { + id: string; + name: string; +}; + +type Institution = { + id: string; + name: string; + collaborators: Collaborator[]; +}; + +@Component({ + selector: 'app-person-network-institutions', + imports: [ + MatTableModule, + MatIconModule, + MatSortModule, + RouterModule, + CdkDetailRowDirective, + MatButtonModule, + ], + templateUrl: './person-network-institutions.component.html', + styleUrl: './person-network-institutions.component.scss', +}) +export class PersonNetworkInstitutionsComponent implements AfterViewInit { + collaborationNetwork = input.required(); + searchTerm = input.required(); + + displayedColumns: string[] = ['id', 'name', 'collaborators']; + + dataSource = new MatTableDataSource(); + + trackBy = (index: number, item: Institution) => item.id; + + @ViewChild(MatSort) sort!: MatSort; + + constructor() { + effect(() => { + const collaborationNetwork = this.collaborationNetwork(); + if (!collaborationNetwork) { + return; + } + + this.dataSource = this.buildInstitutionsDataSource(collaborationNetwork); + this.dataSource.sortingDataAccessor = (item, property) => { + if (property === 'collaborators') { + return item.collaborators.length; + } + return (item as any)[property]; + }; + if (this.sort) { + this.dataSource.sort = this.sort; + this.setDefaultSort(); + } + }); + + effect(() => { + const searchTerm = this.searchTerm().toLowerCase(); + this.dataSource.filter = searchTerm; + }); + } + + ngAfterViewInit() { + if (this.sort) { + this.dataSource.sort = this.sort; + } + } + + private setDefaultSort(): void { + this.sort.active = 'name'; + this.sort.direction = 'asc'; + this.sort.sortChange.emit({ active: 'name', direction: 'asc' }); + } + + buildInstitutionsDataSource( + collaborationNetwork: CollaborationNetwork, + ): MatTableDataSource { + const institutionsMap: Record = {}; + + for (const node of collaborationNetwork.nodes) { + if (node.category === 'institution') { + institutionsMap[node.raw_id] = { + id: node.raw_id, + name: node.display_name, + collaborators: [], + }; + } + } + + for (const edge of collaborationNetwork.edges) { + if (edge.raw_target_id in institutionsMap) { + const institution = institutionsMap[edge.raw_target_id]; + institution.collaborators.push({ + id: edge.raw_source_id, + name: + collaborationNetwork.nodes.find( + (node) => node.raw_id === edge.raw_source_id, + )?.display_name || 'Unbekannt', + }); + } + } + + for (const institution of Object.values(institutionsMap)) { + institution.collaborators.sort((a, b) => + a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }), + ); + } + + return new MatTableDataSource(Object.values(institutionsMap)); + } +} diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html index c9227bb8..9206482a 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html @@ -16,18 +16,6 @@ {{ element.collaborators.length }} - - - - - - (); searchTerm = input.required(); - displayedColumns: string[] = ['id', 'title', 'contributors', 'actions']; + displayedColumns: string[] = ['id', 'title', 'contributors']; dataSource = new MatTableDataSource(); @@ -134,6 +134,10 @@ export class PersonNetworkPublicationsComponent implements AfterViewInit { } }); + Object.values(allWorks).forEach((work) => { + work.collaborators.sort((a, b) => a.name.localeCompare(b.name)); + }); + return new MatTableDataSource( Object.values(allWorks).filter((work) => work.collaborators.length > 0), ); diff --git a/webapp/src/app/modules/person-network/person-network.component.html b/webapp/src/app/modules/person-network/person-network.component.html index 6ed2bd00..6883dce7 100644 --- a/webapp/src/app/modules/person-network/person-network.component.html +++ b/webapp/src/app/modules/person-network/person-network.component.html @@ -27,6 +27,9 @@ Publikationen + + Institutionen +
- {{ - this.displayedTable() === "collaborators" - ? "Suche Kollaborierende nach Name oder ID" - : "Suche Publikationen nach Titel oder ID" - }} + {{ this.searchTermLabel() }} - search + search + @@ -61,6 +63,11 @@ [collaborationNetwork]="collaborationNetwork" [searchTerm]="searchTerm()" /> + } @else if (this.displayedTable() === "institutions") { + }
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 5dc7902b..e91df9fb 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -36,6 +36,7 @@ import { MatExpansionModule } from '@angular/material/expansion'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { PersonNetworkFilterDialogComponent } from '../person-network-filter-dialog/person-network-filter-dialog.component'; import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; +import { PersonNetworkInstitutionsComponent } from '../person-network-institutions/person-network-institutions.component'; @Component({ selector: 'app-person-network', @@ -62,6 +63,7 @@ import { PersonNetworkInfoCardComponent } from '../person-network-info-card/pers MatExpansionModule, MatDialogModule, PersonNetworkInfoCardComponent, + PersonNetworkInstitutionsComponent, ], templateUrl: './person-network.component.html', styleUrl: './person-network.component.scss', @@ -88,18 +90,32 @@ export class PersonNetworkComponent implements OnInit { publications = signal(0); connections = signal(0); + searchTermLabel = computed(() => { + const displayedTable = this.displayedTable(); + switch (displayedTable) { + case 'collaborators': + return 'Suche Kollaborierende nach Name oder ID'; + case 'publications': + return 'Suche Publikationen nach Titel oder ID'; + case 'institutions': + return 'Suche Institutionen nach Name oder ID'; + default: + return 'Suchbegriff'; + } + }); + private readonly categoryTableMap: Record = { author: 'collaborators', collaborator: 'collaborators', work: 'publications', + institution: 'institutions', }; latestNodeId = signal(null); handleNodeClick = ({ id, name, category }: NodeClickEvent): void => { if (this.latestNodeId() === id) { - this.latestNodeId.set(null); - this.filterForm.patchValue({ searchTerm: '' }); + this.clearSearch(); return; } @@ -111,6 +127,11 @@ export class PersonNetworkComponent implements OnInit { }); }; + clearSearch() { + this.latestNodeId.set(null); + this.filterForm.patchValue({ searchTerm: '' }); + } + readonly summaryCards = computed(() => [ { icon: 'person', @@ -175,7 +196,6 @@ export class PersonNetworkComponent implements OnInit { }); dialogRef.afterClosed().subscribe((result) => { - console.log('Dialog result:', result); if (result) { this.filterForm.setValue({ searchTerm: this.filterForm.get('searchTerm')?.value || '', From 44bd8c6ce514100367cf43e833f30c6225c10011 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 5 Jun 2026 17:22:19 +0200 Subject: [PATCH 06/33] added persons filtering --- .../person-list/person-list.component.html | 6 +- .../person-list/person-list.component.ts | 161 ++++++++++-------- 2 files changed, 93 insertions(+), 74 deletions(-) diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 1ae258b0..60f62a13 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -9,7 +9,11 @@

- + + @for (opt of institutionOptions; track opt.value) { + {{ opt.label }} + } +
{{ resultRange() }}
diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index ccca7dba..40bea7e3 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -1,4 +1,9 @@ -import { Component, inject, DestroyRef, computed, signal } from '@angular/core'; +import { + Component, + inject, + DestroyRef, + computed, +} from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterLink, ActivatedRoute, Router } from '@angular/router'; import { toObservable, toSignal } from '@angular/core/rxjs-interop'; @@ -7,6 +12,8 @@ import { MatIconModule } from '@angular/material/icon'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { Params } from '@angular/router'; import { Author, AuthorsListResponse, @@ -16,8 +23,26 @@ import { import { SharedStateService } from '../../shared/services/shared-state.service'; import { PaginationService } from '../../shared/services/pagination.service'; import { createLoadError } from '../../shared/utils/errorHandler'; -import { distinctUntilChanged, switchMap, tap, finalize, map } from 'rxjs'; -import { AuthorAffiliationsInner } from '../../api'; +import { distinctUntilChanged, switchMap, tap, finalize, map, filter } from 'rxjs'; +import { encodeFilters, PersonFilters, decodeFilters } from '../../shared/utils/filters'; +import { PersonSearchRequest } from '../../api'; +export interface InstitutionOption { + label: string; + value: string; +} + +export const INSTITUTION_OPTIONS: InstitutionOption[] = [ + { + label: 'Universität Duisburg-Essen', + value: 'University of Duisburg-Essen', + }, + { label: 'Ruhr-Universität Bochum', value: 'Ruhr University Bochum' }, + { label: 'TU Dortmund', value: 'TU Dortmund University' }, + { label: 'Universität Münster', value: 'University of Münster' }, + { label: 'RWTH Aachen', value: 'RWTH Aachen University' }, +]; + +export const DEFAULT_INSTITUTION = INSTITUTION_OPTIONS[0]; @Component({ selector: 'app-person-list', @@ -27,13 +52,14 @@ import { AuthorAffiliationsInner } from '../../api'; MatPaginatorModule, MatProgressSpinnerModule, MatSnackBarModule, + MatSelectModule, RouterLink, ], templateUrl: './person-list.component.html', styleUrl: './person-list.component.scss', standalone: true, }) -export class PersonListComponent { +export class PersonListComponent { private readonly personsService = inject(PersonsService); private readonly destroyRef = inject(DestroyRef); private readonly snackBar = inject(MatSnackBar); @@ -42,43 +68,38 @@ export class PersonListComponent { public readonly state = inject(SharedStateService); public readonly paginationService = inject(PaginationService); + //expose to template + readonly institutionOptions = INSTITUTION_OPTIONS; + private readonly defaultIncludes = - 'display_name,works_count,cited_by_count,topics,orcid,affiliations'; - private readonly defaultInstitutionName = 'University of Duisburg-Essen'; + 'display_name,works_count,cited_by_count,topics,orcid,last_known_institutions'; private readonly queryParams = toSignal( this.route.queryParams.pipe( map((params) => ({ - search: params['search'] as string | null, + name: params['search'] as string | null, + filters: decodeFilters(params['filters'] as string | null), page: Number(params['page'] ?? 0), size: Number(params['size'] ?? this.paginationService.options[2]), })), ), { initialValue: { - search: null, + name: null, + filters: { institution: DEFAULT_INSTITUTION.value } as PersonFilters, page: 0, size: this.paginationService.options[2], }, }, ); - - readonly searchValue = computed( - () => this.queryParams()['search'] ?? null, - ); - readonly pageIndex = computed(() => - Number(this.queryParams()['page'] ?? 0), - ); - readonly pageSize = computed( - () => - Number(this.queryParams()['size'] ?? this.paginationService.options[2]), // default 10 - ); + readonly activeFilters = computed(() => this.queryParams().filters); + readonly searchValue = computed(() => this.queryParams().name); + readonly pageIndex = computed(() => this.queryParams().page); + readonly pageSize = computed(() => this.queryParams().size); loading = false; - readonly persons = computed( - () => this.state.persons() ?? [], - ); + readonly persons = computed(() => this.state.persons()); readonly total = computed( () => this.state.persons().meta?.count ?? this.persons().results?.length, @@ -96,50 +117,35 @@ export class PersonListComponent { constructor() { toObservable(this.queryParams) .pipe( - map(() => ({ - search: this.searchValue(), - page: this.pageIndex(), - pageSize: this.pageSize(), - })), - distinctUntilChanged( - (a, b) => - a.search === b.search && - a.page === b.page && - a.pageSize === b.pageSize, - ), - tap(({ search }) => { + distinctUntilChanged( + (a, b) => + a.name === b.name && + a.page === b.page && + a.size === b.size && + JSON.stringify(a.filters) === JSON.stringify(b.filters), + ), + tap(() => { this.state.hasSearched.set(false); this.loading = true; - if (!search) this.state.hasSearched.set(false); }), - switchMap(({ search, page, pageSize }) => - search - ? this.personsService - .searchPersonsByName( - search, - this.defaultIncludes, - pageSize, - page, - ) - .pipe( - tap((result) => { - this.state.persons.set(this.sortByRanking(result)); - this.state.hasSearched.set(true); - }), - ) - : this.personsService - .searchPersonsByInstitution( - this.defaultInstitutionName, - this.defaultIncludes, - pageSize, - page, - ) - .pipe( - tap((result) => { - this.state.persons.set(this.sortByRanking(result)); - }), - ), - ), + switchMap(({ name, filters, page, size }) => { + const pageOffset = page * size + const body: PersonSearchRequest = { + name: name ?? undefined, + filters, + limit: size, + page_offset: pageOffset, + include: this.defaultIncludes, + }; + return this.personsService + .searchPersonsWithFilters(body) + .pipe( + tap((result) => { + this.state.persons.set(this.sortByRanking(result)); + this.state.hasSearched.set(!!name); + }), + ); + }), finalize(() => (this.loading = false)), takeUntilDestroyed(this.destroyRef), ) @@ -156,20 +162,30 @@ export class PersonListComponent { }); } - onPage(event: PageEvent): void { + navigateRouter(params: Params): void { this.router.navigate([], { relativeTo: this.route, - queryParams: { - page: event.pageIndex, - size: event.pageSize, - }, - queryParamsHandling: 'merge', // preserve search param + queryParams: params, + queryParamsHandling: 'merge', + }); + } + + onPage(event: PageEvent): void { + this.navigateRouter({ page: event.pageIndex, size: event.pageSize }); + } + + //encode filters + onFilterChange(patch: Partial): void { + const updated = { ...this.activeFilters(), ...patch }; + this.navigateRouter({ + filters: encodeFilters(updated), + page: 0 }); } institution(person: Author): DehydratedInstitution | null { - if (!person.affiliations?.length) null; - return person.affiliations?.at(-1)?.institution ?? null; + if (!person.last_known_institutions?.length) return null; + return person.last_known_institutions?.at(-1) ?? null; } topics(person: Author): string[] { @@ -179,7 +195,6 @@ export class PersonListComponent { .filter(Boolean); } - // Sorting logic sortByRanking(response: AuthorsListResponse): AuthorsListResponse { if (!response.results) return response; return { @@ -205,7 +220,7 @@ export class PersonListComponent { } hasInstitution(person: Author): boolean { - return !!person.affiliations?.some((a) => a.institution); + return !!person.last_known_institutions?.some((a) => a.display_name); } hasOrcid(person: Author): boolean { From fdb0cb3daa786bb8f3806558e089a4bfabc87da7 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Sat, 6 Jun 2026 11:45:49 +0200 Subject: [PATCH 07/33] implement topics and institute filters --- service/src/main/inse/config.py | 4 + .../src/main/inse/institutions/__init__.py | 1 + service/src/main/inse/institutions/logic.py | 309 ++++++++++++++ .../main/inse/institutions/search_client.py | 95 +++++ service/src/main/inse/institutions/service.py | 108 +++++ .../src/main/inse/institutions/test_logic.py | 236 ++++++++++ .../inse/institutions/test_search_client.py | 77 ++++ service/src/main/inse/main.py | 4 + service/src/main/inse/tags.py | 4 +- service/src/main/inse/topics/__init__.py | 5 + service/src/main/inse/topics/logic.py | 257 +++++++++++ service/src/main/inse/topics/search_client.py | 99 +++++ service/src/main/inse/topics/service.py | 113 +++++ service/src/main/inse/topics/test_logic.py | 195 +++++++++ .../main/inse/topics/test_search_client.py | 75 ++++ service/src/main/inse/works/logic.py | 8 + service/src/main/inse/works/search_client.py | 67 ++- service/src/main/inse/works/service.py | 10 + .../src/main/inse/works/test_search_client.py | 157 ++++++- webapp/src/app/api/api/works.service.ts | 22 +- .../src/app/api/api/works.serviceInterface.ts | 4 +- .../person-publications.component.html | 163 ++++++- .../person-publications.component.scss | 195 ++++++++- .../person-publications.component.ts | 403 +++++++++++++++++- 24 files changed, 2557 insertions(+), 54 deletions(-) create mode 100644 service/src/main/inse/institutions/__init__.py create mode 100644 service/src/main/inse/institutions/logic.py create mode 100644 service/src/main/inse/institutions/search_client.py create mode 100644 service/src/main/inse/institutions/service.py create mode 100644 service/src/main/inse/institutions/test_logic.py create mode 100644 service/src/main/inse/institutions/test_search_client.py create mode 100644 service/src/main/inse/topics/__init__.py create mode 100644 service/src/main/inse/topics/logic.py create mode 100644 service/src/main/inse/topics/search_client.py create mode 100644 service/src/main/inse/topics/service.py create mode 100644 service/src/main/inse/topics/test_logic.py create mode 100644 service/src/main/inse/topics/test_search_client.py diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index ad171904..4d83fe03 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -34,6 +34,10 @@ class Settings(BaseSettings): "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==" ) openalex_works_search_timeout_seconds: float = 30.0 + # OpenAlex public API config + openalex_api_base_url: str = "https://api.openalex.org" + openalex_api_key: Optional[str] = None + openalex_api_timeout_seconds: float = 30.0 # LLM config llm_api_url: Optional[str] = None diff --git a/service/src/main/inse/institutions/__init__.py b/service/src/main/inse/institutions/__init__.py new file mode 100644 index 00000000..9be5f207 --- /dev/null +++ b/service/src/main/inse/institutions/__init__.py @@ -0,0 +1 @@ +"""Institution lookup module.""" diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py new file mode 100644 index 00000000..34504553 --- /dev/null +++ b/service/src/main/inse/institutions/logic.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for OpenAlex institutions. +""" +import logging +from copy import deepcopy +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_400_BAD_REQUEST +from starlette.status import HTTP_502_BAD_GATEWAY + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.autocomplete_response_meta import AutocompleteResponseMeta +from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner +from inse.models.institutions_list_response import InstitutionsListResponse +from .search_client import OpenAlexInstitutionsClient + +logger = logging.getLogger(__name__) + +_VALID_INSTITUTION_TYPES = { + "education", + "healthcare", + "company", + "archive", + "nonprofit", + "government", + "facility", + "other", +} + + +async def list_institutions( + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + client: OpenAlexInstitutionsClient | None = None, +) -> InstitutionsListResponse: + if sample is not None and (sort or page not in (None, 1)): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="sample cannot be combined with sort or page.", + ) + + openalex_client = client or OpenAlexInstitutionsClient() + + try: + data = await openalex_client.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code + detail = "OpenAlex institutions request failed." + try: + error_body = exc.response.json() + detail = error_body.get("message") or error_body.get("error") or detail + except ValueError: + if exc.response.text: + detail = exc.response.text + raise HTTPException(status_code=status_code, detail=detail) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex institutions request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex institutions request failed.", + ) from exc + + try: + normalized_data = _normalize_institutions_response(data) + return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse() + except ValidationError as exc: + logger.exception("OpenAlex institutions response could not be parsed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex institutions response could not be parsed.", + ) from exc + + +async def autocomplete_institutions( + *, + query: str, + country_code: str | None = None, + institution_type: str | None = None, + limit: int = 10, + client: OpenAlexInstitutionsClient | None = None, +) -> AutocompleteResponse: + filters = [] + if country_code: + filters.append(f"country_code:{country_code}") + if institution_type: + filters.append(f"type:{institution_type}") + + response = await list_institutions( + search=query, + filter=",".join(filters) if filters else None, + sort="works_count:desc", + per_page=limit, + page=1, + select=( + "id,ror,display_name,country_code,type,works_count," + "cited_by_count,geo" + ), + client=client, + ) + + results = [] + for institution in response.results or []: + if not institution.id or not institution.display_name: + continue + + hint_parts = [] + if institution.geo: + if institution.geo.city: + hint_parts.append(institution.geo.city) + if institution.geo.country: + hint_parts.append(institution.geo.country) + elif institution.country_code: + hint_parts.append(institution.country_code) + if institution.type: + hint_parts.append(institution.type) + + results.append( + AutocompleteResponseResultsInner( + id=institution.id, + display_name=institution.display_name, + hint=" · ".join(hint_parts) if hint_parts else None, + cited_by_count=institution.cited_by_count, + works_count=institution.works_count, + entity_type="institution", + external_id=institution.ror, + ) + ) + + return AutocompleteResponse( + meta=AutocompleteResponseMeta( + count=response.meta.count if response.meta else len(results), + db_response_time_ms=( + response.meta.db_response_time_ms if response.meta else None + ), + ), + results=results, + ) + + +def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]: + normalized = deepcopy(data) + + meta = normalized.get("meta") + if isinstance(meta, dict): + for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + meta[field] = _int_or_none(meta.get(field)) + meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) + meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) + + for institution in normalized.get("results") or []: + if not isinstance(institution, dict): + continue + + for field in [ + "id", + "ror", + "display_name", + "country_code", + "homepage_url", + "image_url", + "image_thumbnail_url", + "works_api_url", + ]: + institution[field] = _str_or_none(institution.get(field)) + + institution_type = institution.get("type") + if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES: + institution["type"] = None + else: + institution["type"] = _str_or_none(institution_type) + + institution["display_name_acronyms"] = _str_list_or_none( + institution.get("display_name_acronyms") + ) + institution["display_name_alternatives"] = _str_list_or_none( + institution.get("display_name_alternatives") + ) + institution["lineage"] = _str_list_or_none(institution.get("lineage")) + institution["works_count"] = _int_or_none(institution.get("works_count")) + institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count")) + institution["created_date"] = _date_str_or_none(institution.get("created_date")) + institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date")) + + summary_stats = institution.get("summary_stats") + if isinstance(summary_stats, dict): + summary_stats["2yr_mean_citedness"] = _number_or_none( + summary_stats.get("2yr_mean_citedness") + ) + summary_stats["h_index"] = _int_or_none(summary_stats.get("h_index")) + summary_stats["i10_index"] = _int_or_none(summary_stats.get("i10_index")) + + geo = institution.get("geo") + if isinstance(geo, dict): + for field in [ + "city", + "geonames_city_id", + "region", + "country_code", + "country", + ]: + geo[field] = _str_or_none(geo.get(field)) + geo["latitude"] = _number_or_none(geo.get("latitude")) + geo["longitude"] = _number_or_none(geo.get("longitude")) + + ids = institution.get("ids") + if isinstance(ids, dict): + for field in ["openalex", "ror", "grid", "wikipedia", "wikidata"]: + ids[field] = _str_or_none(ids.get(field)) + ids["mag"] = _int_or_none(ids.get("mag")) + + for counts_by_year in institution.get("counts_by_year") or []: + if not isinstance(counts_by_year, dict): + continue + for field in ["year", "works_count", "cited_by_count"]: + counts_by_year[field] = _int_or_none(counts_by_year.get(field)) + + for group in normalized.get("group_by") or []: + if not isinstance(group, dict): + continue + + group["key"] = _str_or_none(group.get("key")) + group["key_display_name"] = _str_or_none(group.get("key_display_name")) + group["count"] = _int_or_none(group.get("count")) + + return normalized + + +def _str_or_none(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, bool): + return str(value).lower() + return str(value) + + +def _str_list_or_none(value: Any) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list): + return None + return [_str_or_none(item) for item in value if item is not None] + + +def _int_or_none(value: Any) -> int | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(float(value)) + except ValueError: + return None + return None + + +def _number_or_none(value: Any) -> int | float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return None + return int(number) if number.is_integer() else number + return None + + +def _date_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + return text[:10] + + +def _datetime_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + if len(text) == 10: + return f"{text}T00:00:00Z" + return text diff --git a/service/src/main/inse/institutions/search_client.py b/service/src/main/inse/institutions/search_client.py new file mode 100644 index 00000000..3db5e1dd --- /dev/null +++ b/service/src/main/inse/institutions/search_client.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +HTTP client for OpenAlex institutions. +""" +from typing import Any + +import httpx + +from .. import config + + +class OpenAlexInstitutionsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.openalex_api_key + self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds + self.transport = transport + + def list_institutions_params( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {"per_page": per_page} + + if search: + params["search"] = search + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + if group_by: + params["group_by"] = group_by + if cursor: + params["cursor"] = cursor + elif page is not None: + params["page"] = page + if sample is not None: + params["sample"] = sample + if select: + params["select"] = select + if self.api_key: + params["api_key"] = self.api_key + + return params + + async def list_institutions( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + "/institutions", + params=self.list_institutions_params( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ), + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py new file mode 100644 index 00000000..69d6911e --- /dev/null +++ b/service/src/main/inse/institutions/service.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for OpenAlex institutions. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.institutions_list_response import InstitutionsListResponse +from inse.tags import Tags +from . import logic + + +router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS]) + + +@router.get( + "/autocomplete", + operation_id="autocompleteInstitutions", + response_model=AutocompleteResponse, + response_model_exclude_none=True, + summary="Returns institution options for autocomplete inputs.", +) +async def autocomplete_institutions( + query: Annotated[ + str, + Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1), + ], + country_code: Annotated[ + str | None, + Query(alias="countryCode", description="Optional ISO country code filter."), + ] = None, + institution_type: Annotated[ + str | None, + Query(alias="type", description="Optional institution type filter."), + ] = None, + limit: Annotated[ + int, + Query(description="Maximum number of autocomplete options.", ge=1, le=25), + ] = 10, +): + return await logic.autocomplete_institutions( + query=query, + country_code=country_code, + institution_type=institution_type, + limit=limit, + ) + + +@router.get( + "", + operation_id="listInstitutions", + response_model=InstitutionsListResponse, + response_model_exclude_none=True, + summary="Returns a list of OpenAlex institutions.", +) +async def list_institutions( + search: Annotated[ + str | None, + Query(description="Full-text search, for example 'Duisburg Essen'."), + ] = None, + filter: Annotated[ + str | None, + Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."), + ] = None, + sort: Annotated[ + str | None, + Query(description="Sort field, for example 'works_count:desc'."), + ] = "works_count:desc", + group_by: Annotated[ + str | None, + Query(description="OpenAlex group_by field, for example 'country_code'."), + ] = None, + per_page: Annotated[ + int, + Query(description="Results per page.", ge=1, le=100), + ] = 25, + page: Annotated[ + int | None, + Query(description="Page number. Use cursor for deep pagination.", ge=1), + ] = 1, + cursor: Annotated[ + str | None, + Query(description="Cursor pagination token. Use '*' to start."), + ] = None, + sample: Annotated[ + int | None, + Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000), + ] = None, + select: Annotated[ + str | None, + Query(description="Comma-separated fields to return."), + ] = None, +): + return await logic.list_institutions( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py new file mode 100644 index 00000000..e079ff8e --- /dev/null +++ b/service/src/main/inse/institutions/test_logic.py @@ -0,0 +1,236 @@ +import httpx +import pytest +from fastapi import HTTPException + +from inse.institutions import logic +from inse.institutions.search_client import OpenAlexInstitutionsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_list_institutions_maps_openalex_response_to_model(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + "homepage_url": "https://www.uni-due.de", + "image_url": "https://example.org/image.jpg", + "image_thumbnail_url": "https://example.org/thumb.jpg", + "display_name_acronyms": ["UDE"], + "display_name_alternatives": ["Universitaet Duisburg-Essen"], + "works_count": 123, + "cited_by_count": 456, + "summary_stats": { + "2yr_mean_citedness": 1.5, + "h_index": 42, + "i10_index": 99, + }, + "geo": { + "city": "Duisburg", + "geonames_city_id": "2934691", + "region": "North Rhine-Westphalia", + "country_code": "DE", + "country": "Germany", + "latitude": 51.4344, + "longitude": 6.7623, + }, + "lineage": ["https://openalex.org/I123"], + "ids": { + "openalex": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "mag": 123, + "grid": "grid.12345.6", + "wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen", + "wikidata": "https://www.wikidata.org/wiki/Q317070", + }, + "counts_by_year": [ + { + "year": 2024, + "works_count": 12, + "cited_by_count": 34, + } + ], + "works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123", + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", + } + ], + "group_by": [ + { + "key": "DE", + "key_display_name": "Germany", + "count": 1, + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(search="Duisburg Essen", client=client) + + assert result.meta.count == 1 + institution = result.results[0] + assert institution.display_name == "University of Duisburg-Essen" + assert institution.summary_stats.h_index == 42 + assert institution.geo.country == "Germany" + assert institution.ids.mag == 123 + assert institution.counts_by_year[0].year == 2024 + assert result.group_by[0].key_display_name == "Germany" + + +@pytest.mark.anyio +async def test_list_institutions_rejects_sample_with_sort(): + with pytest.raises(HTTPException) as exc_info: + await logic.list_institutions(sample=10, sort="works_count:desc") + + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_list_institutions_accepts_practical_openalex_type_variants(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": 123, + "ror": 456, + "display_name": "Example Institute", + "country_code": 789, + "type": "unknown-openalex-type", + "display_name_acronyms": ["EI", 123], + "display_name_alternatives": "not-a-list", + "works_count": "12", + "cited_by_count": "34.0", + "summary_stats": { + "2yr_mean_citedness": "1.25", + "h_index": "10.0", + "i10_index": True, + }, + "geo": { + "city": 123, + "geonames_city_id": 12345, + "latitude": "51.4", + "longitude": "6", + }, + "ids": {"openalex": 123, "mag": "123"}, + "counts_by_year": [ + { + "year": "2024", + "works_count": "12.0", + "cited_by_count": False, + } + ], + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + } + ], + "group_by": [{"key": True, "count": 1}], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(client=client) + + assert result.results[0].id == "123" + assert result.results[0].ror == "456" + assert result.results[0].country_code == "789" + assert result.results[0].type is None + assert result.results[0].display_name_acronyms == ["EI", "123"] + assert result.results[0].display_name_alternatives is None + assert result.results[0].works_count == 12 + assert result.results[0].cited_by_count == 34 + assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25 + assert result.results[0].summary_stats.h_index == 10 + assert result.results[0].summary_stats.i10_index is None + assert result.results[0].geo.city == "123" + assert result.results[0].geo.geonames_city_id == "12345" + assert result.results[0].geo.latitude == 51.4 + assert result.results[0].geo.longitude == 6 + assert result.results[0].ids.openalex == "123" + assert result.results[0].ids.mag == 123 + assert result.results[0].counts_by_year[0].year == 2024 + assert result.results[0].counts_by_year[0].works_count == 12 + assert result.results[0].counts_by_year[0].cited_by_count is None + assert result.group_by[0].key == "true" + + +@pytest.mark.anyio +async def test_autocomplete_institutions_returns_frontend_options(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["search"] == "Duisburg Essen" + assert request.url.params["filter"] == "country_code:DE,type:education" + assert request.url.params["sort"] == "works_count:desc" + assert request.url.params["per_page"] == "5" + assert request.url.params["select"] == ( + "id,ror,display_name,country_code,type,works_count," + "cited_by_count,geo" + ) + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/I123", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + "works_count": 123, + "cited_by_count": 456, + "geo": { + "city": "Duisburg", + "country": "Germany", + }, + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.autocomplete_institutions( + query="Duisburg Essen", + country_code="DE", + institution_type="education", + limit=5, + client=client, + ) + + assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + assert len(result.results) == 1 + option = result.results[0] + assert option.id == "https://openalex.org/I123" + assert option.display_name == "University of Duisburg-Essen" + assert option.hint == "Duisburg · Germany · education" + assert option.works_count == 123 + assert option.cited_by_count == 456 + assert option.entity_type == "institution" + assert option.external_id == "https://ror.org/04mz5ra38" diff --git a/service/src/main/inse/institutions/test_search_client.py b/service/src/main/inse/institutions/test_search_client.py new file mode 100644 index 00000000..0051b8cf --- /dev/null +++ b/service/src/main/inse/institutions/test_search_client.py @@ -0,0 +1,77 @@ +import httpx +import pytest + +from inse.institutions.search_client import OpenAlexInstitutionsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_list_institutions_params_include_openalex_query_parameters(): + client = OpenAlexInstitutionsClient(api_key="test-key") + + params = client.list_institutions_params( + search="Duisburg Essen", + filter="country_code:DE,type:education", + sort="works_count:desc", + group_by="country_code", + per_page=10, + page=2, + select="id,display_name", + ) + + assert params == { + "search": "Duisburg Essen", + "filter": "country_code:DE,type:education", + "sort": "works_count:desc", + "group_by": "country_code", + "per_page": 10, + "page": 2, + "select": "id,display_name", + "api_key": "test-key", + } + + +def test_list_institutions_params_prefers_cursor_over_page(): + client = OpenAlexInstitutionsClient(api_key="test-key") + + params = client.list_institutions_params(cursor="*", page=3) + + assert params["cursor"] == "*" + assert "page" not in params + + +@pytest.mark.anyio +async def test_list_institutions_calls_openalex_institutions_endpoint(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.method == "GET" + assert request.url.path == "/institutions" + assert request.url.params["search"] == "Duisburg Essen" + assert request.url.params["api_key"] == "test-key" + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I123", + "display_name": "University of Duisburg-Essen", + "country_code": "DE", + "type": "education", + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + base_url="https://api.openalex.org", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await client.list_institutions(search="Duisburg Essen") + + assert result["meta"]["count"] == 1 + assert result["results"][0]["display_name"] == "University of Duisburg-Essen" diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 96f6e5a8..cb7fc9b1 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -11,6 +11,8 @@ from fastapi import FastAPI from fastapi.responses import RedirectResponse from fastapi.middleware.cors import CORSMiddleware from inse.collaboration_network.router import router as collaboration_network_router +from inse.institutions.service import router as institutions_service_router +from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router from inse.search.service import router as search_router @@ -32,6 +34,8 @@ app = FastAPI( servers=settings.servers, ) app.include_router(collaboration_network_router) +app.include_router(institutions_service_router) +app.include_router(topics_service_router) app.include_router(works_service_router) app.include_router(search_router) app.include_router(service_router) diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 219152ad..21c6b03c 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -4,4 +4,6 @@ from enum import Enum class Tags(Enum): PERSON = "Person" PERSON_NETWORK = "Person Network" - WORKS = "Works" \ No newline at end of file + INSTITUTIONS = "Institutions" + TOPICS = "Topics" + WORKS = "Works" diff --git a/service/src/main/inse/topics/__init__.py b/service/src/main/inse/topics/__init__.py new file mode 100644 index 00000000..6909a227 --- /dev/null +++ b/service/src/main/inse/topics/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +OpenAlex topics module. +""" diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py new file mode 100644 index 00000000..5d4bdef7 --- /dev/null +++ b/service/src/main/inse/topics/logic.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for OpenAlex topics. +""" +import logging +from copy import deepcopy +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_400_BAD_REQUEST +from starlette.status import HTTP_502_BAD_GATEWAY + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.autocomplete_response_meta import AutocompleteResponseMeta +from inse.models.autocomplete_response_results_inner import ( + AutocompleteResponseResultsInner, +) +from inse.models.topics_list_response import TopicsListResponse +from .search_client import OpenAlexTopicsClient + +logger = logging.getLogger(__name__) + + +async def list_topics( + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + client: OpenAlexTopicsClient | None = None, +) -> TopicsListResponse: + if sample is not None and (sort or page not in (None, 1)): + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail="sample cannot be combined with sort or page.", + ) + + openalex_client = client or OpenAlexTopicsClient() + + try: + data = await openalex_client.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code + detail = "OpenAlex topics request failed." + try: + error_body = exc.response.json() + detail = error_body.get("message") or error_body.get("error") or detail + except ValueError: + if exc.response.text: + detail = exc.response.text + raise HTTPException(status_code=status_code, detail=detail) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex topics request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex topics request failed.", + ) from exc + + try: + normalized_data = _normalize_topics_response(data) + return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() + except ValidationError as exc: + logger.exception("OpenAlex topics response could not be parsed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex topics response could not be parsed.", + ) from exc + + +async def autocomplete_topics( + *, + query: str, + domain_id: str | None = None, + field_id: str | None = None, + subfield_id: str | None = None, + limit: int = 10, + client: OpenAlexTopicsClient | None = None, +) -> AutocompleteResponse: + filters = [] + if domain_id: + filters.append(f"domain.id:{domain_id}") + if field_id: + filters.append(f"field.id:{field_id}") + if subfield_id: + filters.append(f"subfield.id:{subfield_id}") + + response = await list_topics( + search=query, + filter=",".join(filters) if filters else None, + sort="works_count:desc", + per_page=limit, + page=1, + select=( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ), + client=client, + ) + + results = [] + for topic in response.results or []: + if not topic.id or not topic.display_name: + continue + + hint_parts = [] + if topic.var_field and topic.var_field.display_name: + hint_parts.append(topic.var_field.display_name) + if topic.subfield and topic.subfield.display_name: + hint_parts.append(topic.subfield.display_name) + if topic.domain and topic.domain.display_name: + hint_parts.append(topic.domain.display_name) + + results.append( + AutocompleteResponseResultsInner( + id=topic.id, + display_name=topic.display_name, + hint=" · ".join(hint_parts) if hint_parts else topic.description, + cited_by_count=topic.cited_by_count, + works_count=topic.works_count, + entity_type="topic", + external_id=topic.ids.openalex if topic.ids else None, + ) + ) + + return AutocompleteResponse( + meta=AutocompleteResponseMeta( + count=response.meta.count if response.meta else len(results), + db_response_time_ms=( + response.meta.db_response_time_ms if response.meta else None + ), + ), + results=results, + ) + + +def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]: + normalized = deepcopy(data) + + meta = normalized.get("meta") + if isinstance(meta, dict): + for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]: + meta[field] = _int_or_none(meta.get(field)) + meta["next_cursor"] = _str_or_none(meta.get("next_cursor")) + meta["cost_usd"] = _number_or_none(meta.get("cost_usd")) + + for topic in normalized.get("results") or []: + if not isinstance(topic, dict): + continue + + for field in ["id", "display_name", "description", "works_api_url"]: + topic[field] = _str_or_none(topic.get(field)) + topic["keywords"] = _str_list_or_none(topic.get("keywords")) + topic["works_count"] = _int_or_none(topic.get("works_count")) + topic["cited_by_count"] = _int_or_none(topic.get("cited_by_count")) + topic["created_date"] = _date_str_or_none(topic.get("created_date")) + topic["updated_date"] = _datetime_str_or_none(topic.get("updated_date")) + + for relation_field in ["subfield", "field", "domain"]: + relation = topic.get(relation_field) + if not isinstance(relation, dict): + continue + relation["id"] = _str_or_none(relation.get("id")) + relation["display_name"] = _str_or_none(relation.get("display_name")) + + ids = topic.get("ids") + if isinstance(ids, dict): + for field in ["openalex", "wikipedia"]: + ids[field] = _str_or_none(ids.get(field)) + + for group in normalized.get("group_by") or []: + if not isinstance(group, dict): + continue + + group["key"] = _str_or_none(group.get("key")) + group["key_display_name"] = _str_or_none(group.get("key_display_name")) + group["count"] = _int_or_none(group.get("count")) + + return normalized + + +def _str_or_none(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, bool): + return str(value).lower() + return str(value) + + +def _str_list_or_none(value: Any) -> list[str] | None: + if value is None: + return None + if not isinstance(value, list): + return None + return [_str_or_none(item) for item in value if item is not None] + + +def _int_or_none(value: Any) -> int | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str): + try: + return int(float(value)) + except ValueError: + return None + return None + + +def _number_or_none(value: Any) -> int | float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return None + return int(number) if number.is_integer() else number + return None + + +def _date_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + return text[:10] + + +def _datetime_str_or_none(value: Any) -> str | None: + text = _str_or_none(value) + if not text: + return None + if len(text) == 10: + return f"{text}T00:00:00Z" + return text diff --git a/service/src/main/inse/topics/search_client.py b/service/src/main/inse/topics/search_client.py new file mode 100644 index 00000000..7c70afa0 --- /dev/null +++ b/service/src/main/inse/topics/search_client.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +HTTP client for OpenAlex topics. +""" +from typing import Any + +import httpx + +from .. import config + + +class OpenAlexTopicsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.openalex_api_key + self.timeout = ( + timeout + if timeout is not None + else config.settings.openalex_api_timeout_seconds + ) + self.transport = transport + + def list_topics_params( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {"per_page": per_page} + + if search: + params["search"] = search + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + if group_by: + params["group_by"] = group_by + if cursor: + params["cursor"] = cursor + elif page is not None: + params["page"] = page + if sample is not None: + params["sample"] = sample + if select: + params["select"] = select + if self.api_key: + params["api_key"] = self.api_key + + return params + + async def list_topics( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + "/topics", + params=self.list_topics_params( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ), + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/topics/service.py b/service/src/main/inse/topics/service.py new file mode 100644 index 00000000..70252254 --- /dev/null +++ b/service/src/main/inse/topics/service.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for OpenAlex topics. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from inse.models.autocomplete_response import AutocompleteResponse +from inse.models.topics_list_response import TopicsListResponse +from inse.tags import Tags +from . import logic + + +router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS]) + + +@router.get( + "/autocomplete", + operation_id="autocompleteTopics", + response_model=AutocompleteResponse, + response_model_exclude_none=True, + summary="Returns topic options for autocomplete inputs.", +) +async def autocomplete_topics( + query: Annotated[ + str, + Query(description="Topic search text, for example 'machine learning'.", min_length=1), + ], + domain_id: Annotated[ + str | None, + Query(alias="domainId", description="Optional OpenAlex domain id filter."), + ] = None, + field_id: Annotated[ + str | None, + Query(alias="fieldId", description="Optional OpenAlex field id filter."), + ] = None, + subfield_id: Annotated[ + str | None, + Query(alias="subfieldId", description="Optional OpenAlex subfield id filter."), + ] = None, + limit: Annotated[ + int, + Query(description="Maximum number of autocomplete options.", ge=1, le=25), + ] = 10, +): + return await logic.autocomplete_topics( + query=query, + domain_id=domain_id, + field_id=field_id, + subfield_id=subfield_id, + limit=limit, + ) + + +@router.get( + "", + operation_id="listTopics", + response_model=TopicsListResponse, + response_model_exclude_none=True, + summary="Returns a list of OpenAlex topics.", +) +async def list_topics( + search: Annotated[ + str | None, + Query(description="Full-text search, for example 'machine learning'."), + ] = None, + filter: Annotated[ + str | None, + Query(description="OpenAlex filter, for example 'domain.id:1,works_count:>1000'."), + ] = None, + sort: Annotated[ + str | None, + Query(description="Sort field, for example 'works_count:desc'."), + ] = "works_count:desc", + group_by: Annotated[ + str | None, + Query(description="OpenAlex group_by field, for example 'domain.id'."), + ] = None, + per_page: Annotated[ + int, + Query(description="Results per page.", ge=1, le=100), + ] = 25, + page: Annotated[ + int | None, + Query(description="Page number. Use cursor for deep pagination.", ge=1), + ] = 1, + cursor: Annotated[ + str | None, + Query(description="Cursor pagination token. Use '*' to start."), + ] = None, + sample: Annotated[ + int | None, + Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000), + ] = None, + select: Annotated[ + str | None, + Query(description="Comma-separated fields to return."), + ] = None, +): + return await logic.list_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py new file mode 100644 index 00000000..e6f9a3a4 --- /dev/null +++ b/service/src/main/inse/topics/test_logic.py @@ -0,0 +1,195 @@ +import httpx +import pytest +from fastapi import HTTPException + +from inse.topics import logic +from inse.topics.search_client import OpenAlexTopicsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_list_topics_maps_openalex_response_to_model(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "keywords": ["machine learning", "classification"], + "subfield": { + "id": "https://openalex.org/subfields/1702", + "display_name": "Artificial Intelligence", + }, + "field": { + "id": "https://openalex.org/fields/17", + "display_name": "Computer Science", + }, + "domain": { + "id": "https://openalex.org/domains/4", + "display_name": "Physical Sciences", + }, + "works_count": 123, + "cited_by_count": 456, + "ids": { + "openalex": "https://openalex.org/T12419", + "wikipedia": "https://en.wikipedia.org/wiki/Machine_learning", + }, + "works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419", + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", + } + ], + "group_by": [ + { + "key": "https://openalex.org/domains/4", + "key_display_name": "Physical Sciences", + "count": 1, + } + ], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_topics(search="machine learning", client=client) + + assert result.meta.count == 1 + topic = result.results[0] + assert topic.display_name == "Machine learning" + assert topic.var_field.display_name == "Computer Science" + assert topic.subfield.display_name == "Artificial Intelligence" + assert topic.domain.display_name == "Physical Sciences" + assert topic.ids.openalex == "https://openalex.org/T12419" + assert result.group_by[0].key_display_name == "Physical Sciences" + + +@pytest.mark.anyio +async def test_list_topics_rejects_sample_with_sort(): + with pytest.raises(HTTPException) as exc_info: + await logic.list_topics(sample=10, sort="works_count:desc") + + assert exc_info.value.status_code == 400 + + +@pytest.mark.anyio +async def test_list_topics_accepts_practical_openalex_type_variants(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": "1", "page": "1", "per_page": "25"}, + "results": [ + { + "id": 123, + "display_name": 456, + "description": True, + "keywords": ["topic", 123], + "subfield": {"id": 1, "display_name": 2}, + "field": {"id": 3, "display_name": 4}, + "domain": {"id": 5, "display_name": 6}, + "works_count": "12.0", + "cited_by_count": False, + "ids": {"openalex": 123, "wikipedia": 456}, + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + } + ], + "group_by": [{"key": True, "count": "1"}], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_topics(client=client) + + topic = result.results[0] + assert topic.id == "123" + assert topic.display_name == "456" + assert topic.description == "true" + assert topic.keywords == ["topic", "123"] + assert topic.works_count == 12 + assert topic.cited_by_count is None + assert topic.var_field.id == "3" + assert topic.domain.display_name == "6" + assert topic.ids.wikipedia == "456" + assert topic.created_date.isoformat() == "2023-12-25" + assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00" + assert result.group_by[0].key == "true" + + +@pytest.mark.anyio +async def test_autocomplete_topics_returns_frontend_options(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["search"] == "machine learning" + assert request.url.params["filter"] == ( + "domain.id:https://openalex.org/domains/4," + "field.id:https://openalex.org/fields/17," + "subfield.id:https://openalex.org/subfields/1702" + ) + assert request.url.params["sort"] == "works_count:desc" + assert request.url.params["per_page"] == "5" + assert request.url.params["select"] == ( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ) + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "db_response_time_ms": 12}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "field": {"display_name": "Computer Science"}, + "subfield": {"display_name": "Artificial Intelligence"}, + "domain": {"display_name": "Physical Sciences"}, + "works_count": 123, + "cited_by_count": 456, + "ids": {"openalex": "https://openalex.org/T12419"}, + } + ], + }, + ) + + client = OpenAlexTopicsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.autocomplete_topics( + query="machine learning", + domain_id="https://openalex.org/domains/4", + field_id="https://openalex.org/fields/17", + subfield_id="https://openalex.org/subfields/1702", + limit=5, + client=client, + ) + + assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + assert len(result.results) == 1 + option = result.results[0] + assert option.id == "https://openalex.org/T12419" + assert option.display_name == "Machine learning" + assert option.hint == ( + "Computer Science · Artificial Intelligence · Physical Sciences" + ) + assert option.works_count == 123 + assert option.cited_by_count == 456 + assert option.entity_type == "topic" + assert option.external_id == "https://openalex.org/T12419" diff --git a/service/src/main/inse/topics/test_search_client.py b/service/src/main/inse/topics/test_search_client.py new file mode 100644 index 00000000..69c16a82 --- /dev/null +++ b/service/src/main/inse/topics/test_search_client.py @@ -0,0 +1,75 @@ +import httpx +import pytest + +from inse.topics.search_client import OpenAlexTopicsClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_list_topics_params_include_openalex_query_parameters(): + client = OpenAlexTopicsClient(api_key="test-key") + + params = client.list_topics_params( + search="machine learning", + filter="domain.id:4,works_count:>1000", + sort="works_count:desc", + group_by="domain.id", + per_page=10, + page=2, + select="id,display_name", + ) + + assert params == { + "search": "machine learning", + "filter": "domain.id:4,works_count:>1000", + "sort": "works_count:desc", + "group_by": "domain.id", + "per_page": 10, + "page": 2, + "select": "id,display_name", + "api_key": "test-key", + } + + +def test_list_topics_params_prefers_cursor_over_page(): + client = OpenAlexTopicsClient(api_key="test-key") + + params = client.list_topics_params(cursor="*", page=3) + + assert params["cursor"] == "*" + assert "page" not in params + + +@pytest.mark.anyio +async def test_list_topics_calls_openalex_topics_endpoint(): + def handler(request: httpx.Request) -> httpx.Response: + assert request.method == "GET" + assert request.url.path == "/topics" + assert request.url.params["search"] == "machine learning" + assert request.url.params["api_key"] == "test-key" + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + } + ], + }, + ) + + client = OpenAlexTopicsClient( + base_url="https://api.openalex.org", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await client.list_topics(search="machine learning") + + assert result["meta"]["count"] == 1 + assert result["results"][0]["display_name"] == "Machine learning" diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index a284a919..c4396b8e 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -33,6 +33,8 @@ async def get_author_works( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, client: OpenAlexWorksSearchClient | None = None, ) -> WorkPage: search_client = client or OpenAlexWorksSearchClient() @@ -44,6 +46,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) elements, total = _parse_full_work_search_response(data) @@ -191,6 +195,8 @@ async def _search_author_works_data( publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict: try: return await search_client.search_author_works( @@ -200,6 +206,8 @@ async def _search_author_works_data( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) except MissingApiKeyError as exc: logger.error("OpenAlex works Elasticsearch API key is not configured.") diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 8f44a776..355bfb6e 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -40,26 +40,52 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict[str, Any]: indexed_author_id = f"https://openalex.org/{author_id.strip()}" - filters = self._work_filters(publication_year, work_type, language) + filters = self._work_filters( + publication_year, + work_type, + language, + topic_id, + ) + author_filters: list[dict[str, Any]] = [ + { + "term": { + "authorships.author.id": indexed_author_id, + }, + }, + ] + must_clauses: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": author_filters, + }, + }, + }, + }, + ] + if institution_id: + must_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": institution_id, + }, + }, + }, + }) return { "from": (page - 1) * size, "size": size, "query": { "bool": { - "must": [ - { - "nested": { - "path": "authorships", - "query": { - "term": { - "authorships.author.id": indexed_author_id, - }, - }, - }, - }, - ], + "must": must_clauses, "filter": filters, }, }, @@ -74,6 +100,7 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + topic_id: list[str] | None = None, ) -> list[dict[str, Any]]: filters: list[dict[str, Any]] = [] if publication_year: @@ -82,6 +109,16 @@ class OpenAlexWorksSearchClient: filters.append({"terms": {"type": work_type}}) if language: filters.append({"terms": {"language": language}}) + if topic_id: + filters.append({ + "bool": { + "should": [ + {"terms": {"topics.id": topic_id}}, + {"terms": {"primary_topic.id": topic_id}}, + ], + "minimum_should_match": 1, + }, + }) return filters async def search_author_works( @@ -92,6 +129,8 @@ class OpenAlexWorksSearchClient: publication_year: list[int] | None = None, work_type: list[str] | None = None, language: list[str] | None = None, + institution_id: list[str] | None = None, + topic_id: list[str] | None = None, ) -> dict[str, Any]: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") @@ -111,6 +150,8 @@ class OpenAlexWorksSearchClient: publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ), ) # logging.debug(f"Response: {response.text}") diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 476f2b9a..22916d7c 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -46,6 +46,14 @@ async def get_author_works( language: Annotated[ list[str] | None, Query(description="Filter by language code. Can be repeated.") ] = None, + institution_id: Annotated[ + list[str] | None, + Query(description="Filter by OpenAlex institution id. Can be repeated."), + ] = None, + topic_id: Annotated[ + list[str] | None, + Query(description="Filter by OpenAlex topic id. Can be repeated."), + ] = None, principal: security.Principal = Depends( security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) ), @@ -57,6 +65,8 @@ async def get_author_works( publication_year=publication_year, work_type=work_type, language=language, + institution_id=institution_id, + topic_id=topic_id, ) diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 5a376f26..150880a7 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -1,3 +1,5 @@ +import json + import httpx import pytest @@ -19,7 +21,9 @@ def test_author_works_query_searches_authorship_author_id(): assert query["size"] == 25 author_query = query["query"]["bool"]["must"][0]["nested"] assert author_query["path"] == "authorships" - assert author_query["query"]["term"]["authorships.author.id"] == "https://openalex.org/A5023888391" + assert author_query["query"]["bool"]["filter"] == [ + {"term": {"authorships.author.id": "https://openalex.org/A5023888391"}}, + ] assert query["query"]["bool"]["filter"] == [] @@ -33,13 +37,164 @@ def test_author_works_query_adds_publication_filters(): publication_year=[2023, 2024], work_type=["article", "book-chapter"], language=["en", "de"], + institution_id=["https://openalex.org/I123"], + topic_id=["https://openalex.org/T12419"], ) assert query["query"]["bool"]["filter"] == [ {"terms": {"publication_year": [2023, 2024]}}, {"terms": {"type": ["article", "book-chapter"]}}, {"terms": {"language": ["en", "de"]}}, + { + "bool": { + "should": [ + {"terms": {"topics.id": ["https://openalex.org/T12419"]}}, + {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, + ], + "minimum_should_match": 1, + }, + }, ] + assert query["query"]["bool"]["must"] == [ + { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + { + "term": { + "authorships.author.id": "https://openalex.org/A5023888391" + } + }, + ], + }, + }, + }, + }, + { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ + "https://openalex.org/I123", + ], + }, + }, + }, + }, + ] + + +def test_author_works_query_uses_nested_institution_path(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], + ) + + assert query["query"]["bool"]["must"][1] == { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ + "https://openalex.org/I205640436", + ], + }, + }, + }, + } + + +def test_author_works_query_adds_topic_filter(): + client = OpenAlexWorksSearchClient(api_key="test-key") + + query = client.author_works_query( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) + + assert query["query"]["bool"]["filter"] == [ + { + "bool": { + "should": [ + {"terms": {"topics.id": ["https://openalex.org/T12419"]}}, + {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, + ], + "minimum_should_match": 1, + }, + }, + ] + + +@pytest.mark.anyio +async def test_search_author_works_passes_institution_filter_to_query(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body["query"]["bool"]["must"][1]["nested"]["path"] == ( + "authorships.institutions" + ) + assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == { + "authorships.institutions.id": ["https://openalex.org/I205640436"], + } + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], + ) + + +@pytest.mark.anyio +async def test_search_author_works_passes_topic_filter_to_query(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body["query"]["bool"]["filter"] == [ + { + "bool": { + "should": [ + {"terms": {"topics.id": ["https://openalex.org/T12419"]}}, + { + "terms": { + "primary_topic.id": ["https://openalex.org/T12419"], + }, + }, + ], + "minimum_should_match": 1, + }, + }, + ] + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) @pytest.mark.anyio diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 2a156323..2f42b8f2 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -112,13 +112,15 @@ export class WorksService extends BaseService implements WorksServiceInterface { * @param publicationYear Filter by publication year. Can be repeated. * @param type Filter by publication type. Can be repeated. * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. * @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; - public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); } @@ -146,6 +148,18 @@ export class WorksService extends BaseService implements WorksServiceInterface { element, 'language'); }) } + if (institutionId) { + institutionId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_id'); + }) + } + if (topicId) { + topicId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_id'); + }) + } let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/api/works.serviceInterface.ts b/webapp/src/app/api/api/works.serviceInterface.ts index 887bb9c3..4572c0ad 100644 --- a/webapp/src/app/api/api/works.serviceInterface.ts +++ b/webapp/src/app/api/api/works.serviceInterface.ts @@ -42,7 +42,9 @@ export interface WorksServiceInterface { * @param publicationYear Filter by publication year. Can be repeated. * @param type Filter by publication type. Can be repeated. * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. */ - getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, extraHttpRequestParams?: any): Observable; + getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, extraHttpRequestParams?: any): Observable; } diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 96c5df8d..dc294f86 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -1,16 +1,16 @@
-
-
-
Publikationen
-

Übersicht der wissenschaftlichen Veröffentlichungen.

-
+
+
Publikationen
+

Übersicht der wissenschaftlichen Veröffentlichungen.

+
+
- Jahr @for (year of publicationYearOptions; track year) { {{ year }} @@ -19,11 +19,11 @@ - Typ @for (type of typeOptions; track type.value) { {{ type.label }} @@ -32,11 +32,11 @@ - Sprache @for (language of languageOptions; track language.value) { {{ @@ -46,11 +46,108 @@ -
+ + @if (selectedInstitutions.length || selectedTopics.length) { +
+ @for (institution of selectedInstitutions; track institution.id) { + + {{ institution.display_name }} + + + } + @for (topic of selectedTopics; track topic.id) { + + {{ topic.display_name }} + + + } +
+ }
@@ -71,7 +168,6 @@ } @else {
{{ publication.title || "Ohne Titel" }}
} -
Becker, A.; Müller, T.; Zhang, L.
@@ -102,6 +198,33 @@ + + Institutionen + + @let publicationInstitutions = institutions(publication); +
+ @for ( + institution of publicationInstitutions.slice(0, 3); + track institution.id + ) { + + {{ institution.name }} + + } @empty { + - + } + @if (publicationInstitutions.length > 3) { + + +{{ publicationInstitutions.length - 3 }} + + } +
+ +
+ Zitationen @@ -112,14 +235,20 @@ Themen + @let publicationTopics = publication.topics ?? [];
- @for (topic of (publication.topics ?? []).slice(0, 3); track topic.id) { - + @for (topic of publicationTopics.slice(0, 3); track topic.id) { + {{ topic.display_name }} - + } @empty { - } + @if (publicationTopics.length > 3) { + + +{{ publicationTopics.length - 3 }} + + }
diff --git a/webapp/src/app/modules/person-publications/person-publications.component.scss b/webapp/src/app/modules/person-publications/person-publications.component.scss index 0f05c502..e6d4fe76 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.scss +++ b/webapp/src/app/modules/person-publications/person-publications.component.scss @@ -6,10 +6,10 @@ .section-heading { display: flex; - align-items: flex-start; + align-items: center; justify-content: space-between; - gap: 24px; - margin-bottom: 22px; + gap: 18px; + margin-bottom: 18px; } h2 { @@ -25,11 +25,20 @@ h2 { font-size: 14px; } +.publication-filter-stack { + display: flex; + align-items: flex-start; + flex-direction: column; + gap: 8px; + padding-top: 10px; + padding-bottom: 25px; +} + .publication-filters { display: flex; flex-wrap: wrap; justify-content: flex-end; - align-items: flex-start; + align-items: center; gap: 10px; } @@ -37,17 +46,117 @@ h2 { width: 150px; } -.publication-filters button { +.publication-filters .institution-filter, +.publication-filters .topic-filter { + width: 320px; +} + +.publication-filters .reset-filter-btn { + min-width: 132px; height: 42px; - border-color: var(--sg-border); + padding: 0 14px; + border-color: #d9e2f0; border-radius: var(--sg-radius-sm); color: var(--sg-text); + background: #fff; +} + +.publication-filters .reset-filter-btn mat-icon { + margin-right: 6px; + width: 20px; + height: 20px; + font-size: 20px; } ::ng-deep .publication-filters .mat-mdc-form-field-subscript-wrapper { display: none; } +::ng-deep .publication-filters .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .publication-filters .mat-mdc-form-field-infix { + min-height: 42px; + padding-top: 11px; + padding-bottom: 9px; +} + +::ng-deep .publication-filters .mdc-notched-outline__leading, +::ng-deep .publication-filters .mdc-notched-outline__notch, +::ng-deep .publication-filters .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .publication-filters .mat-mdc-select-value, +::ng-deep .publication-filters input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .publication-filters .mat-mdc-select-placeholder, +::ng-deep .publication-filters input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +::ng-deep .publication-filters .mat-mdc-form-field-icon-suffix, +::ng-deep .publication-filters .mat-mdc-select-arrow-wrapper { + transform: none; +} + +::ng-deep .mat-mdc-option small { + display: block; + color: var(--sg-text-muted); + font-size: 11px; + line-height: 1.2; +} + +.selected-filter-chips { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + max-width: 900px; + margin: 0; +} + +.selected-filter-chip { + display: inline-flex; + align-items: center; + max-width: 320px; + min-height: 26px; + padding: 3px 4px 3px 9px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-size: 11px; + line-height: 1.2; +} + +.selected-filter-chip button { + display: inline-grid; + place-items: center; + width: 20px; + height: 20px; + margin-left: 3px; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-muted); + cursor: pointer; +} + +.selected-filter-chip mat-icon { + width: 14px; + height: 14px; + font-size: 14px; +} + .table-wrap { position: relative; overflow-x: auto; @@ -55,7 +164,7 @@ h2 { table { width: 100%; - min-width: 980px; + min-width: 1120px; border-collapse: separate; border-spacing: 0 10px; overflow: hidden; @@ -111,6 +220,63 @@ a.title:hover { max-width: 320px; } +.publication-topic-tag, +.publication-topic-more { + display: inline-flex; + align-items: center; + max-width: 180px; + min-height: 24px; + padding: 3px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-size: 11px; + line-height: 1.2; +} + +.publication-topic-tag { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.publication-topic-more { + color: var(--sg-text-muted); +} + +.institution-tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + max-width: 280px; +} + +.publication-institution-tag, +.publication-institution-more { + display: inline-flex; + align-items: center; + max-width: 180px; + min-height: 24px; + padding: 3px 8px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-size: 11px; + line-height: 1.2; +} + +.publication-institution-tag { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.publication-institution-more { + color: var(--sg-text-muted); +} + ::ng-deep .mat-mdc-header-cell { color: var(--sg-text-muted); font-size: 12px; @@ -155,12 +321,27 @@ mat-paginator { flex-direction: column; } + .publication-filter-stack { + align-items: stretch; + } + .publication-filters { justify-content: stretch; + max-width: none; } .publication-filters mat-form-field, .publication-filters button { width: 100%; } + + .publication-filters .institution-filter, + .publication-filters .topic-filter { + width: 100%; + } + + .selected-filter-chips { + justify-content: flex-start; + max-width: none; + } } diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index 1350a65b..a3ddc599 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -1,6 +1,11 @@ -import { Component, OnInit, ViewChild } from '@angular/core'; +import { Component, DestroyRef, OnInit, ViewChild, inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router } from '@angular/router'; +import { + MatAutocompleteModule, + MatAutocompleteSelectedEvent, +} from '@angular/material/autocomplete'; import { MatIconModule } from '@angular/material/icon'; import { MatPaginator, @@ -12,20 +17,72 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatTableModule } from '@angular/material/table'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { + catchError, + combineLatest, + debounceTime, + distinctUntilChanged, + finalize, + map, + of, + switchMap, +} from 'rxjs'; import { Work, WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; import { createLoadError } from '../../shared/utils/errorHandler'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; +interface InstitutionAutocompleteOption { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + +interface InstitutionAutocompleteResponse { + results?: InstitutionAutocompleteOption[] | null; +} + +interface TopicAutocompleteOption { + id?: string | null; + display_name?: string | null; + hint?: string | null; + cited_by_count?: number | null; + works_count?: number | null; + entity_type?: string | null; + external_id?: string | null; +} + +interface TopicAutocompleteResponse { + results?: TopicAutocompleteOption[] | null; +} + +interface PublicationFilterQueryState { + pageIndex: number; + pageSize: number; + publicationYears: number[]; + types: string[]; + languages: string[]; + institutions: InstitutionAutocompleteOption[]; + topics: TopicAutocompleteOption[]; +} + @Component({ selector: 'app-person-publications', imports: [ MatButtonModule, + MatAutocompleteModule, ChipComponent, MatIconModule, MatFormFieldModule, + MatInputModule, MatPaginatorModule, MatProgressSpinnerModule, MatSelectModule, @@ -38,20 +95,34 @@ import { ChipComponent } from '../../shared/ui/chip/chip.component'; }) export class PersonPublicationsComponent implements OnInit { @ViewChild(MatPaginator) paginator?: MatPaginator; + private readonly destroyRef = inject(DestroyRef); displayedColumns: string[] = [ 'title', 'type', 'year', 'language', + 'institutions', 'topics', 'citations', ]; publications: Work[] = []; total = 0; loading = false; + institutionLookupLoading = false; + topicLookupLoading = false; authorId = ''; currentPageIndex = 0; + institutionOptions: InstitutionAutocompleteOption[] = []; + selectedInstitutions: InstitutionAutocompleteOption[] = []; + topicOptions: TopicAutocompleteOption[] = []; + selectedTopics: TopicAutocompleteOption[] = []; + readonly institutionSearchControl = new FormControl< + string | InstitutionAutocompleteOption + >('', { nonNullable: true }); + readonly topicSearchControl = new FormControl('', { + nonNullable: true, + }); readonly filterForm = new FormGroup({ publicationYears: new FormControl([], { nonNullable: true }), @@ -61,6 +132,18 @@ export class PersonPublicationsComponent implements OnInit { readonly publicationYearOptions = this.createPublicationYearOptions(); + private readonly queryParamKeys = { + page: 'publicationPage', + pageSize: 'publicationPageSize', + years: 'publicationYear', + types: 'publicationType', + languages: 'publicationLanguage', + institutionIds: 'publicationInstitutionId', + institutionNames: 'publicationInstitutionName', + topicIds: 'publicationTopicId', + topicNames: 'publicationTopicName', + } as const; + readonly typeOptions = [ { value: 'article', label: 'article' }, { value: 'book', label: 'book' }, @@ -90,16 +173,28 @@ export class PersonPublicationsComponent implements OnInit { constructor( private readonly route: ActivatedRoute, + private readonly router: Router, private readonly workService: WorksService, + private readonly httpClient: HttpClient, public readonly paginationService: PaginationService, private readonly snackBar: MatSnackBar, ) {} ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - this.authorId = params.get('id') ?? ''; - this.resetAndLoad(); - }); + this.setupInstitutionAutocomplete(); + this.setupTopicAutocomplete(); + + const parentParamMap = this.route.parent?.paramMap; + if (!parentParamMap) return; + + combineLatest([parentParamMap, this.route.queryParamMap]) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(([params, queryParams]) => { + this.authorId = params.get('id') ?? ''; + const queryState = this.parsePublicationFilterQueryParams(queryParams); + this.applyPublicationFilterQueryState(queryState); + this.load(queryState.pageIndex, queryState.pageSize); + }); } load(pageIndex = 0, pageSize = this.paginationService.selection): void { @@ -116,6 +211,8 @@ export class PersonPublicationsComponent implements OnInit { this.filters().publicationYears, this.filters().types, this.filters().languages, + this.selectedInstitutionIds(), + this.selectedTopicIds(), ) .subscribe({ next: (page) => { @@ -137,13 +234,19 @@ export class PersonPublicationsComponent implements OnInit { onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; this.currentPageIndex = event.pageIndex; - this.load(event.pageIndex, event.pageSize); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: event.pageIndex + 1, + [this.queryParamKeys.pageSize]: event.pageSize, + }); } - resetAndLoad(): void { + applyFilters(): void { this.currentPageIndex = 0; this.paginator?.firstPage(); - this.load(0, this.paginationService.selection); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: 1, + [this.queryParamKeys.pageSize]: this.paginationService.selection, + }); } clearFilters(): void { @@ -152,7 +255,65 @@ export class PersonPublicationsComponent implements OnInit { types: [], languages: [], }); - this.resetAndLoad(); + this.selectedInstitutions = []; + this.selectedTopics = []; + this.institutionOptions = []; + this.topicOptions = []; + this.institutionSearchControl.setValue('', { emitEvent: false }); + this.topicSearchControl.setValue('', { emitEvent: false }); + this.updatePublicationFilterQueryParams({ + [this.queryParamKeys.page]: 1, + [this.queryParamKeys.pageSize]: this.paginationService.selection, + [this.queryParamKeys.years]: null, + [this.queryParamKeys.types]: null, + [this.queryParamKeys.languages]: null, + [this.queryParamKeys.institutionIds]: null, + [this.queryParamKeys.institutionNames]: null, + [this.queryParamKeys.topicIds]: null, + [this.queryParamKeys.topicNames]: null, + }); + } + + displayInstitution(option: string | InstitutionAutocompleteOption): string { + return typeof option === 'string' ? option : (option.display_name ?? ''); + } + + selectInstitution(event: MatAutocompleteSelectedEvent): void { + const institution = event.option.value as InstitutionAutocompleteOption; + if (!institution.id) return; + if (!this.selectedInstitutions.some((item) => item.id === institution.id)) { + this.selectedInstitutions = [...this.selectedInstitutions, institution]; + this.applyFilters(); + } + this.institutionSearchControl.setValue('', { emitEvent: false }); + this.institutionOptions = []; + } + + removeInstitution(institution: InstitutionAutocompleteOption): void { + this.selectedInstitutions = this.selectedInstitutions.filter( + (item) => item.id !== institution.id, + ); + this.applyFilters(); + } + + displayTopic(option: string | TopicAutocompleteOption): string { + return typeof option === 'string' ? option : (option.display_name ?? ''); + } + + selectTopic(event: MatAutocompleteSelectedEvent): void { + const topic = event.option.value as TopicAutocompleteOption; + if (!topic.id) return; + if (!this.selectedTopics.some((item) => item.id === topic.id)) { + this.selectedTopics = [...this.selectedTopics, topic]; + this.applyFilters(); + } + this.topicSearchControl.setValue('', { emitEvent: false }); + this.topicOptions = []; + } + + removeTopic(topic: TopicAutocompleteOption): void { + this.selectedTopics = this.selectedTopics.filter((item) => item.id !== topic.id); + this.applyFilters(); } doiUrl(doi: string | null | undefined): string | null { @@ -175,6 +336,24 @@ export class PersonPublicationsComponent implements OnInit { return 'info'; } + institutions(publication: Work): Array<{ id: string; name: string }> { + const institutionsById = new Map(); + + for (const authorship of publication.authorships ?? []) { + for (const institution of authorship.institutions ?? []) { + if (!institution.id || !institution.display_name) continue; + if (!institutionsById.has(institution.id)) { + institutionsById.set(institution.id, { + id: institution.id, + name: institution.display_name, + }); + } + } + } + + return Array.from(institutionsById.values()); + } + private filters() { return { publicationYears: this.filterForm.controls.publicationYears.value, @@ -183,6 +362,210 @@ export class PersonPublicationsComponent implements OnInit { }; } + private setupInstitutionAutocomplete(): void { + this.institutionSearchControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.institutionOptions = []; + return of([]); + } + this.institutionLookupLoading = true; + return this.searchInstitutions(query).pipe( + catchError(() => of([])), + finalize(() => { + this.institutionLookupLoading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + const selectedIds = new Set(this.selectedInstitutionIds()); + this.institutionOptions = options.filter( + (option) => !!option.id && !selectedIds.has(option.id), + ); + }); + } + + private setupTopicAutocomplete(): void { + this.topicSearchControl.valueChanges + .pipe( + debounceTime(250), + map((value) => (typeof value === 'string' ? value.trim() : '')), + distinctUntilChanged(), + switchMap((query) => { + if (query.length < 2) { + this.topicOptions = []; + return of([]); + } + this.topicLookupLoading = true; + return this.searchTopics(query).pipe( + catchError(() => of([])), + finalize(() => { + this.topicLookupLoading = false; + }), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((options) => { + const selectedIds = new Set(this.selectedTopicIds()); + this.topicOptions = options.filter( + (option) => !!option.id && !selectedIds.has(option.id), + ); + }); + } + + private searchInstitutions(query: string) { + const params = new HttpParams() + .set('query', query) + .set('limit', '10'); + + const basePath = this.workService.configuration.basePath ?? ''; + return this.httpClient + .get(`${basePath}/api/institutions/autocomplete`, { + params, + }) + .pipe(map((response) => response.results ?? [])); + } + + private searchTopics(query: string) { + const params = new HttpParams().set('query', query).set('limit', '10'); + + const basePath = this.workService.configuration.basePath ?? ''; + return this.httpClient + .get(`${basePath}/api/topics/autocomplete`, { + params, + }) + .pipe(map((response) => response.results ?? [])); + } + + private selectedInstitutionIds(): string[] { + return this.selectedInstitutions + .map((institution) => institution.id) + .filter((id): id is string => !!id); + } + + private selectedTopicIds(): string[] { + return this.selectedTopics + .map((topic) => topic.id) + .filter((id): id is string => !!id); + } + + private updatePublicationFilterQueryParams( + overrides: Record | null>, + ): void { + const filters = this.filters(); + const institutionIds = this.selectedInstitutionIds(); + const institutionNames = this.selectedInstitutions + .map((institution) => institution.display_name) + .filter((name): name is string => !!name); + const topicIds = this.selectedTopicIds(); + const topicNames = this.selectedTopics + .map((topic) => topic.display_name) + .filter((name): name is string => !!name); + + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { + [this.queryParamKeys.years]: filters.publicationYears.length + ? filters.publicationYears + : null, + [this.queryParamKeys.types]: filters.types.length ? filters.types : null, + [this.queryParamKeys.languages]: filters.languages.length + ? filters.languages + : null, + [this.queryParamKeys.institutionIds]: institutionIds.length + ? institutionIds + : null, + [this.queryParamKeys.institutionNames]: institutionNames.length + ? institutionNames + : null, + [this.queryParamKeys.topicIds]: topicIds.length ? topicIds : null, + [this.queryParamKeys.topicNames]: topicNames.length ? topicNames : null, + ...overrides, + }, + queryParamsHandling: 'merge', + }); + } + + private parsePublicationFilterQueryParams( + queryParams: ParamMap, + ): PublicationFilterQueryState { + const institutionIds = queryParams.getAll(this.queryParamKeys.institutionIds); + const institutionNames = queryParams.getAll(this.queryParamKeys.institutionNames); + const topicIds = queryParams.getAll(this.queryParamKeys.topicIds); + const topicNames = queryParams.getAll(this.queryParamKeys.topicNames); + + return { + pageIndex: + this.parsePositiveInteger(queryParams.get(this.queryParamKeys.page), 1) - 1, + pageSize: this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.pageSize), + this.paginationService.selection, + ), + publicationYears: this.parseNumberParams( + queryParams.getAll(this.queryParamKeys.years), + ), + types: this.parseStringParams(queryParams.getAll(this.queryParamKeys.types)), + languages: this.parseStringParams( + queryParams.getAll(this.queryParamKeys.languages), + ), + institutions: institutionIds + .filter(Boolean) + .map((id, index) => ({ + id, + display_name: institutionNames[index] || id, + })), + topics: topicIds + .filter(Boolean) + .map((id, index) => ({ + id, + display_name: topicNames[index] || id, + })), + }; + } + + private applyPublicationFilterQueryState( + queryState: PublicationFilterQueryState, + ): void { + this.currentPageIndex = queryState.pageIndex; + this.paginationService.selection = queryState.pageSize; + this.selectedInstitutions = queryState.institutions; + this.selectedTopics = queryState.topics; + this.filterForm.setValue( + { + publicationYears: queryState.publicationYears, + types: queryState.types, + languages: queryState.languages, + }, + { emitEvent: false }, + ); + } + + private parseStringParams(values: string[]): string[] { + return values.map((value) => value.trim()).filter(Boolean); + } + + private parseNumberParams(values: string[]): number[] { + return values + .map((value) => Number(value)) + .filter((value) => Number.isInteger(value)); + } + + private parsePositiveInteger(value: string | null, fallback: number): number { + const parsedValue = Number(value); + if (!Number.isInteger(parsedValue) || parsedValue < 1) { + return fallback; + } + + return parsedValue; + } + private createPublicationYearOptions(): number[] { const currentYear = new Date().getFullYear(); return Array.from({ length: 90 }, (_, index) => currentYear - index); From 135705adc9ae366846a5c0cb931c984df1f7a48b Mon Sep 17 00:00:00 2001 From: genja Date: Sat, 6 Jun 2026 14:49:41 +0200 Subject: [PATCH 08/33] removed redundant proprerty --- webapp/src/app/modules/person-list/person-list.component.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index fdb2bc8b..4c170319 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -52,8 +52,6 @@ export class PersonListComponent { public readonly state = inject(SharedStateService); public readonly paginationService = inject(PaginationService); - //expose to template - readonly institutionOptions = INSTITUTION_OPTIONS; private readonly defaultIncludes = 'display_name,works_count,cited_by_count,topics,orcid,relevance_rating,last_known_institutions,affiliations'; From bc3f6b6a950bacf2ca304e02b2bc6c0ed0d5119e Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Sat, 6 Jun 2026 17:09:39 +0200 Subject: [PATCH 09/33] implement detail page --- service/src/main/inse/works/logic.py | 27 ++ service/src/main/inse/works/search_client.py | 28 +- service/src/main/inse/works/service.py | 18 + .../src/main/inse/works/test_search_client.py | 53 ++- webapp/src/app/app.routes.ts | 8 + .../research-timeline.component.html | 45 +- .../research-timeline.component.scss | 62 ++- .../research-timeline.component.ts | 52 ++- .../person-overview.component.html | 3 +- .../person-overview.component.ts | 22 +- .../person-publications.component.html | 13 +- .../person-publications.component.ts | 8 +- .../publication-detail.component.html | 256 ++++++++++ .../publication-detail.component.scss | 436 ++++++++++++++++++ .../publication-detail.component.ts | 182 ++++++++ 15 files changed, 1182 insertions(+), 31 deletions(-) create mode 100644 webapp/src/app/modules/publication-detail/publication-detail.component.html create mode 100644 webapp/src/app/modules/publication-detail/publication-detail.component.scss create mode 100644 webapp/src/app/modules/publication-detail/publication-detail.component.ts diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index c4396b8e..cc607218 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -11,6 +11,7 @@ import httpx from fastapi import HTTPException from pydantic import ValidationError from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_404_NOT_FOUND from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.models.work import Work @@ -94,6 +95,32 @@ async def get_all_author_works( ) +async def get_work( + work_id: str, + client: OpenAlexWorksSearchClient | None = None, +) -> Work: + search_client = client or OpenAlexWorksSearchClient() + try: + data = await search_client.search_work(work_id) + except MissingApiKeyError as exc: + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="OpenAlex works search is not configured.", + ) from exc + except httpx.HTTPError as exc: + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + elements, _ = _parse_full_work_search_response(data) + if not elements: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Publication not found.", + ) + return elements[0] + + async def get_topics_by_time_by_author( author_id: str, max_topics_per_year: int = 3, diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 355bfb6e..36b1b3bb 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -113,7 +113,12 @@ class OpenAlexWorksSearchClient: filters.append({ "bool": { "should": [ - {"terms": {"topics.id": topic_id}}, + { + "nested": { + "path": "topics", + "query": {"terms": {"topics.id": topic_id}}, + }, + }, {"terms": {"primary_topic.id": topic_id}}, ], "minimum_should_match": 1, @@ -157,3 +162,24 @@ class OpenAlexWorksSearchClient: # logging.debug(f"Response: {response.text}") response.raise_for_status() return response.json() + + async def search_work(self, work_id: str) -> dict[str, Any]: + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + + indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}" + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{self.index}/_search", + headers={"Authorization": f"ApiKey {self.api_key}"}, + json={ + "size": 1, + "query": {"term": {"id": indexed_work_id}}, + }, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 22916d7c..64479cd8 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -16,6 +16,7 @@ from inse.tags import Tags from .. import security from . import logic from inse.models.work_page import WorkPage +from inse.models.work import Work from inse.models.works_list_response import WorksListResponse from inse.models.topics_by_time import TopicsByTime @@ -94,3 +95,20 @@ async def get_topics_by_time_by_author( author_id, max_topics_per_year=max_topics_per_year, ) + + +@router.get( + "/detail/{work_id}", + operation_id="getWork", + response_model=Work, + summary="Returns one publication.", +) +async def get_work( + work_id: Annotated[ + str, Path(description="The OpenAlex work id, for example W2741809807.") + ], + principal: security.Principal = Depends( + security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) + ), +): + return await logic.get_work(work_id) diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 150880a7..0bfe1a44 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -48,7 +48,16 @@ def test_author_works_query_adds_publication_filters(): { "bool": { "should": [ - {"terms": {"topics.id": ["https://openalex.org/T12419"]}}, + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, ], "minimum_should_match": 1, @@ -125,7 +134,16 @@ def test_author_works_query_adds_topic_filter(): { "bool": { "should": [ - {"terms": {"topics.id": ["https://openalex.org/T12419"]}}, + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, {"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}}, ], "minimum_should_match": 1, @@ -169,7 +187,16 @@ async def test_search_author_works_passes_topic_filter_to_query(): { "bool": { "should": [ - {"terms": {"topics.id": ["https://openalex.org/T12419"]}}, + { + "nested": { + "path": "topics", + "query": { + "terms": { + "topics.id": ["https://openalex.org/T12419"], + }, + }, + }, + }, { "terms": { "primary_topic.id": ["https://openalex.org/T12419"], @@ -217,6 +244,26 @@ async def test_search_author_works_calls_elasticsearch_index_with_api_key(): assert result == {"hits": {"total": {"value": 0}, "hits": []}} +@pytest.mark.anyio +async def test_search_work_filters_by_work_id(): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + assert body == { + "size": 1, + "query": {"term": {"id": "https://openalex.org/W2741809807"}}, + } + return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) + + client = OpenAlexWorksSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + index="openalex-works", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + await client.search_work("W2741809807") + + @pytest.mark.anyio async def test_search_author_works_requires_api_key(): client = OpenAlexWorksSearchClient(api_key="") diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c8fe99fe..38a8ee32 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -26,6 +26,14 @@ export const routes: Routes = [ (mod) => mod.PersonListComponent, ), }, + { + path: 'publication/:publicationId', + canActivate: [userGuard], + loadComponent: () => + import('./modules/publication-detail/publication-detail.component').then( + (mod) => mod.PublicationDetailComponent, + ), + }, { path: 'person/:id', canActivate: [userGuard], 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 cfd25c2e..799f618a 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 @@ -112,7 +112,16 @@ *ngFor="let item of timelineItems; let index = index; trackBy: trackByYear" class="timeline-item" > -

{{ getMainTopic(item) }}

+

+ +

{{ item.publication_count }} @@ -121,14 +130,17 @@
- {{ topic.name }} {{ topic.count }} - + @@ -155,7 +167,16 @@
{{ getPhaseYearLabel(phase) }} -

{{ phase.primaryTopicName }}

+

+ +

{{ phase.publication_count }} {{ phase.publication_count === 1 ? 'Publikation' : 'Publikationen' }} @@ -165,14 +186,17 @@
- {{ topic.name }} {{ topic.count }} - + @@ -208,16 +232,19 @@ else noPhaseYearTopics " > - {{ topic.name }} {{ topic.count }} - + @@ -246,4 +273,4 @@ Keine Timeline-Daten vorhanden.
- \ No newline at end of file + 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 16ca7935..4088f182 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 @@ -315,6 +315,32 @@ font-size: 12px; } +.main-topic-button { + padding: 0; + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-weight: inherit; + line-height: inherit; + cursor: pointer; + + &:hover:not(:disabled) { + color: #0057ff; + text-decoration: underline; + } + + &:focus-visible { + outline: 2px solid #0057ff; + outline-offset: 3px; + border-radius: 3px; + } + + &:disabled { + cursor: default; + } +} + .topic-list { display: flex; flex-direction: column; @@ -335,6 +361,24 @@ font-size: 12px; font-weight: 500; line-height: 1.25; + border: 0; + font-family: inherit; + 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); + } + + &:focus-visible { + outline: 2px solid #0057ff; + outline-offset: 2px; + } + + &:disabled { + cursor: default; + } } .topic-name { @@ -515,6 +559,22 @@ color: #40506f; font-size: 11px; line-height: 1.25; + border: 0; + font-family: inherit; + cursor: pointer; + + &:hover:not(:disabled) { + color: #0057ff; + } + + &:focus-visible { + outline: 2px solid #0057ff; + outline-offset: 2px; + } + + &:disabled { + cursor: default; + } span { overflow-wrap: anywhere; @@ -686,4 +746,4 @@ .phase-year-row { grid-template-columns: 1fr; } -} \ No newline at end of file +} 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 56ec4486..5ca333ef 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 @@ -9,6 +9,7 @@ import { } from '@angular/core'; export interface TopicTimelineTopic { + id?: string; name: string; count: number; } @@ -27,11 +28,17 @@ export interface TimelineYearRange { endYear: number; } +export interface TimelineTopicSelection { + topic: TopicTimelineTopic; + years: number[]; +} + interface ResearchTimelinePhase { id: string; startYear: number; endYear: number; publication_count: number; + primaryTopic: TopicTimelineTopic; primaryTopicName: string; years: TopicTimelineElement[]; topics: TopicTimelineTopic[]; @@ -41,6 +48,7 @@ interface WorkingResearchTimelinePhase { startYear: number; endYear: number; publication_count: number; + primaryTopic: TopicTimelineTopic; primaryTopicName: string; years: TopicTimelineElement[]; } @@ -62,6 +70,7 @@ export class ResearchTimelineComponent implements OnChanges { @Output() viewModeChange = new EventEmitter(); @Output() yearRangeChange = new EventEmitter(); + @Output() topicSelect = new EventEmitter(); timelineViewMode: TimelineViewMode = 'years'; @@ -167,12 +176,27 @@ export class ResearchTimelineComponent implements OnChanges { this.emitYearRangeChange(); } + selectTopic(topic: TopicTimelineTopic): void { + if (!topic.id) { + return; + } + + this.topicSelect.emit({ + topic, + years: this.createSelectedYears(), + }); + } + getPrimaryTopic(item: TopicTimelineElement): TopicTimelineTopic | undefined { return (item.primary_topics ?? [])[0]; } getMainTopic(item: TopicTimelineElement): string { - return this.getPrimaryTopic(item)?.name ?? this.getFirstTopic(item)?.name ?? 'Keine Topics'; + return this.getMainTopicItem(item)?.name ?? 'Keine Topics'; + } + + getMainTopicItem(item: TopicTimelineElement): TopicTimelineTopic | undefined { + return this.getPrimaryTopic(item) ?? this.getFirstTopic(item); } getDisplayedTopics(item: TopicTimelineElement): TopicTimelineTopic[] { @@ -276,7 +300,10 @@ export class ResearchTimelineComponent implements OnChanges { if (candidates.length === 0) { this.pushWorkingPhase(phases, currentPhase); - currentPhase = this.createWorkingPhase(item, this.getMainTopic(item)); + currentPhase = this.createWorkingPhase( + item, + this.getMainTopicItem(item) ?? { name: 'Keine Topics', count: 0 }, + ); continue; } @@ -299,7 +326,7 @@ export class ResearchTimelineComponent implements OnChanges { } this.pushWorkingPhase(phases, currentPhase); - currentPhase = this.createWorkingPhase(item, candidates[0].name); + currentPhase = this.createWorkingPhase(item, candidates[0]); } this.pushWorkingPhase(phases, currentPhase); @@ -309,13 +336,14 @@ export class ResearchTimelineComponent implements OnChanges { private createWorkingPhase( item: TopicTimelineElement, - primaryTopicName: string, + primaryTopic: TopicTimelineTopic, ): WorkingResearchTimelinePhase { return { startYear: item.year, endYear: item.year, publication_count: item.publication_count, - primaryTopicName, + primaryTopic, + primaryTopicName: primaryTopic.name, years: [item], }; } @@ -343,6 +371,7 @@ export class ResearchTimelineComponent implements OnChanges { ): TopicTimelineTopic[] { const counts = new Map(); const originalNames = new Map(); + const ids = new Map(); for (const year of years) { for (const topic of year.topics ?? []) { @@ -353,12 +382,16 @@ export class ResearchTimelineComponent implements OnChanges { const normalizedName = this.normalizeTopicName(topic.name); originalNames.set(normalizedName, topic.name); + if (topic.id) { + ids.set(normalizedName, topic.id); + } counts.set(normalizedName, (counts.get(normalizedName) ?? 0) + topic.count); } } return Array.from(counts.entries()) .map(([normalizedName, count]) => ({ + id: ids.get(normalizedName), name: originalNames.get(normalizedName) ?? normalizedName, count, })) @@ -372,6 +405,13 @@ export class ResearchTimelineComponent implements OnChanges { .slice(0, this.displayedPhaseTopicLimit); } + private createSelectedYears(): number[] { + return Array.from( + { length: this.selectedEndYear - this.selectedStartYear + 1 }, + (_, index) => this.selectedStartYear + index, + ); + } + private getDominantPrimaryTopicCandidates(item: TopicTimelineElement): TopicTimelineTopic[] { const primaryTopics = item.primary_topics ?? []; @@ -443,4 +483,4 @@ export class ResearchTimelineComponent implements OnChanges { endYear: this.selectedEndYear, }); } -} \ No newline at end of file +} 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 363ee7f6..9faf2002 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -8,5 +8,6 @@ [endYear]="timelineEndYear" (viewModeChange)="onTimelineViewModeChange($event)" (yearRangeChange)="onTimelineYearRangeChange($event)" + (topicSelect)="onTimelineTopicSelect($event)" > - \ No newline at end of file + 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 883d017d..e21190cf 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -9,6 +9,7 @@ import { ResearchTimelineComponent, TimelineViewMode, TimelineYearRange, + TimelineTopicSelection, TopicTimelineElement, TopicTimelineTopic, } from './components/research-timeline/research-timeline.component'; @@ -88,6 +89,22 @@ export class PersonOverviewComponent implements OnInit { ); } + onTimelineTopicSelect(selection: TimelineTopicSelection): void { + if (!selection.topic.id) { + return; + } + + void this.router.navigate(['../publications'], { + relativeTo: this.route, + queryParams: { + publicationPage: 1, + publicationYear: selection.years, + publicationTopicId: selection.topic.id, + publicationTopicName: selection.topic.name, + }, + }); + } + private findAuthorId(paramMaps: readonly ParamMap[]): string { return ( paramMaps @@ -139,7 +156,8 @@ export class PersonOverviewComponent implements OnInit { } private mapTopicCounts(topics: TopicCount[] | undefined): TopicTimelineTopic[] { - return (topics ?? []).map((topic) => ({ + return (topics ?? []).map((topic: TopicCount & { id?: string | null }) => ({ + id: topic.id ?? undefined, name: topic.name, count: topic.count ?? 0, })); @@ -174,4 +192,4 @@ export class PersonOverviewComponent implements OnInit { replaceUrl, }); } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index dc294f86..a34b24ef 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -161,13 +161,12 @@ Titel - @if (doiUrl(publication.doi); as url) { - - {{ publication.title || "Ohne Titel" }} - - } @else { -
{{ publication.title || "Ohne Titel" }}
- } + + {{ publication.title || "Ohne Titel" }} +
diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index a3ddc599..4867052f 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -1,7 +1,7 @@ import { Component, DestroyRef, OnInit, ViewChild, inject } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, ParamMap, Router } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; import { MatAutocompleteModule, MatAutocompleteSelectedEvent, @@ -89,6 +89,7 @@ interface PublicationFilterQueryState { MatSnackBarModule, MatTableModule, ReactiveFormsModule, + RouterLink, ], templateUrl: './person-publications.component.html', styleUrl: './person-publications.component.scss', @@ -321,6 +322,11 @@ export class PersonPublicationsComponent implements OnInit { return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; } + publicationKey(publication: Work): string { + const id = publication.id ?? publication.ids?.openalex ?? publication.doi ?? ''; + return id.split('/').filter(Boolean).pop() ?? id; + } + publicationRange(): string { if (this.total === 0 || this.publications.length === 0) { return 'Keine Publikationen'; diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html new file mode 100644 index 00000000..58179d64 --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -0,0 +1,256 @@ +
+ + + @if (loading) { +
+ +

Publikation wird geladen...

+
+ } @else if (notFound || !publication) { +
+ search_off +

Publikation nicht gefunden

+

Die Publikation konnte nicht geladen werden.

+ + Zur Personensuche + +
+ } @else { +
+
+
+ @if (publication.type) { + {{ publication.type }} + } + @if (publication.publication_year) { + {{ publication.publication_year }} + } + @if (publication.language) { + {{ publication.language | uppercase }} + } +
+

{{ publication.title || publication.display_name || "Ohne Titel" }}

+

+ @for (authorship of authors(); track authorship.author?.id; let last = $last) { + {{ authorship.author?.display_name || authorship.raw_author_name || "Unbekannt" }}@if (!last) {, } + } @empty { + Autorinnen und Autoren nicht angegeben + } +

+
+ @for (link of externalLinks().slice(0, 3); track link.url; let first = $first) { + + {{ link.label }} + open_in_new + + } +
+
+ +
+
+ format_quote + {{ publication.cited_by_count ?? 0 | number }} + Zitationen +
+
+ menu_book + {{ publication.referenced_works_count ?? 0 | number }} + Referenzen +
+
+ {{ publication.open_access?.is_oa ? "lock_open" : "lock" }} + {{ publication.open_access?.is_oa ? "Ja" : "Nein" }} + Open Access +
+
+
+ + @if (publication.is_retracted) { +
+ warning + Diese Publikation wurde zurückgezogen. +
+ } + +
+
+ @if (abstractText(); as abstract) { +
+
+ subject +

Abstract

+
+

{{ abstract }}

+
+ } + +
+
+ group +

Autorinnen und Autoren

+ {{ authors().length }} +
+
+ @for (authorship of authors(); track authorship.author?.id) { + + } @empty { +

Keine Angaben vorhanden.

+ } +
+
+ + @if (publication.topics?.length || publication.keywords?.length) { +
+
+ interests +

Themen und Keywords

+
+
+ @for (topic of publication.topics ?? []; track topic.id) { + + {{ topic.display_name }} + + } + @for (keyword of publication.keywords ?? []; track keyword.id) { + {{ keyword.display_name }} + } +
+
+ } + + @if (sources().length) { +
+
+ library_books +

Quellen und Versionen

+
+
+ @for (location of sources(); track location.source?.id || location.landing_page_url) { +
+
+ {{ location.source?.display_name || "Externe Quelle" }} +

+ {{ location.version || location.source?.type || "Veröffentlichte Version" }} + @if (location.license) { · {{ location.license }} } +

+
+
+ @if (location.is_oa) { + Open Access + } + @if (location.pdf_url || location.landing_page_url; as sourceUrl) { + + open_in_new + + } +
+
+ } +
+
+ } +
+ + +
+ } +
diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss new file mode 100644 index 00000000..9e183808 --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -0,0 +1,436 @@ +:host { + display: block; + background: var(--sg-background); +} + +.detail-page { + max-width: 1500px; + margin: 0 auto; + padding: 26px 32px 56px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 7px; + margin-bottom: 22px; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 600; + text-decoration: none; + cursor: pointer; +} + +.back-link mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1fr) 420px; + gap: 42px; + padding: 38px 42px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-lg); + background: + radial-gradient(circle at 90% 10%, rgba(200, 217, 255, 0.75), transparent 35%), + linear-gradient(140deg, #fff 0%, #f8faff 100%); + box-shadow: var(--sg-shadow-sm); +} + +.eyebrow, +.tags, +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.eyebrow span { + padding: 5px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: rgba(255, 255, 255, 0.85); + color: var(--sg-text-muted); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +h1 { + max-width: 920px; + margin: 20px 0 13px; + font-size: clamp(27px, 3vw, 42px); + line-height: 1.13; +} + +.author-line { + max-width: 900px; + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; + line-height: 1.7; +} + +.hero-actions { + margin-top: 26px; +} + +.hero-actions a { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 42px; + padding: 9px 16px; + border: 1px solid var(--sg-border-strong); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-weight: 700; + text-decoration: none; +} + +.hero-actions a.primary-action { + border-color: var(--sg-primary); + background: var(--sg-primary); + color: #fff; +} + +.hero-actions mat-icon { + width: 17px; + height: 17px; + font-size: 17px; +} + +.metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + align-self: center; + overflow: hidden; + border: 1px solid rgba(199, 211, 232, 0.8); + border-radius: var(--sg-radius-md); + background: rgba(255, 255, 255, 0.8); +} + +.metrics div { + display: flex; + align-items: center; + flex-direction: column; + gap: 5px; + padding: 22px 10px; + text-align: center; +} + +.metrics div + div { + border-left: 1px solid var(--sg-border); +} + +.metrics mat-icon { + color: var(--sg-text-soft); +} + +.metrics .positive mat-icon { + color: var(--sg-success); +} + +.metrics strong { + color: var(--sg-text); + font-family: "Montserrat", "Open Sans", sans-serif; + font-size: 22px; +} + +.metrics span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.warning { + display: flex; + align-items: center; + gap: 10px; + margin-top: 20px; + padding: 14px 18px; + border: 1px solid #f1c6cc; + border-radius: var(--sg-radius-sm); + background: #fff4f5; + color: #9c2637; + font-weight: 700; +} + +.content-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) 380px; + gap: 24px; + margin-top: 24px; +} + +main, +aside { + display: flex; + flex-direction: column; + gap: 24px; +} + +.card { + padding: 26px 28px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-md); + background: var(--sg-surface); + box-shadow: var(--sg-shadow-sm); +} + +.section-title { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 20px; +} + +.section-title mat-icon { + color: var(--sg-text-muted); +} + +.section-title h2 { + margin: 0; + font-size: 16px; +} + +.section-title span { + margin-left: auto; + color: var(--sg-text-muted); + font-size: 12px; +} + +.abstract-card p { + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.8; +} + +.author-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.author-list article { + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + gap: 11px; + align-items: center; + padding: 12px; + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); +} + +.avatar { + display: grid; + place-items: center; + width: 38px; + height: 38px; + border-radius: 50%; + background: #e5ecfb; + color: var(--sg-text); + font-weight: 700; + text-transform: uppercase; +} + +.author-list a, +.author-list strong { + color: var(--sg-text); + font-size: 13px; + font-weight: 700; + text-decoration: none; +} + +.author-list p, +.source-list p { + margin: 3px 0 0; + color: var(--sg-text-muted); + font-size: 11px; +} + +.tags span { + padding: 7px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + color: var(--sg-text-muted); + font-size: 11px; +} + +.tags .topic-tag { + border-color: #cbd8f1; + background: #f5f8ff; + color: var(--sg-text); +} + +.source-list, +.compact-list, +.link-list { + display: grid; + gap: 10px; +} + +.source-list article, +.compact-list div { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 13px 0; + border-bottom: 1px solid var(--sg-border); +} + +.source-list article:last-child, +.compact-list div:last-child { + border-bottom: 0; +} + +.source-actions { + display: flex; + align-items: center; + gap: 10px; +} + +.source-actions a { + height: 24px; +} + +.source-actions mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.oa-badge { + padding: 4px 8px; + border-radius: 999px; + background: var(--sg-success-soft); + color: var(--sg-success); + font-size: 10px; + font-weight: 700; +} + +dl { + margin: 0; +} + +dl div { + display: grid; + grid-template-columns: 115px minmax(0, 1fr); + gap: 12px; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); +} + +dl div:last-child { + border-bottom: 0; +} + +dt { + color: var(--sg-text-muted); + font-size: 12px; +} + +dd { + margin: 0; + overflow-wrap: anywhere; + color: var(--sg-text); + font-size: 12px; + font-weight: 600; + text-align: right; +} + +.compact-list div { + align-items: flex-start; + flex-direction: column; + gap: 3px; +} + +.compact-list strong { + font-size: 12px; +} + +.compact-list span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.link-list a { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 12px; + font-weight: 700; + text-decoration: none; +} + +.link-list a:last-child { + border-bottom: 0; +} + +.link-list mat-icon { + width: 16px; + height: 16px; + color: var(--sg-text-muted); + font-size: 16px; +} + +.state { + display: grid; + place-items: center; + min-height: 380px; + color: var(--sg-text-muted); + text-align: center; +} + +.error-state mat-icon { + width: 46px; + height: 46px; + font-size: 46px; +} + +.empty { + color: var(--sg-text-muted); +} + +@media (max-width: 1150px) { + .hero, + .content-grid { + grid-template-columns: 1fr; + } + + .metrics { + width: 100%; + } +} + +@media (max-width: 700px) { + .detail-page { + padding: 18px 16px 40px; + } + + .hero, + .card { + padding: 22px 20px; + } + + .metrics, + .author-list { + grid-template-columns: 1fr; + } + + .metrics div + div { + border-top: 1px solid var(--sg-border); + border-left: 0; + } +} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts new file mode 100644 index 00000000..e4c0b56f --- /dev/null +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -0,0 +1,182 @@ +import { DatePipe, DecimalPipe, UpperCasePipe } from '@angular/common'; +import { Location } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { HttpClient } from '@angular/common/http'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { finalize } from 'rxjs'; + +import { Authorship, Location as ApiLocation, Work, WorksService } from '../../api'; + +interface DetailLink { + label: string; + url: string; +} + +interface InstitutionDetail { + id: string; + name: string; + country?: string | null; + type?: string | null; +} + +@Component({ + selector: 'app-publication-detail', + imports: [ + DatePipe, + DecimalPipe, + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + RouterLink, + UpperCasePipe, + ], + templateUrl: './publication-detail.component.html', + styleUrl: './publication-detail.component.scss', +}) +export class PublicationDetailComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly location = inject(Location); + private readonly worksService = inject(WorksService); + + publication: Work | null = null; + loading = true; + notFound = false; + + ngOnInit(): void { + this.route.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const publicationId = params.get('publicationId'); + if (!publicationId) { + this.loading = false; + this.notFound = true; + return; + } + + this.loadPublication(publicationId); + }); + } + + navigateBack(): void { + this.location.back(); + } + + abstractText(): string | null { + const index = this.publication?.abstract_inverted_index; + if (!index || typeof index !== 'object') return null; + + const words: Array<{ word: string; position: number }> = []; + for (const [word, rawPositions] of Object.entries(index)) { + if (!Array.isArray(rawPositions)) continue; + for (const position of rawPositions) { + if (typeof position === 'number') words.push({ word, position }); + } + } + + return words + .sort((first, second) => first.position - second.position) + .map(({ word }) => word) + .join(' ') || null; + } + + authors(): Authorship[] { + return this.publication?.authorships ?? []; + } + + institutions(): InstitutionDetail[] { + const institutions = new Map(); + for (const authorship of this.authors()) { + for (const institution of authorship.institutions ?? []) { + if (!institution.id || !institution.display_name) continue; + institutions.set(institution.id, { + id: institution.id, + name: institution.display_name, + country: institution.country_code, + type: institution.type, + }); + } + } + return Array.from(institutions.values()); + } + + sources(): ApiLocation[] { + const locations = [ + this.publication?.primary_location, + this.publication?.best_oa_location, + ...(this.publication?.locations ?? []), + ].filter((location): location is ApiLocation => !!location); + const unique = new Map(); + for (const location of locations) { + const key = + location.source?.id ?? + location.landing_page_url ?? + location.pdf_url ?? + JSON.stringify(location); + unique.set(key, location); + } + return Array.from(unique.values()); + } + + externalLinks(): DetailLink[] { + if (!this.publication) return []; + const links: DetailLink[] = []; + this.addLink(links, 'Open Access', this.publication.open_access?.oa_url); + this.addLink(links, 'DOI', this.doiUrl(this.publication.doi)); + return links.filter( + (link, index) => links.findIndex((candidate) => candidate.url === link.url) === index, + ); + } + + pages(): string | null { + const first = this.publication?.biblio?.first_page; + const last = this.publication?.biblio?.last_page; + if (first && last) return `${first}-${last}`; + return first ?? last ?? null; + } + + openAccessLabel(): string { + if (this.publication?.open_access?.is_oa) { + return this.publication.open_access.oa_status + ? `Open Access (${this.publication.open_access.oa_status})` + : 'Open Access'; + } + return 'Kein Open Access'; + } + + private loadPublication(publicationId: string): void { + this.loading = true; + this.notFound = false; + this.publication = null; + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get( + `${basePath}/api/works/detail/${encodeURIComponent(publicationId)}`, + ) + .pipe(finalize(() => (this.loading = false))) + .subscribe({ + next: (publication) => { + this.publication = publication; + }, + error: () => { + this.notFound = true; + }, + }); + } + + private doiUrl(doi: string | null | undefined): string | null { + if (!doi) return null; + return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; + } + + private addLink(links: DetailLink[], label: string, value: string | null | undefined) { + if (!value) return; + links.push({ label, url: value.startsWith('http') ? value : `https://${value}` }); + } +} From 9f3066dbc44881472ec677cb2fc3e60d67319104 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 6 Jun 2026 17:13:37 +0200 Subject: [PATCH 10/33] Removed visible IDs from network --- webapp/src/app/app.routes.ts | 14 +++++++++ .../institution/institution.component.html | 1 + .../institution/institution.component.scss | 0 .../institution/institution.component.ts | 11 +++++++ ...erson-network-collaborators.component.html | 17 +++++----- ...erson-network-collaborators.component.scss | 9 ++++++ .../person-network-collaborators.component.ts | 2 +- ...erson-network-filter-dialog.component.scss | 6 +--- .../person-network-graph.component.ts | 3 +- ...person-network-institutions.component.html | 31 +++++++++++++------ ...person-network-institutions.component.scss | 9 ++++++ .../person-network-institutions.component.ts | 2 +- ...person-network-publications.component.html | 22 ++++++++----- ...person-network-publications.component.scss | 9 ++++++ .../person-network-publications.component.ts | 2 +- .../person-network.component.ts | 9 ++++-- .../src/app/modules/work/work.component.html | 1 + .../src/app/modules/work/work.component.scss | 0 webapp/src/app/modules/work/work.component.ts | 11 +++++++ 19 files changed, 121 insertions(+), 38 deletions(-) create mode 100644 webapp/src/app/modules/institution/institution.component.html create mode 100644 webapp/src/app/modules/institution/institution.component.scss create mode 100644 webapp/src/app/modules/institution/institution.component.ts create mode 100644 webapp/src/app/modules/work/work.component.html create mode 100644 webapp/src/app/modules/work/work.component.scss create mode 100644 webapp/src/app/modules/work/work.component.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 62ca6832..3c869a34 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -82,6 +82,20 @@ export const routes: Routes = [ }, ], }, + { + path: 'institution/:id', + canActivate: [userGuard], + loadComponent: () => + import('./modules/institution/institution.component').then( + (mod) => mod.InstitutionComponent, + ), + }, + { + path: 'work/:id', + canActivate: [userGuard], + loadComponent: () => + import('./modules/work/work.component').then((mod) => mod.WorkComponent), + }, { path: '**', redirectTo: 'login', diff --git a/webapp/src/app/modules/institution/institution.component.html b/webapp/src/app/modules/institution/institution.component.html new file mode 100644 index 00000000..06cbe4a2 --- /dev/null +++ b/webapp/src/app/modules/institution/institution.component.html @@ -0,0 +1 @@ +

institution works!

diff --git a/webapp/src/app/modules/institution/institution.component.scss b/webapp/src/app/modules/institution/institution.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts new file mode 100644 index 00000000..0cdeb3de --- /dev/null +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -0,0 +1,11 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-institution', + imports: [], + templateUrl: './institution.component.html', + styleUrl: './institution.component.scss', +}) +export class InstitutionComponent { + +} diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html index 174e3857..cee55b3c 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.html @@ -1,9 +1,5 @@
- - - - @@ -39,15 +35,18 @@ >
ID{{ element.id }} Name @@ -19,13 +15,13 @@ - +
+@if (dataSource.filteredData.length === 0) { +

Keine Kollaborierenden gefunden.

+}
diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss index 57d2cbf4..4dfb4f9e 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.scss @@ -27,3 +27,12 @@ .detail-row { width: 100%; } + +.work-link { + color: var(--sg-primary); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts index 0860dec1..798ff06f 100644 --- a/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts +++ b/webapp/src/app/modules/person-network-collaborators/person-network-collaborators.component.ts @@ -43,7 +43,7 @@ export class PersonNetworkCollaboratorsComponent implements AfterViewInit { collaborationNetwork = input.required(); searchTerm = input.required(); - displayedColumns: string[] = ['id', 'name', 'count', 'actions']; + displayedColumns: string[] = ['name', 'count', 'actions']; dataSource = new MatTableDataSource(); diff --git a/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss index 8a9b4eb9..d030a8c7 100644 --- a/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss +++ b/webapp/src/app/modules/person-network-filter-dialog/person-network-filter-dialog.component.scss @@ -1,17 +1,13 @@ form { - padding: 20px; + padding: 5px; display: flex; flex-direction: column; - gap: 20px; } - - .form-field-full { width: 100%; } - .toggle-group { margin-bottom: 20px; } diff --git a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts index 8c6235de..9567c626 100644 --- a/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts +++ b/webapp/src/app/modules/person-network-graph/person-network-graph.component.ts @@ -81,7 +81,7 @@ export class PersonNetworkGraphComponent { author: 'Autor', collaborator: 'Kollaborierender', institution: 'Institution', - work: 'Arbeit', + work: 'Publikation', }; onChartEvent(event: any, type: string) { @@ -194,6 +194,7 @@ export class PersonNetworkGraphComponent { friction: 0.9, gravity: 0.2, }, + zoom: 0.1, links: item.links.map((e) => { return { source: e[0] + '', diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html index 052d4d06..22621d39 100644 --- a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.html @@ -1,11 +1,7 @@
- - - - - + @@ -16,7 +12,19 @@ {{ element.collaborators.length }} - + + + + +
ID{{ element.id }} TitelName {{ element.name }} + + open_in_new + +
+@if (dataSource.filteredData.length === 0) { +

Keine Institutionen gefunden.

+} @@ -34,9 +45,11 @@ diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss index 57d2cbf4..7cb09d57 100644 --- a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.scss @@ -27,3 +27,12 @@ .detail-row { width: 100%; } + +.person-link { + color: var(--sg-primary); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts index 38df3cbe..d68dd101 100644 --- a/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts +++ b/webapp/src/app/modules/person-network-institutions/person-network-institutions.component.ts @@ -41,7 +41,7 @@ export class PersonNetworkInstitutionsComponent implements AfterViewInit { collaborationNetwork = input.required(); searchTerm = input.required(); - displayedColumns: string[] = ['id', 'name', 'collaborators']; + displayedColumns: string[] = ['name', 'collaborators', 'actions']; dataSource = new MatTableDataSource(); diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html index 9206482a..80a737c9 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.html +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.html @@ -1,9 +1,5 @@
- - - - + + + +
ID{{ element.id }} Titel @@ -16,6 +12,14 @@ {{ element.collaborators.length }} + + open_in_new + +
+@if (dataSource.filteredData.length === 0) { +

Keine Publikationen gefunden.

+} @@ -34,10 +41,9 @@ diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss b/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss index 57d2cbf4..7cb09d57 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.scss @@ -27,3 +27,12 @@ .detail-row { width: 100%; } + +.person-link { + color: var(--sg-primary); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} diff --git a/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts b/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts index d594e6fa..eee8078c 100644 --- a/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts +++ b/webapp/src/app/modules/person-network-publications/person-network-publications.component.ts @@ -43,7 +43,7 @@ export class PersonNetworkPublicationsComponent implements AfterViewInit { collaborationNetwork = input.required(); searchTerm = input.required(); - displayedColumns: string[] = ['id', 'title', 'contributors']; + displayedColumns: string[] = ['title', 'contributors', 'actions']; dataSource = new MatTableDataSource(); 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 e91df9fb..ca8a9a52 100644 --- a/webapp/src/app/modules/person-network/person-network.component.ts +++ b/webapp/src/app/modules/person-network/person-network.component.ts @@ -94,11 +94,11 @@ export class PersonNetworkComponent implements OnInit { const displayedTable = this.displayedTable(); switch (displayedTable) { case 'collaborators': - return 'Suche Kollaborierende nach Name oder ID'; + return 'Suche Kollaborierende nach Name'; case 'publications': - return 'Suche Publikationen nach Titel oder ID'; + return 'Suche Publikationen nach Titel'; case 'institutions': - return 'Suche Institutionen nach Name oder ID'; + return 'Suche Institutionen nach Name'; default: return 'Suchbegriff'; } @@ -120,6 +120,9 @@ export class PersonNetworkComponent implements OnInit { } this.latestNodeId.set(id); + if (category === 'author') { + return; + } this.filterForm.patchValue({ displayedTable: this.categoryTableMap[category], diff --git a/webapp/src/app/modules/work/work.component.html b/webapp/src/app/modules/work/work.component.html new file mode 100644 index 00000000..e8187ec0 --- /dev/null +++ b/webapp/src/app/modules/work/work.component.html @@ -0,0 +1 @@ +

work works!

diff --git a/webapp/src/app/modules/work/work.component.scss b/webapp/src/app/modules/work/work.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/work/work.component.ts b/webapp/src/app/modules/work/work.component.ts new file mode 100644 index 00000000..f4fda054 --- /dev/null +++ b/webapp/src/app/modules/work/work.component.ts @@ -0,0 +1,11 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-work', + imports: [], + templateUrl: './work.component.html', + styleUrl: './work.component.scss', +}) +export class WorkComponent { + +} From 0025bac51afa55a479ef9cf17c9a89446ea80b62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 6 Jun 2026 17:31:36 +0200 Subject: [PATCH 11/33] Merge branch 'dev' into network --- service/Dockerfile | 3 +- service/pyproject.toml | 1 + service/src/main/inse/.env | 4 +- .../inse/collaboration_network/service.py | 4 +- service/src/main/inse/funders/__init__.py | 5 + .../inse/funders/elastic_search_client.py | 160 ++++ service/src/main/inse/funders/logic.py | 305 ++++++++ service/src/main/inse/funders/model.py | 44 ++ service/src/main/inse/funders/service.py | 39 + service/src/main/inse/funders/test_logic.py | 263 +++++++ .../main/inse/integrations/elasticsearch.py | 21 +- service/src/main/inse/integrations/llm.py | 46 +- service/src/main/inse/logic.py | 277 ++----- service/src/main/inse/main.py | 4 + service/src/main/inse/model.py | 3 - service/src/main/inse/models/topic_count.py | 3 + service/src/main/inse/persons/__init__.py | 0 service/src/main/inse/persons/logic.py | 435 +++++++++++ service/src/main/inse/persons/model.py | 45 ++ .../src/main/inse/persons/query_builder.py | 230 ++++++ service/src/main/inse/persons/service.py | 234 ++++++ service/src/main/inse/service.py | 146 +--- service/src/main/inse/util.py | 9 +- service/src/main/inse/works/logic.py | 68 +- service/src/main/inse/works/model.py | 322 -------- service/src/main/inse/works/service.py | 12 + service/uv.lock | 114 +++ webapp/openapitools.json | 2 +- webapp/src/app/api/.openapi-generator/FILES | 8 + webapp/src/app/api/api/api.ts | 4 +- webapp/src/app/api/api/funding.service.ts | 161 ++++ webapp/src/app/api/api/iNSEService.service.ts | 291 +------- webapp/src/app/api/api/persons.service.ts | 546 +++++++++++++- webapp/src/app/api/api/topics.service.ts | 51 ++ webapp/src/app/api/api/works.service.ts | 60 ++ .../src/app/api/model/authorPositionCount.ts | 18 + webapp/src/app/api/model/customAuthor.ts | 39 + .../api/model/customAuthorsListResponse.ts | 22 + webapp/src/app/api/model/funderByAuthor.ts | 23 + .../app/api/model/fundersByAuthorResponse.ts | 19 + webapp/src/app/api/model/models.ts | 7 + .../model/publicationIdsByAuthorPosition.ts | 18 + .../api/model/publicationsByAuthorResponse.ts | 21 + webapp/src/app/api/model/topicCount.ts | 1 + webapp/src/app/app.routes.ts | 7 + .../person-funding.component.html | 180 +++++ .../person-funding.component.scss | 298 ++++++++ .../person-funding.component.ts | 270 +++++++ .../person-interesting.component.html | 9 +- .../person-interesting.component.scss | 14 +- .../person-interesting.component.ts | 20 +- .../person-list/person-list.component.html | 291 ++++++-- .../person-list/person-list.component.scss | 688 ++++++++++++++++-- .../person-list/person-list.component.ts | 470 +++++++++--- .../research-timeline.component.scss | 19 + .../research-timeline.component.ts | 85 ++- .../person-overview.component.html | 5 + .../person-overview.component.ts | 86 ++- .../app/modules/person/person.component.html | 140 ++-- .../app/modules/person/person.component.scss | 64 +- .../app/modules/person/person.component.ts | 37 +- .../topic-hierarchy.component.html | 93 +++ .../topic-hierarchy.component.scss | 194 +++++ .../topic-hierarchy.component.spec.ts | 23 + .../topic-hierarchy.component.ts | 156 ++++ .../app/shared/services/credential.service.ts | 68 +- .../ui/app-layout/app-layout.component.html | 12 +- .../ui/app-layout/app-layout.component.scss | 71 +- .../ui/app-layout/app-layout.component.ts | 15 +- .../ui/app-menu/app-menu.component.html | 1 + .../shared/ui/app-menu/app-menu.component.ts | 8 +- .../app-searchbar.component.html | 23 + .../app-searchbar.component.scss | 28 + .../app-searchbar/app-searchbar.component.ts | 112 +++ webapp/src/app/shared/utils/filters.ts | 19 + 75 files changed, 6152 insertions(+), 1442 deletions(-) create mode 100644 service/src/main/inse/funders/__init__.py create mode 100644 service/src/main/inse/funders/elastic_search_client.py create mode 100644 service/src/main/inse/funders/logic.py create mode 100644 service/src/main/inse/funders/model.py create mode 100644 service/src/main/inse/funders/service.py create mode 100644 service/src/main/inse/funders/test_logic.py create mode 100644 service/src/main/inse/persons/__init__.py create mode 100644 service/src/main/inse/persons/logic.py create mode 100644 service/src/main/inse/persons/model.py create mode 100644 service/src/main/inse/persons/query_builder.py create mode 100644 service/src/main/inse/persons/service.py create mode 100644 webapp/src/app/api/api/funding.service.ts create mode 100644 webapp/src/app/api/model/authorPositionCount.ts create mode 100644 webapp/src/app/api/model/customAuthor.ts create mode 100644 webapp/src/app/api/model/customAuthorsListResponse.ts create mode 100644 webapp/src/app/api/model/funderByAuthor.ts create mode 100644 webapp/src/app/api/model/fundersByAuthorResponse.ts create mode 100644 webapp/src/app/api/model/publicationIdsByAuthorPosition.ts create mode 100644 webapp/src/app/api/model/publicationsByAuthorResponse.ts create mode 100644 webapp/src/app/modules/person-funding/person-funding.component.html create mode 100644 webapp/src/app/modules/person-funding/person-funding.component.scss create mode 100644 webapp/src/app/modules/person-funding/person-funding.component.ts create mode 100644 webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html create mode 100644 webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss create mode 100644 webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.spec.ts create mode 100644 webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts create mode 100644 webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html create mode 100644 webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss create mode 100644 webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts create mode 100644 webapp/src/app/shared/utils/filters.ts diff --git a/service/Dockerfile b/service/Dockerfile index 403e56c1..2335ec87 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -15,7 +15,8 @@ RUN mkdir /test && \ "pytest~=8.1.0" \ "httpx~=0.27.0" \ "python-multipart~=0.0.19"\ - "elasticsearch~=9.4.0" + "elasticsearch~=9.4.0" \ + "openai~=2.41.0" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/pyproject.toml b/service/pyproject.toml index d0d54039..689f20cf 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -10,6 +10,7 @@ dependencies = [ "elasticsearch~=9.4.0", "fastapi~=0.115.0", "httpx~=0.27.0", + "openai~=2.41.0", "pydantic~=2.7.1", "pydantic-settings~=2.2.1", "pyjwt~=2.8.0", diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 72266db6..f2fc4762 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -1,6 +1,6 @@ ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ -LLM_API_URL=https://project.nes.uni-due.de/llm2/api/generate +LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 -LLM_MODEL=gemma4:e4b \ No newline at end of file +LLM_MODEL=gemma4-e4b \ No newline at end of file diff --git a/service/src/main/inse/collaboration_network/service.py b/service/src/main/inse/collaboration_network/service.py index 19c18e45..418db2fc 100644 --- a/service/src/main/inse/collaboration_network/service.py +++ b/service/src/main/inse/collaboration_network/service.py @@ -229,7 +229,9 @@ def reduce_collaboration_network( or node.raw_id in valid_node_ids } - return collaboration_nodes, {edge for edge in collaboration_edges if edge.raw_source_id in valid_node_ids} + return collaboration_nodes, { + edge for edge in collaboration_edges if edge.raw_source_id in valid_node_ids + } def extract_institutions(works: List[Work]) -> Set[InstitutionInformation]: diff --git a/service/src/main/inse/funders/__init__.py b/service/src/main/inse/funders/__init__.py new file mode 100644 index 00000000..a12699fd --- /dev/null +++ b/service/src/main/inse/funders/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Funders domain package. +""" diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py new file mode 100644 index 00000000..f19cc511 --- /dev/null +++ b/service/src/main/inse/funders/elastic_search_client.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + HTTP client for funded-publication searches in the OpenAlex works index. +""" +from typing import Any + +import httpx + +from .. import config + + +class MissingApiKeyError(Exception): + pass + + +class FundedPublicationsSearchClient: + def __init__( + self, + base_url: str | None = None, + index: str | None = None, + api_key: str | None = None, + timeout: float | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/") + self.index = index or config.settings.openalex_works_search_index + self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key + self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds + self.transport = transport + + @staticmethod + def indexed_author_id(author_id: str) -> str: + short_id = author_id.strip().removeprefix("https://openalex.org/") + return f"https://openalex.org/{short_id}" + + def publications_by_author_query( + self, + author_id: str, + page: int, + size: int, + *, + funded_only: bool = False, + ) -> dict[str, Any]: + indexed_author_id = self.indexed_author_id(author_id) + must: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": { + "term": { + "authorships.author.id": indexed_author_id, + }, + }, + }, + }, + ] + + if funded_only: + must.append(self._has_funding_clause()) + + return { + "from": (page - 1) * size, + "size": size, + "track_total_hits": True, + "_source": self._publication_source_fields(), + "query": { + "bool": { + "must": must, + }, + }, + } + + @staticmethod + def _publication_source_fields() -> list[str]: + return [ + "id", + "doi", + "title", + "display_name", + "publication_year", + "primary_location.landing_page_url", + "primary_location.pdf_url", + "best_oa_location.landing_page_url", + "best_oa_location.pdf_url", + "open_access.oa_url", + "authorships.author.id", + "authorships.author.display_name", + "authorships.author_position", + "funders.id", + "funders.display_name", + "funders.ror", + "awards.id", + "awards.funder_id", + "awards.funder_display_name", + "awards.funder_award_id", + ] + + @staticmethod + def _has_funding_clause() -> dict[str, Any]: + return { + "bool": { + "should": [ + { + "nested": { + "path": "funders", + "query": { + "bool": { + "should": [ + {"exists": {"field": "funders.id"}}, + {"exists": {"field": "funders.display_name"}}, + ], + "minimum_should_match": 1, + }, + }, + }, + }, + { + "nested": { + "path": "awards", + "query": { + "bool": { + "should": [ + {"exists": {"field": "awards.funder_id"}}, + {"exists": {"field": "awards.funder_display_name"}}, + ], + "minimum_should_match": 1, + }, + }, + }, + }, + ], + "minimum_should_match": 1, + }, + } + + def funded_publications_by_author_query( + self, + author_id: str, + page: int, + size: int, + ) -> dict[str, Any]: + return self.publications_by_author_query(author_id, page, size, funded_only=True) + + async def search(self, payload: dict[str, Any]) -> dict[str, Any]: + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{self.index}/_search", + headers={"Authorization": f"ApiKey {self.api_key}"}, + json=payload, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py new file mode 100644 index 00000000..95a7493e --- /dev/null +++ b/service/src/main/inse/funders/logic.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Business logic for author funding based on publication works. +""" +import logging +from typing import Any + +import httpx +from fastapi import HTTPException +from pydantic import ValidationError +from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_503_SERVICE_UNAVAILABLE + +from ..persons import logic as person_logic +from . import model +from .elastic_search_client import FundedPublicationsSearchClient +from .elastic_search_client import MissingApiKeyError + +logger = logging.getLogger(__name__) + +_VALID_AUTHOR_POSITIONS = frozenset({"first", "middle", "last"}) +_ES_PAGE_SIZE = 500 +_MAX_ES_PAGES = 100 + + +async def get_publications_by_author_id( + author_id: str, + page: int = 1, + page_size: int = 20, + client: FundedPublicationsSearchClient | None = None, +) -> model.PublicationsByAuthorResponse: + search_client = client or FundedPublicationsSearchClient() + total_works, all_hits = await _fetch_all_author_work_hits( + search_client, + author_id, + funded_only=True, + ) + funded_hits = [ + hit for hit in all_hits + if _publication_has_funder_data(hit.get("_source", {})) + ] + start = (page - 1) * page_size + end = start + page_size + + return model.PublicationsByAuthorResponse( + author_id=FundedPublicationsSearchClient.indexed_author_id(author_id), + page=page, + page_size=page_size, + total_works=total_works, + total=len(funded_hits), + results_count=len(funded_hits[start:end]), + results=funded_hits[start:end], + ) + + +async def get_funders_by_author_id( + author_id: str, + client: FundedPublicationsSearchClient | None = None, +) -> model.FundersByAuthorResponse: + search_client = client or FundedPublicationsSearchClient() + funder_counts: dict[str, dict[str, Any]] = {} + + normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id) + author_name = _get_author_name(author_id) + + try: + _, all_hits = await _fetch_all_author_work_hits( + search_client, + author_id, + funded_only=True, + ) + _collect_funders_from_publications(all_hits, author_id, funder_counts) + + if not funder_counts: + logger.info( + "No funders aggregated for author %s from Elasticsearch.", + normalized_author_id, + ) + + funders = sorted( + funder_counts.values(), + key=lambda entry: entry["publication_count"], + reverse=True, + ) + + return model.FundersByAuthorResponse( + author_id=normalized_author_id, + author_name=author_name, + funder_count=len(funders), + funders=[model.FunderByAuthor.model_validate(entry) for entry in funders], + ) + except ValidationError as exc: + logger.exception("Funders response could not be validated for author %s.", author_id) + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Funders response could not be parsed.", + ) from exc + + +async def _fetch_all_author_work_hits( + search_client: FundedPublicationsSearchClient, + author_id: str, + *, + funded_only: bool = False, + page_size: int = _ES_PAGE_SIZE, +) -> tuple[int, list[dict]]: + page = 1 + total_works = 0 + all_hits: list[dict] = [] + + while page <= _MAX_ES_PAGES: + data = await _search_funded_publications( + search_client, + author_id, + page, + page_size, + funded_only=funded_only, + ) + total_works, hits = _parse_publication_search_response(data) + all_hits.extend(hits) + + if not hits or page * page_size >= total_works: + break + + page += 1 + + if page > _MAX_ES_PAGES and page * page_size < total_works: + logger.warning( + "Stopped pagination for author %s at %s pages (total works: %s).", + author_id, + _MAX_ES_PAGES, + total_works, + ) + + return total_works, all_hits + + +async def _search_funded_publications( + search_client: FundedPublicationsSearchClient, + author_id: str, + page: int, + page_size: int, + *, + funded_only: bool = False, +) -> dict: + try: + payload = search_client.publications_by_author_query( + author_id, + page, + page_size, + funded_only=funded_only, + ) + return await search_client.search(payload) + except MissingApiKeyError as exc: + logger.error("OpenAlex works Elasticsearch API key is not configured.") + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="OpenAlex works search is not configured.", + ) from exc + except httpx.HTTPError as exc: + logger.exception("OpenAlex works search request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + + +def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: + hits = data.get("hits", {}) + total = hits.get("total", 0) + + if isinstance(total, dict): + total = total.get("value", 0) + + results = hits.get("hits", []) + for hit in results: + _add_publication_url(hit.get("_source", {})) + + return total, results + + +def _get_author_name(author_id: str) -> str | None: + short_author_id = author_id.replace("https://openalex.org/", "") + search_result = person_logic.search_persons(author_id=short_author_id) + + if not search_result.results: + return None + + return search_result.results[0].display_name + + +def _get_author_position_in_publication(publication: dict, author_id: str) -> str: + normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id) + + for authorship in publication.get("authorships", []): + author = authorship.get("author", {}) + if author.get("id") == normalized_author_id: + position = authorship.get("author_position", "unknown") + if position in _VALID_AUTHOR_POSITIONS: + return position + return "unknown" + + return "unknown" + + +def _publication_has_funder_data(publication: dict) -> bool: + for funder in publication.get("funders", []): + if funder.get("id") or funder.get("display_name"): + return True + + for award in publication.get("awards", []): + if award.get("funder_id") or award.get("funder_display_name"): + return True + + return False + + +def _add_publication_url(publication: dict) -> None: + publication["publication_url"] = _resolve_publication_url(publication) + + +def _resolve_publication_url(publication: dict) -> str | None: + primary_location = publication.get("primary_location") or {} + best_oa_location = publication.get("best_oa_location") or {} + open_access = publication.get("open_access") or {} + + for url in ( + primary_location.get("pdf_url"), + best_oa_location.get("pdf_url"), + primary_location.get("landing_page_url"), + best_oa_location.get("landing_page_url"), + open_access.get("oa_url"), + ): + if url: + return url + + doi = publication.get("doi") + if doi: + return doi if doi.startswith("http") else f"https://doi.org/{doi}" + + return publication.get("id") + + +def _collect_funders_from_publications( + results: list[dict], + author_id: str, + funder_counts: dict[str, dict[str, Any]], +) -> None: + for hit in results: + publication = hit.get("_source", {}) + if not _publication_has_funder_data(publication): + continue + + publication_id = publication.get("id") + publication_url = publication.get("publication_url") or _resolve_publication_url(publication) + author_position = _get_author_position_in_publication(publication, author_id) + publication_funders: set[tuple[str, str | None, str | None]] = set() + + for funder in publication.get("funders", []): + funder_id = funder.get("id") + funder_name = funder.get("display_name") + if funder_id or funder_name: + key = funder_id or funder_name + publication_funders.add((key, funder_id, funder_name)) + + for award in publication.get("awards", []): + funder_id = award.get("funder_id") + funder_name = award.get("funder_display_name") + if funder_id or funder_name: + key = funder_id or funder_name + publication_funders.add((key, funder_id, funder_name)) + + for key, funder_id, funder_name in publication_funders: + if key not in funder_counts: + funder_counts[key] = { + "funder_id": funder_id, + "funder_name": funder_name, + "publication_count": 0, + "author_position_count": { + "first": 0, + "middle": 0, + "last": 0, + "unknown": 0, + }, + "publication_ids": { + "first": [], + "middle": [], + "last": [], + "unknown": [], + }, + "publication_urls": {}, + "publication_titles": {}, + } + + entry = funder_counts[key] + entry["publication_count"] += 1 + entry["author_position_count"][author_position] += 1 + entry["publication_ids"][author_position].append(publication_id) + if publication_id and publication_url: + entry["publication_urls"][publication_id] = publication_url + if publication_id: + title = publication.get("display_name") or publication.get("title") or publication_id + entry["publication_titles"][publication_id] = title + diff --git a/service/src/main/inse/funders/model.py b/service/src/main/inse/funders/model.py new file mode 100644 index 00000000..982737b3 --- /dev/null +++ b/service/src/main/inse/funders/model.py @@ -0,0 +1,44 @@ +from typing import Any + +from pydantic import BaseModel + + +class PublicationsByAuthorResponse(BaseModel): + author_id: str + page: int + page_size: int + total_works: int + total: int + results_count: int + results: list[dict[str, Any]] + + +class PublicationIdsByAuthorPosition(BaseModel): + first: list[str] = [] + middle: list[str] = [] + last: list[str] = [] + unknown: list[str] = [] + + +class AuthorPositionCount(BaseModel): + first: int = 0 + middle: int = 0 + last: int = 0 + unknown: int = 0 + + +class FunderByAuthor(BaseModel): + funder_id: str | None = None + funder_name: str | None = None + publication_count: int + author_position_count: AuthorPositionCount + publication_ids: PublicationIdsByAuthorPosition + publication_urls: dict[str, str] = {} + publication_titles: dict[str, str] = {} + + +class FundersByAuthorResponse(BaseModel): + author_id: str + author_name: str | None = None + funder_count: int + funders: list[FunderByAuthor] diff --git a/service/src/main/inse/funders/service.py b/service/src/main/inse/funders/service.py new file mode 100644 index 00000000..b6c8c05f --- /dev/null +++ b/service/src/main/inse/funders/service.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + REST API for author publications and funding. +""" +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Query + +from . import logic +from . import model + + +router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"]) + + +@router.get( + "/{author_id}/publications", + operation_id="getPublicationsByAuthor", + response_model=model.PublicationsByAuthorResponse, + summary="Get funded publications by author.", +) +async def get_publications_by_author( + author_id: str, + page: Annotated[int, Query(ge=1)] = 1, + page_size: Annotated[int, Query(ge=1, le=1000)] = 200, +): + return await logic.get_publications_by_author_id(author_id, page, page_size) + + +@router.get( + "/{author_id}/funders", + operation_id="getFundersByAuthor", + response_model=model.FundersByAuthorResponse, + summary="Get funding organizations by author.", +) +async def get_funders_by_author(author_id: str): + return await logic.get_funders_by_author_id(author_id) diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py new file mode 100644 index 00000000..1c519224 --- /dev/null +++ b/service/src/main/inse/funders/test_logic.py @@ -0,0 +1,263 @@ +import json + +import httpx +import pytest +from fastapi import HTTPException + +from inse.funders import logic +from inse.funders.elastic_search_client import FundedPublicationsSearchClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def _funded_publication_hit( + work_id: str, + *, + funder_id: str | None = "https://openalex.org/F123", + funder_name: str | None = "Example Funder", + author_position: str = "first", + award_funder_id: str | None = None, + award_funder_name: str | None = None, + pdf_url: str | None = None, +) -> dict: + source: dict = { + "id": work_id, + "primary_location": { + "pdf_url": pdf_url, + }, + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5023888391", + "display_name": "Example Author", + }, + "author_position": author_position, + } + ], + "funders": [], + "awards": [], + } + if funder_id or funder_name: + source["funders"].append( + { + "id": funder_id, + "display_name": funder_name, + } + ) + if award_funder_id or award_funder_name: + source["awards"].append( + { + "funder_id": award_funder_id, + "funder_display_name": award_funder_name, + } + ) + return {"_source": source} + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content.decode("utf-8")) + assert payload["from"] == 0 + return httpx.Response( + 200, + json={ + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + author_position="first", + pdf_url="https://example.org/w1.pdf", + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + author_position="last", + ), + ], + }, + }, + ) + + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type( + "Result", + (), + {"results": [type("Author", (), {"display_name": "Example Author"})()]}, + )(), + ) + + client = FundedPublicationsSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + response = await logic.get_funders_by_author_id("A5023888391", client=client) + + assert response.author_id == "https://openalex.org/A5023888391" + assert response.author_name == "Example Author" + assert response.funder_count == 1 + assert response.funders[0].funder_id == "https://openalex.org/F123" + assert response.funders[0].funder_name == "Funder A" + assert response.funders[0].publication_count == 2 + assert response.funders[0].author_position_count.first == 1 + assert response.funders[0].author_position_count.last == 1 + assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"] + assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"] + assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" + assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch): + requested_pages: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content.decode("utf-8")) + size = payload["size"] + offset = payload["from"] + page = offset // size + 1 + requested_pages.append(page) + total = size + 1 + if page == 1: + hits = [ + _funded_publication_hit( + f"https://openalex.org/W{i}", + funder_id=f"https://openalex.org/F{i}", + funder_name=f"Funder {i}", + ) + for i in range(1, size + 1) + ] + else: + hits = [ + _funded_publication_hit( + f"https://openalex.org/W{total}", + funder_id=f"https://openalex.org/F{total}", + funder_name=f"Funder {total}", + ) + ] + + return httpx.Response( + 200, + json={ + "hits": { + "total": {"value": total}, + "hits": hits, + }, + }, + ) + + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type("Result", (), {"results": []})(), + ) + + client = FundedPublicationsSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + response = await logic.get_funders_by_author_id("A5023888391", client=client) + + assert requested_pages == [1, 2] + assert response.funder_count > 1 + funder_names = {funder.funder_name for funder in response.funders} + assert "Funder 1" in funder_names + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Bundesministerium", + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + ), + ], + }, + }, + ) + + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type("Result", (), {"results": []})(), + ) + + client = FundedPublicationsSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + response = await logic.get_funders_by_author_id("A5093075883", client=client) + + assert response.funder_count == 1 + assert response.funders[0].funder_name == "Bundesministerium" + assert response.funders[0].publication_count == 1 + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={"hits": {"total": {"value": 0}, "hits": []}}, + ) + + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type("Result", (), {"results": []})(), + ) + + client = FundedPublicationsSearchClient( + base_url="https://project.nes.uni-due.de/elastic", + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + response = await logic.get_funders_by_author_id("A5093075883", client=client) + + assert response.funder_count == 0 + assert response.funders == [] + + +@pytest.mark.anyio +async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch): + monkeypatch.setattr( + logic.person_logic, + "search_persons", + lambda author_id: type("Result", (), {"results": []})(), + ) + client = FundedPublicationsSearchClient(api_key="") + + with pytest.raises(HTTPException) as exc: + await logic.get_funders_by_author_id("A5023888391", client=client) + + assert exc.value.status_code == 503 diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 3d744ad9..2bb78629 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -10,8 +10,10 @@ def search( query: dict = None, source = None, size: int = None, + offset:int = None, sort: list = None, body: dict = None, + track_total_hits = False ) -> dict[str, Any]: headers = { @@ -27,8 +29,12 @@ def search( payload["_source"] = source if size is not None: payload["size"] = size + if offset is not None: + payload["from"] = offset if sort is not None: payload["sort"] = sort + if track_total_hits: + payload["track_total_hits"] = True else: payload = { "query": { @@ -49,22 +55,23 @@ def search( return response.json() def get( index: str, - doc_id:str, - body: dict = None, - + doc_id: str, + source: list = None, ) -> dict[str, Any]: headers = { "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", "Content-Type": "application/json" } - payload = body - - # get document directly + + params = {} + if source is not None: + params["_source_includes"] = ",".join(source) + with httpx.Client() as client: response = client.get( f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}", - json=payload, + params=params, headers=headers ) response.raise_for_status() diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 8ec7a76d..6cf4ed22 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -1,5 +1,4 @@ -from typing import Any -import httpx +from openai import OpenAI, APIConnectionError from .. import config @@ -7,26 +6,35 @@ def call( system_prompt: str, user_prompt: str, model: str = None, - stream: bool = False, - timeout: int = 30 + timeout: int = 30, + temperature: float = 1.0, + top_p: float = 0.95, ) -> str: - headers = { - "Authorization": f"Bearer {config.settings.llm_api_token}", - "Content-Type": "application/json" - } - if model is None: model = config.settings.llm_model - payload = { - "model": model, - "prompt": f"{system_prompt}\n{user_prompt}", - "stream": stream - } + client = OpenAI( + base_url=config.settings.llm_api_url, + api_key=config.settings.llm_api_key, + timeout=timeout, + ) - with httpx.Client(timeout=timeout) as client: - response = client.post(config.settings.llm_api_url, json=payload, headers=headers) - response.raise_for_status() - data = response.json() - return data.get("response", "") + try: + response = client.chat.completions.create( + model=model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ], + + temperature=temperature, + top_p=top_p, + extra_body={"top_k": 64}, + ) + except APIConnectionError: + return "Etwas ist schiefgelaufen. Bitte versuche es später erneut." + + return response.choices[0].message.content or ( + "Etwas ist schiefgelaufen. Bitte versuche es erneut." + ) diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 688c81d9..353626d6 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -12,23 +12,14 @@ from typing import Type from sqlalchemy.orm import Session from sqlalchemy import select from sqlalchemy import func -from fastapi import HTTPException import logging import httpx import json -import time from . import schema from . import model from . import config -from .integrations import elasticsearch -from .integrations import llm -from . import util -from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError -from inse.models.author import Author -from inse.models.authors_list_response import AuthorsListResponse -from inse.models.meta import Meta from inse.models.topic import Topic from inse.models.topic_subfield import TopicSubfield from inse.models.topic_field import TopicField @@ -38,20 +29,6 @@ from inse.models.topic_domain import TopicDomain logger = logging.getLogger(__name__) -def _init_es_client() -> Optional[Elasticsearch]: - es_url = config.settings.elasticsearch_url - if not es_url: - logger.warning("Elasticsearch URL not configured; skipping client init.") - return None - client = Elasticsearch( - hosts=[str(es_url)], - api_key=config.settings.elasticsearch_api_key, - ) - logger.info("Elasticsearch client initialized with URL: %s", es_url) - return client - - -es_client = _init_es_client() topic_cache_filename: str = "topic_hierarchy_cache.json" @@ -113,8 +90,12 @@ def insert_element(db: Session, value: S) -> S: def _load_topic_cache() -> dict: """Loads the topic hierarchy cache from a JSON file.""" + import os try: cache_path = "/data/" + topic_cache_filename + if not os.path.exists(cache_path): + current_dir = os.path.dirname(__file__) + cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename) with open(cache_path, "r", encoding="utf-8") as f: return json.load(f) except Exception as exc: @@ -250,202 +231,56 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict: return counts - -### persons - - -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 - elif query: - query_field = "display_name" - query_value = query - else: - return AuthorsListResponse(results=[], meta=Meta(count=0)) - - data = elasticsearch.search( - index="openalex-authors", query_field=query_field, query_value=query_value - ) - - authors = [] - for hit in data.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - source_copy = dict(source) - source_copy["id"] = source_copy.get("id") or hit.get("_id", "") - - # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) - ids = source_copy.get("ids") - if isinstance(ids, dict): - ids_copy = dict(ids) - for str_field in ["openalex", "orcid", "scopus"]: - val = ids_copy.get(str_field) - if val is not None and not isinstance(val, str): - ids_copy[str_field] = str(val) - source_copy["ids"] = ids_copy - - author = Author.from_dict(source_copy) - if author: - authors.append(author) - - return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) - - -def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: - start_time = time.time() - search_result = search_persons(author_id=author_id) - if not search_result.results: - return "No person found." - if len(search_result.results) > 1: - return "Multiple persons found, cannot generate bio." - - person = search_result.results[0] - person_json = json.dumps(person.model_dump_json()) - - system_prompt = """\ - Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person. - - Gehe dabei auf folgende drei Punkte ein: - - 1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema) - 2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung? - 3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend? - - Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\ +def get_topic_hierarchy() -> dict: """ - - user_prompt = f"Daten zur Person:\n{person_json}" - - headers = { - "Authorization": f"Bearer {config.settings.llm_api_key}", - "Content-Type": "application/json", - } - payload = { - "model": config.settings.llm_model, - "prompt": f"{system_prompt}\n{user_prompt}", - "stream": False, - } - - with httpx.Client(timeout=30.0) as client: - response = client.post( - config.settings.llm_api_url, json=payload, headers=headers - ) - response.raise_for_status() - data = response.json() - bio = data.get("response", "") - - elapsed_time = time.time() - start_time - logger.info( - f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds" - ) - - return bio - -def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: - body = { - "_source":include.split(",") if include else True, - } - - try: - hit = elasticsearch.get( - index="openalex-authors", - body=body, - doc_id=author_id - ) - except NotFoundError: - raise HTTPException( - status_code=404, detail=f"Person with id {author_id} not found" - ) - - except ApiError as e: - raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") - persons = [util.get_persons_data(hit)] - - return AuthorsListResponse(results=persons) - - -def search_persons_by_name( - author_name: str, limit: Optional[int] = 10, include: Optional[str] = None -) -> AuthorsListResponse: - if not author_name: - raise HTTPException(status_code=400, detail="name must be provided") - - search_query = { - "bool": { - "should": [ - {"match_phrase": {"display_name": {"query": author_name, "boost": 5}}}, - { - "match_phrase_prefix": { - "display_name": {"query": author_name, "boost": 3} - } - }, - # { - # "match": { - # "display_name": { - # "query": author_name, - # "fuzziness": 1 - # } - # } - # } - ], - "minimum_should_match": 1, - } - } - try: - response = elasticsearch.search( - index="openalex-authors", - query=search_query, - source=include.split(",") if include else True, - size=limit, - ) - - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) - - hits = response.get("hits", {}).get("hits", []) - - persons = [util.get_persons_data(hit) for hit in hits] - - return AuthorsListResponse(results=persons) - - -def search_persons_by_institution( - institution_name: str, limit: Optional[int] = 10, include: Optional[str] = None -) -> AuthorsListResponse: - - if not institution_name: - raise HTTPException(status_code=400, detail="institution_name must be provided") - - search_query = { - "nested": { - "path": "affiliations", - "query": { - "match_phrase": { - "affiliations.institution.display_name": institution_name - } - }, - } - } - try: - response = elasticsearch.search( - index="openalex-authors", - query=search_query, - source=include.split(",") if include else True, - size=limit, - sort=[{"works_count": {"order": "desc"}}], - ) - - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) - - hits = response.get("hits", {}).get("hits", []) - persons = [util.get_persons_data(hit) for hit in hits] - return AuthorsListResponse(results=persons) + Builds and returns a hierarchical tree structure of topics: + Domains -> Fields -> Subfields -> Topics + """ + flat_cache = _load_topic_cache() + tree = {} + + for topic_name, info in flat_cache.items(): + domain = info.get("domain") or "Unbekannter Bereich" + field = info.get("field") or "Unbekanntes Feld" + subfield = info.get("subfield") or "Unbekanntes Teilfeld" + topic_id = info.get("topic_id", "") + + # Clean topic ID to just be the trailing ID or keep full URL + # For querying, display name is used in persons search, but ID is useful + + if domain not in tree: + tree[domain] = {} + if field not in tree[domain]: + tree[domain][field] = {} + if subfield not in tree[domain][field]: + tree[domain][field][subfield] = [] + + tree[domain][field][subfield].append({ + "id": topic_id, + "name": topic_name + }) + + formatted_domains = [] + for d_name, d_fields in tree.items(): + formatted_fields = [] + for f_name, f_subfields in d_fields.items(): + formatted_subfields = [] + for sf_name, sf_topics in f_subfields.items(): + sf_topics.sort(key=lambda x: x["name"]) + formatted_subfields.append({ + "name": sf_name, + "topics": sf_topics + }) + formatted_subfields.sort(key=lambda x: x["name"]) + formatted_fields.append({ + "name": f_name, + "subfields": formatted_subfields + }) + formatted_fields.sort(key=lambda x: x["name"]) + formatted_domains.append({ + "name": d_name, + "fields": formatted_fields + }) + formatted_domains.sort(key=lambda x: x["name"]) + + return {"domains": formatted_domains} diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 41d776c2..4e0e62d2 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -12,6 +12,8 @@ from fastapi.responses import RedirectResponse from fastapi.middleware.cors import CORSMiddleware from inse.collaboration_network.router import router as collaboration_network_router from inse.works.service import router as works_service_router +from inse.persons.service import router as persons_service_router +from inse.funders.service import router as funders_service_router from . import config from .service import router as service_router @@ -32,6 +34,8 @@ app = FastAPI( ) app.include_router(collaboration_network_router) app.include_router(works_service_router) +app.include_router(persons_service_router) +app.include_router(funders_service_router) app.include_router(service_router) app.include_router(account_router) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index aaac61b1..669f049f 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -36,8 +36,5 @@ class Page(BaseModel, Generic[T]): class ItemPage(Page[Item]): pass -class PersonBio(BaseModel): - bio: str = Field(description="The generated biography.") - diff --git a/service/src/main/inse/models/topic_count.py b/service/src/main/inse/models/topic_count.py index 3e0d1f1e..fa4a2fcf 100644 --- a/service/src/main/inse/models/topic_count.py +++ b/service/src/main/inse/models/topic_count.py @@ -1,6 +1,9 @@ +from typing import Optional + from pydantic import BaseModel, Field class TopicCount(BaseModel): + id: Optional[str] = Field(default=None, description="The topic id.") name: str = Field(description="The topic display name.") count: int = Field(default=0, description="The number of occurrences.") diff --git a/service/src/main/inse/persons/__init__.py b/service/src/main/inse/persons/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py new file mode 100644 index 00000000..a4dc5c0f --- /dev/null +++ b/service/src/main/inse/persons/logic.py @@ -0,0 +1,435 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for persons / authors. +""" + +import json +import logging +import time +from typing import Optional, Callable, Any, List +import hashlib +import httpx +from fastapi import HTTPException +from .. import config +from .. import util +from ..integrations import llm +from inse.models.author import Author +from inse.models.authors_list_response import AuthorsListResponse +from inse import util +from inse.integrations import elasticsearch +from inse.models.meta import Meta +from inse.persons.query_builder import build_authors_search +from inse.persons.model import CustomAuthor, CustomAuthorsListResponse, PersonSearchRequest +logger = logging.getLogger(__name__) +INDEX_NAME="openalex-authors" + +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 + elif query: + query_field = "display_name" + query_value = query + else: + return AuthorsListResponse(results=[], meta=Meta(count=0)) + + data = elasticsearch.search( + index="openalex-authors", query_field=query_field, query_value=query_value + ) + + authors = [] + for hit in data.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source_copy = dict(source) + source_copy["id"] = source_copy.get("id") or hit.get("_id", "") + + # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) + ids = source_copy.get("ids") + if isinstance(ids, dict): + ids_copy = {} + orcid_val = ids.get("orcid") + if orcid_val: + ids_copy["orcid"] = str(orcid_val) + source_copy["ids"] = ids_copy + + author = Author.from_dict(source_copy) + if author: + authors.append(author) + + return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) + + + +def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: + start_time = time.time() + search_result = search_persons(author_id=author_id) + if not search_result.results: + return "No person found." + if len(search_result.results) > 1: + return "Multiple persons found, cannot generate bio." + + person = search_result.results[0] + person_json = json.dumps(person.model_dump_json()) + + system_prompt = """\ + Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person. + + Gehe dabei auf folgende drei Punkte ein: + + 1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema) + 2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung? + 3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend? + + Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\ + """ + + user_prompt = f"Daten zur Person:\n{person_json}" + + bio = llm.call(system_prompt, user_prompt) + + elapsed_time = time.time() - start_time + logger.info( + f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds" + ) + + return bio + +def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: + body = { + "_source":include.split(",") if include else True, + } + + try: + hit = elasticsearch.get( + index="openalex-authors", + body=body, + doc_id=author_id + ) + except NotFoundError: + raise HTTPException( + status_code=404, detail=f"Person with id {author_id} not found" + ) + + except ApiError as e: + raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") + persons = [util.get_persons_data(hit)] + + return AuthorsListResponse(results=persons) + + + +def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: + body = { + "_source":include.split(",") if include else True, + } + + try: + hit = elasticsearch.get( + index="openalex-authors", + body=body, + doc_id=author_id + ) + except NotFoundError: + raise HTTPException( + status_code=404, detail=f"Person with id {author_id} not found" + ) + + except ApiError as e: + raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") + persons = [util.get_persons_data(hit)] + + return AuthorsListResponse(results=persons) + + +def search_persons_by_name( + author_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None +) -> AuthorsListResponse: + if not author_name: + raise HTTPException(status_code=400, detail="name must be provided") + search_query = { + "bool": { + "should": [ + {"match_phrase": {"display_name": {"query": author_name, "boost": 5}}}, + { + "match_phrase_prefix": { + "display_name": {"query": author_name, "boost": 3} + } + }, + # { + # "match": { + # "display_name": { + # "query": author_name, + # "fuzziness": 1 + # } + # } + # } + ], + "minimum_should_match": 1, + } + } + try: + response = elasticsearch.search( + index="openalex-authors", + query=search_query, + offset=page_offset, + source=include.split(",") if include else True, + size=limit, + track_total_hits=True + ) + + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Elasticsearch search failed: {str(e)}" + ) + total_count = response.get("hits",{}).get("total",{}).get("value",0) + hits = response.get("hits", {}).get("hits", []) + + persons = [util.get_persons_data(hit) for hit in hits] + + return AuthorsListResponse(results=persons,meta=Meta(count=total_count,page=page_offset)) + + +def search_persons_autocomplete(author_name: str, limit: Optional[int] = 5, include: Optional[str] = None) -> AuthorsListResponse: + if not author_name: + raise HTTPException( + status_code=400, + detail="name must be provided" + ) + search_query = { + "function_score": { + "query": { + "wildcard": { + "display_name.keyword": { + "value": author_name + "*", + "case_insensitive": True + } + } + }, + "functions": [ + { + "script_score": { + "script": { + "lang": "painless", + "source": "String name = doc['display_name.keyword'].value.toLowerCase(); String[] parts = name.splitOnToken(' '); Set unique = new HashSet(); for (String p : parts) { unique.add(p); } return unique.size() > 1 ? 1.0 : 0.3;" + } + } + } + ], + "boost_mode": "multiply" + } + } + collapse ={ + "field":"display_name.keyword" + } + body = { + "size":limit, + "query":search_query, + "_source":include.split(",") if include else True, + "sort":[{"works_count": {"order": "desc"}}], + "collapse":collapse + } + try: + response = elasticsearch.search( + index="openalex-authors", + body=body + ) + except Exception as e: + raise HTTPException( + status_code=500, + detail=f"Elasticsearch search failed: {str(e)}" + ) + + hits = response.get("hits", {}).get("hits", []) + + persons = [] + for hit in hits: + fields = hit.get("fields",{}) + source = hit.get("_source",{}) + source_copy = dict (source) + source_copy["id"] = hit.get("_id", "") or source_copy.get("id") + + # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) + ids = source_copy.get("ids") + if isinstance(ids, dict): + ids_copy = {} + orcid_val = ids.get("orcid") + if orcid_val: + ids_copy["orcid"] = str(orcid_val) + source_copy["ids"] = ids_copy + + for key,value in fields.items(): + source_copy[key] = value + author = Author.from_dict(source_copy) + persons.append(author) + + return AuthorsListResponse(results=persons) + +def search_persons_by_institution( + institution_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None +) -> AuthorsListResponse: + + if not institution_name: + raise HTTPException(status_code=400, detail="institution_name must be provided") + + search_query = { + "nested": { + "path": "last_known_institutions", + "query": { + "bool": { + "must": [ + { + "match_phrase": { + "last_known_institutions.display_name": institution_name + } + } + ] + } + } + } + } + try: + response = elasticsearch.search( + index="openalex-authors", + query=search_query, + source=include.split(",") if include else True, + size=limit, + offset=page_offset, + sort=[{"works_count": {"order": "desc"}}], + track_total_hits=True + ) + + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Elasticsearch search failed: {str(e)}" + ) + total_count = response.get("hits",{}).get("total",{}).get("value",0) + hits = response.get("hits", {}).get("hits", []) + persons = [util.get_persons_data(hit) for hit in hits] + return AuthorsListResponse(results=persons,meta=Meta(count=total_count,page=page_offset)) + +def _enrich_author_data(author_data) -> Optional[CustomAuthor]: + if not author_data: + return None + if not isinstance(author_data, dict): + if hasattr(author_data, 'model_dump'): + author_data = author_data.model_dump() + elif hasattr(author_data, 'to_dict'): + author_data = author_data.to_dict() + else: + return None + author_id = author_data.get("id", "") or "" + # Not implemented yet + h = int(hashlib.md5(author_id.encode('utf-8')).hexdigest(), 16) + + + # Experimental suitability rating + suitability_score = h % 100 + if suitability_score < 15: + relevance_rating = "Sehr geeignet" + elif suitability_score < 50: + relevance_rating = "Geeignet" + else: + relevance_rating = "Möglich" + + # Resilient sanitization of IDs to protect against model type conflicts (Generated) TODO: multiple code occurrences (e.g. in util.py) => refactor into seperate utility function (if required, after all merges) + ids = author_data.get("ids") + if isinstance(ids, dict): + ids_copy = {} + orcid_val = ids.get("orcid") + if orcid_val: + ids_copy["orcid"] = str(orcid_val) + author_data["ids"] = ids_copy + + base_author = Author.from_dict(author_data) + if not base_author: + return None + + author = CustomAuthor( + **base_author.model_dump(), + relevance_rating=relevance_rating, + ) + return author + +def advanced_search_persons( + query: Optional[str] = None, + institution_name: Optional[str] = None, + topics: Optional[List[str]] = None, + page: int = 1, + page_size: int = 10, + include: Optional[set[str]] = None, + strict: Optional[bool] = False, + filter_mode: Optional[str] = "from", + filter_year: Optional[int] = None, +) -> CustomAuthorsListResponse: + try: + query_body = build_authors_search( + query=query, + institution_name=institution_name, + topics=topics, + page=page, + page_size=page_size, + include=include, + strict=strict, + track_total_hits = True, + filter_mode=filter_mode, + filter_year=filter_year + ) + response_dict = elasticsearch.search( + index=INDEX_NAME, + body=query_body, + ) + except httpx.HTTPStatusError as e: + if e.response.status_code == 404: + logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") + return CustomAuthorsListResponse( + results=[], + meta=Meta( + count=0, + page=page, + per_page=page_size + ) + ) + elif e.response.status_code == 400: + logger.error(f"Elasticsearch request error: {str(e)}") + raise HTTPException( + status_code=400, detail=f"Elasticsearch request error: {str(e)}" + ) + else: + logger.error(f"Elasticsearch API error: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Elasticsearch API error: {str(e)}" + ) + except httpx.RequestError as e: + logger.error(f"Elasticsearch connection/request error: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}" + ) + except Exception as e: + logger.error(f"Elasticsearch search failed: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Elasticsearch search failed: {str(e)}" + ) + total_count = response_dict.get("hits",{}).get("total",{}).get("value",0) + hits = response_dict.get("hits", {}).get("hits", []) + total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) + + results = [] + for hit in hits: + raw_data = util.get_persons_data(hit) + custom_author = _enrich_author_data(raw_data) + if custom_author: + results.append(custom_author) + + return CustomAuthorsListResponse( + results=results, + meta=Meta( + count=total_count, + page=page, + per_page=page_size + ) + ) diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py new file mode 100644 index 00000000..19e57cec --- /dev/null +++ b/service/src/main/inse/persons/model.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Data models for persons / authors. +""" + +from pydantic import BaseModel +from pydantic import Field +from typing import List, Optional +from inse.models.author import Author +from inse.models.meta import Meta +from inse.models.authors_list_response import AuthorsListResponse + +from inse.models.group_by_result import GroupByResult + + +class CustomAuthor(Author): + relevance_rating: Optional[str] = Field( + default=None, description="The relevance suitability rating." + ) + + +class CustomAuthorsListResponse(AuthorsListResponse): + foo_author: Optional[CustomAuthor] = None + # meta: Optional[Meta] = None + # results: Optional[List[CustomAuthor]] = None + # group_by: Optional[List[GroupByResult]] = None + + +class PersonBio(BaseModel): + bio: str = Field(description="The generated biography.") + + +class PersonFilters(BaseModel): + institution: Optional[str] = None + cited_by_count: Optional[int] = None + # more filters + + +class PersonSearchRequest(BaseModel): + name: Optional[str] = None + filters: PersonFilters = PersonFilters() + include: Optional[str] = None + limit: Optional[int] = 10 + page_offset: Optional[int] = 0 diff --git a/service/src/main/inse/persons/query_builder.py b/service/src/main/inse/persons/query_builder.py new file mode 100644 index 00000000..279bfb98 --- /dev/null +++ b/service/src/main/inse/persons/query_builder.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +from typing import List, Optional, Set, Any + +def build_authors_search( + using: Any = None, + index: Optional[str] = None, + query: Optional[str] = None, + institution_name: Optional[str] = None, + topics: Optional[List[str]] = None, + page: int = 1, + page_size: int = 10, + include: Optional[Set[str]] = None, + strict: Optional[bool] = False, + track_total_hits: Optional[bool] = False, + filter_mode: Optional[str] = "from", + filter_year: Optional[int] = None +) -> dict: + """ + Builds an Elasticsearch search request query body for authors as a dictionary. + """ + # 1. Build Query Clauses + query_clause = None + if query: + query_clause = { + "bool": { + "should": [ + { + "match_phrase": { + "display_name": { + "query": query, + "boost": 5 + } + } + }, + { + "match_phrase_prefix": { + "display_name": { + "query": query, + "boost": 3 + } + } + }, + { + "match": { + "display_name": { + "query": query, + "fuzziness": 1 + } + } + } + ], + "minimum_should_match": 1 + } + } + + # 2. Build Filters + filter_clauses = [] + + # Filter against false entries (nested ((Works > 2 AND Year > 2020) OR has last_known_institution)) + filter_clauses.append({ + "bool": { + "should": [ + { + "bool": { + "filter": [ + { + "range": { "works_count": { "gt": 2 } } + }, + { + "nested": { + "path": "counts_by_year", + "query": { + "range": { "counts_by_year.year": { "gt": 2020 } } # hardcoded for now + } + } + } + ] + } + }, + { + "nested": { + "path": "last_known_institutions", + "query": { + "exists": { + "field": "last_known_institutions.id" + } + } + } + } + + ], + "minimum_should_match": 1 + } + }) + # Institution filter with optional year-based filtering + if institution_name: + if filter_year is not None: + target_year = filter_year + mode = filter_mode or "from" + else: + from datetime import datetime + current_year = datetime.now().year + target_year = current_year - 1 + mode = "from" + + range_query = {"gte": target_year} + if mode == "in": + range_query["lte"] = target_year + + if strict: + filter_clauses.append({ + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + { + "match_phrase": { + "affiliations.institution.display_name": institution_name + } + }, + { + "range": { + "affiliations.years": range_query + } + } + ] + } + } + } + }) + else: + filter_clauses.append({ + "bool": { + "filter": [ + { + "nested": { + "path": "last_known_institutions", + "query": { + "match_phrase": { + "last_known_institutions.display_name": institution_name + } + } + } + }, + { + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + { + "match_phrase": { + "affiliations.institution.display_name": institution_name + } + }, + { + "range": { + "affiliations.years": range_query + } + } + ] + } + } + } + } + ] + } + }) + + if topics: + for t in topics: + if t: + filter_clauses.append({ + "nested": { + "path": "topics", + "query": { + "match_phrase": { + "topics.display_name": t + } + } + } + }) + + # Combine query and filters + body = {} + if query_clause: + if filter_clauses: + body["query"] = { + "bool": { + "must": [query_clause], + "filter": filter_clauses + } + } + else: + body["query"] = query_clause + else: + if filter_clauses: + body["query"] = { + "bool": { + "filter": filter_clauses + } + } + else: + body["query"] = { + "match_all": {} + } + + # 3. Source Filtering + if include: + body["_source"] = list(include) + else: + body["_source"] = True + + # 4. Pagination + es_size = page_size + es_from = (page - 1) * page_size + body["from"] = es_from + body["size"] = es_size + body["track_total_hits"] = track_total_hits + + # 5. Sorting + if not query: + body["sort"] = [ + {"cited_by_count": {"order": "desc"}}, + {"works_count": {"order": "desc"}} + ] + + return body + diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py new file mode 100644 index 00000000..c442b578 --- /dev/null +++ b/service/src/main/inse/persons/service.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for persons / authors. +""" + +from typing import Annotated, Optional + +from fastapi import APIRouter +from fastapi import Path +from fastapi import Query +from typing import List +from . import logic +from . import model +from inse.models.authors_list_response import AuthorsListResponse + + +router = APIRouter( + prefix="/api/inse-service", + tags=["Persons"], + responses={404: {"description": "Not found"}}, +) + + +@router.get( + "/persons/search", + operation_id="searchPersons", + response_model=AuthorsListResponse, + summary="Searches for persons by ID or name.", + response_model_exclude_none=True, +) +def search_persons( + author_id: Annotated[ + str, Query(description="OpenAlex author ID (e.g., A5093075883)") + ] = None, + query: Annotated[ + str, Query(description="Search query (e.g., Arman AND Arzani)") + ] = None, + include: Annotated[ + Optional[str], + Query( + description=( + "Comma-separated include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, sources, counts_by_year, works_api_url, dates, " + "cited_by_count_boost" + ), + example="topics_full,topic_share", + ), + ] = None, +): + include_set = ( + {tag.strip().lower() for tag in include.split(",") if tag.strip()} + if include + else None + ) + return logic.search_persons(author_id, query, include_set) + + +@router.get( + "/persons/bio", + operation_id="generatePersonBio", + response_model=model.PersonBio, + summary="Generates a bio for a person by author ID.", +) +def generate_person_bio( + author_id: Annotated[ + str, Query(description="OpenAlex author ID (e.g., A5093075883)") + ], + include: Annotated[ + Optional[str], + Query( + description=("Comma-separated list to include tags"), + example="topics_full,topic_share", + ), + ] = None, +): + include_set = ( + {tag.strip().lower() for tag in include.split(",") if tag.strip()} + if include + else None + ) + bio = logic.generate_person_bio(author_id, include_set) + return model.PersonBio(bio=bio) + +@router.get( + "/person/{id}", + operation_id="getPersonByID", + response_model=AuthorsListResponse, + summary="Searches for person by ID.", + tags=["Persons"], +) +def get_person_by_id( + id: Annotated[ + str, Path(description="OpenAlex author ID", examples=["A5093075883"]) + ], + include: Annotated[ + Optional[str], + Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share", + ), + ], +): + return logic.get_person_by_id(author_id=id, include=include) + + +@router.get( + "/persons/searchByName", + operation_id="searchPersonsByName", + response_model=AuthorsListResponse, + summary="Searches for person by name.", + tags=["Persons"], +) +def search_persons_by_name( + author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], + include: Annotated[ + Optional[str], + Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share", + ), + ], + limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, + page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, +): + return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit) + +@router.get( + '/persons/autocomplete', + operation_id='searchPersonsAutocomplete', + response_model=AuthorsListResponse, + summary='Searches for person by name.', + tags=[ 'Persons' ]) +def search_persons_autocomplete( + author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], + include : Annotated[Optional[str], Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share" + )]): + return logic.search_persons_autocomplete(author_name=author_name,include=include) + + +@router.get( + "/persons/searchByInstitution", + operation_id="searchPersonsByInstitution", + response_model=AuthorsListResponse, + summary="Searches for persons by institution name.", + tags=["Persons"], +) +def search_persons_by_institution( + institution_name: Annotated[ + str, Query(description="Institution name (e.g., MIT, Oxford University)") + ], + include: Annotated[ + Optional[str], + Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share", + ), + ], + limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, + page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, +): + return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit) + +@router.get( + "/persons/search-list", + operation_id="searchPersonsList", + response_model=model.CustomAuthorsListResponse, + summary="Searches for persons with advanced filters (Topic & Institution) and pagination.", + response_model_exclude_none=True, + tags=["Persons"], +) +def search_persons_list( + query: Annotated[ + Optional[str], Query(description="Search query (e.g., Arman AND Arzani)") + ] = None, + institution_name: Annotated[ + Optional[str], Query(alias="institutionName", description="Filter by institution name") + ] = None, + topic: Annotated[ + Optional[List[str]], Query(description="Filter by topic display names") + ] = None, + page: Annotated[ + int, Query(description="Page number (1-indexed)", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Results per page", ge=1, le=100) + ] = 10, + include: Annotated[ + Optional[str], + Query( + description="Comma-separated include tags", + example="topics_full,topic_share", + ), + ] = None, + strict: Annotated[ + Optional[bool], Query(description="Strict institution search by target year") + ] = False, + filter_mode: Annotated[ + Optional[str], Query(alias="filterMode", description="Filter mode: 'in' or 'from'") + ] = "from", + filter_year: Annotated[ + Optional[int], Query(alias="filterYear", description="Filter year") + ] = None, +): + include_set = ( + {tag.strip().lower() for tag in include.split(",") if tag.strip()} + if include + else None + ) + return logic.advanced_search_persons( + query=query, + institution_name=institution_name, + topics=topic, + page=page, + page_size=page_size, + include=include_set, + strict=strict, + filter_mode=filter_mode, + filter_year=filter_year, + ) diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 76f59946..6e3dadc5 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -27,9 +27,7 @@ from . import schema from . import database from . import security from . import util -from .works import service as works_service -from inse.models.authors_list_response import AuthorsListResponse logger = logging.getLogger(__name__) @@ -44,7 +42,6 @@ router = APIRouter( responses={404: {"description": "Not found"}}, ) - # @app.get("/", include_in_schema=False) # async def show_api(): # return RedirectResponse("api") @@ -212,141 +209,12 @@ def count_topic_hierarchy( ): return logic.count_topic_hierarchy(topic_names) - -### persons - - @router.get( - "/persons/search", - operation_id="searchPersons", - response_model=AuthorsListResponse, - summary="Searches for persons by ID or name.", - response_model_exclude_none=True, - tags=["Persons"], + "/topics/hierarchy", + operation_id="getTopicHierarchy", + response_model=dict, + summary="Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).", + tags=["Topics"], ) -def search_persons( - author_id: Annotated[ - str, Query(description="OpenAlex author ID (e.g., A5093075883)") - ] = None, - query: Annotated[ - str, Query(description="Search query (e.g., Arman AND Arzani)") - ] = None, - include: Annotated[ - Optional[str], - Query( - description=( - "Comma-separated include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, sources, counts_by_year, works_api_url, dates, " - "cited_by_count_boost" - ), - example="topics_full,topic_share", - ), - ] = None, -): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) - return logic.search_persons(author_id, query, include_set) - - -@router.get( - "/persons/bio", - operation_id="generatePersonBio", - response_model=model.PersonBio, - summary="Generates a bio for a person by author ID.", - tags=["Persons"], -) -def generate_person_bio( - author_id: Annotated[ - str, Query(description="OpenAlex author ID (e.g., A5093075883)") - ], - include: Annotated[ - Optional[str], - Query( - description=("Comma-separated list to include tags"), - example="topics_full,topic_share", - ), - ] = None, -): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) - bio = logic.generate_person_bio(author_id, include_set) - return model.PersonBio(bio=bio) - - -@router.get( - "/person/{id}", - operation_id="getPersonByID", - response_model=AuthorsListResponse, - summary="Searches for person by ID.", - tags=["Persons"], -) -def get_person_by_id( - id: Annotated[ - str, Path(description="OpenAlex author ID", examples=["A5093075883"]) - ], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], -): - return logic.get_person_by_id(author_id=id, include=include) - - -@router.get( - "/persons/searchByName", - operation_id="searchPersonsByName", - response_model=AuthorsListResponse, - summary="Searches for person by name.", - tags=["Persons"], -) -def search_persons_by_name( - author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], -): - return logic.search_persons_by_name(author_name=author_name, include=include) - - -@router.get( - "/persons/searchByInstitution", - operation_id="searchPersonsByInstitution", - response_model=AuthorsListResponse, - summary="Searches for persons by institution name.", - tags=["Persons"], -) -def search_persons_by_institution( - institution_name: Annotated[ - str, Query(description="Institution name (e.g., MIT, Oxford University)") - ], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], -): - return logic.search_persons_by_institution(institution_name, include=include) +def get_topic_hierarchy(): + return logic.get_topic_hierarchy() diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index da4fc410..645e2235 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -28,11 +28,10 @@ def get_persons_data(hit:dict): # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) ids = source_copy.get("ids") if isinstance(ids, dict): - ids_copy = dict(ids) - for str_field in ["openalex", "orcid", "scopus"]: - val = ids_copy.get(str_field) - if val is not None and not isinstance(val, str): - ids_copy[str_field] = str(val) + ids_copy = {} + orcid_val = ids.get("orcid") + if orcid_val: + ids_copy["orcid"] = str(orcid_val) source_copy["ids"] = ids_copy author = Author.from_dict(source_copy) diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 98648398..467410b7 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -90,6 +90,32 @@ async def get_all_author_works( ) +async def get_primary_topic_counts( + author_id: str, + client: OpenAlexWorksSearchClient | None = None, +) -> List[TopicCount]: + works = await get_all_author_works(author_id, client=client) + + counts = {} + + for work in works.results or []: + primary_topic = work.primary_topic + if not primary_topic or not primary_topic.display_name: + continue + + name = primary_topic.display_name + if name not in counts: + counts[name] = {"id": primary_topic.id, "name": name, "count": 0} + counts[name]["count"] += 1 + + items = sorted(counts.values(), key=lambda item: item["count"], reverse=True) + + return [ + TopicCount(id=item["id"], name=item["name"], count=item["count"]) + for item in items + ] + + async def get_topics_by_time_by_author( author_id: str, max_topics_per_year: int = 3, @@ -117,45 +143,57 @@ async def get_topics_by_time_by_author( for topic in work.topics or []: if topic.display_name: topic_name = topic.display_name + topic_id = topic.id if topic_name not in years[year]["topics"]: - years[year]["topics"][topic_name] = 0 + years[year]["topics"][topic_name] = { + "id": topic_id, + "name": topic_name, + "count": 0, + } - years[year]["topics"][topic_name] += 1 + years[year]["topics"][topic_name]["count"] += 1 primary_topic = work.primary_topic if primary_topic and primary_topic.display_name: primary_topic_name = primary_topic.display_name + primary_topic_id = primary_topic.id if primary_topic_name not in years[year]["primary_topics"]: - years[year]["primary_topics"][primary_topic_name] = 0 - - years[year]["primary_topics"][primary_topic_name] += 1 + years[year]["primary_topics"][primary_topic_name] = { + "id": primary_topic_id, + "name": primary_topic_name, + "count": 0, + } + years[year]["primary_topics"][primary_topic_name]["count"] += 1 + elements = [] for year in sorted(years.keys()): - topic_items = list(years[year]["topics"].items()) - topic_items.sort(key=lambda item: item[1], reverse=True) + topic_items = list(years[year]["topics"].values()) + topic_items.sort(key=lambda item: item["count"], reverse=True) topics = [] - for topic_name, count in topic_items[:max_topics_per_year]: + for topic in topic_items[:max_topics_per_year]: topics.append(TopicCount( - name=topic_name, - count=count, + id=topic["id"], + name=topic["name"], + count=topic["count"], )) - primary_topic_items = list(years[year]["primary_topics"].items()) - primary_topic_items.sort(key=lambda item: item[1], reverse=True) + primary_topic_items = list(years[year]["primary_topics"].values()) + primary_topic_items.sort(key=lambda item: item["count"], reverse=True) primary_topics = [] - for topic_name, count in primary_topic_items[:max_topics_per_year]: + for topic in primary_topic_items[:max_topics_per_year]: primary_topics.append(TopicCount( - name=topic_name, - count=count, + id=topic["id"], + name=topic["name"], + count=topic["count"], )) elements.append(TopicsByYear( diff --git a/service/src/main/inse/works/model.py b/service/src/main/inse/works/model.py index db5baf59..8c0a8eee 100644 --- a/service/src/main/inse/works/model.py +++ b/service/src/main/inse/works/model.py @@ -8,333 +8,11 @@ from typing import List from typing import Optional from pydantic import BaseModel -from pydantic import ConfigDict from pydantic import Field from inse.models.work import Work -class OpenAlexModel(BaseModel): - model_config = ConfigDict(extra="allow") - - -class Source(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The source id.") - display_name: Optional[str] = Field( - default=None, description="The source display name." - ) - issn_l: Optional[str] = Field(default=None, description="The linking ISSN.") - issn: Optional[List[str]] = Field( - default=None, description="The ISSNs of the source." - ) - is_oa: Optional[bool] = Field( - default=None, description="Whether the source is open access." - ) - is_in_doaj: Optional[bool] = Field( - default=None, description="Whether the source is in DOAJ." - ) - is_core: Optional[bool] = Field( - default=None, description="Whether the source is a core source." - ) - host_organization: Optional[str] = Field( - default=None, description="The host organization id." - ) - host_organization_name: Optional[str] = Field( - default=None, description="The host organization name." - ) - host_organization_lineage: Optional[List[str]] = Field( - default=None, description="The host organization lineage." - ) - type: Optional[str] = Field(default=None, description="The source type.") - - -class Location(OpenAlexModel): - is_oa: Optional[bool] = Field( - default=None, description="Whether this location is open access." - ) - landing_page_url: Optional[str] = Field( - default=None, description="The landing page URL." - ) - pdf_url: Optional[str] = Field(default=None, description="The PDF URL.") - source: Optional[Source] = Field( - default=None, description="The publication source." - ) - license: Optional[str] = Field(default=None, description="The license label.") - license_id: Optional[str] = Field(default=None, description="The license id.") - is_accepted: Optional[bool] = Field( - default=None, description="Whether this manuscript is accepted." - ) - is_published: Optional[bool] = Field( - default=None, description="Whether this manuscript is published." - ) - - -class OpenAccess(OpenAlexModel): - is_oa: Optional[bool] = Field( - default=None, description="Whether the work is open access." - ) - oa_url: Optional[str] = Field(default=None, description="The open access URL.") - any_repository_has_fulltext: Optional[bool] = Field( - default=None, description="Whether a repository has full text." - ) - - -class Author(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The author id.") - display_name: Optional[str] = Field( - default=None, description="The display name of the author." - ) - orcid: Optional[str] = Field( - default=None, description="The optional ORCID of the author." - ) - - -class Institution(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The institution id.") - display_name: Optional[str] = Field( - default=None, description="The institution display name." - ) - ror: Optional[str] = Field(default=None, description="The ROR id.") - country_code: Optional[str] = Field(default=None, description="The country code.") - type: Optional[str] = Field(default=None, description="The institution type.") - lineage: Optional[List[str]] = Field( - default=None, description="The institution lineage." - ) - - -class Authorship(OpenAlexModel): - author: Optional[Author] = Field(default=None, description="The author.") - institutions: List[Institution] = Field( - default_factory=list, description="The author's institutions." - ) - countries: List[str] = Field( - default_factory=list, description="The author's countries." - ) - is_corresponding: Optional[bool] = Field( - default=None, description="Whether this author is corresponding." - ) - raw_author_name: Optional[str] = Field( - default=None, description="The raw author name." - ) - raw_affiliation_strings: List[str] = Field( - default_factory=list, description="The raw affiliation strings." - ) - - -class WorkIds(OpenAlexModel): - openalex: Optional[str] = Field(default=None, description="The OpenAlex id.") - doi: Optional[str] = Field(default=None, description="The DOI.") - mag: Optional[int] = Field(default=None, description="The MAG id.") - pmid: Optional[str] = Field(default=None, description="The PubMed id.") - pmcid: Optional[str] = Field(default=None, description="The PubMed Central id.") - - -class Biblio(OpenAlexModel): - volume: Optional[str] = Field(default=None, description="The volume.") - issue: Optional[str] = Field(default=None, description="The issue.") - first_page: Optional[str] = Field(default=None, description="The first page.") - last_page: Optional[str] = Field(default=None, description="The last page.") - - -class TopicLevel(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The topic level id.") - display_name: Optional[str] = Field( - default=None, description="The topic level display name." - ) - - -class Topic(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The topic id.") - display_name: Optional[str] = Field( - default=None, description="The topic display name." - ) - score: Optional[float] = Field(default=None, description="The topic score.") - subfield: Optional[TopicLevel] = Field( - default=None, description="The topic subfield." - ) - field: Optional[TopicLevel] = Field(default=None, description="The topic field.") - domain: Optional[TopicLevel] = Field(default=None, description="The topic domain.") - - -class Keyword(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The keyword id.") - display_name: Optional[str] = Field( - default=None, description="The keyword display name." - ) - score: Optional[float] = Field(default=None, description="The keyword score.") - - -class Funder(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The funder id.") - display_name: Optional[str] = Field( - default=None, description="The funder display name." - ) - ror: Optional[str] = Field(default=None, description="The ROR id.") - - -class Award(OpenAlexModel): - id: Optional[str] = Field(default=None, description="The award id.") - display_name: Optional[str] = Field( - default=None, description="The award display name." - ) - funder_award_id: Optional[str] = Field( - default=None, description="The funder award id." - ) - funder_id: Optional[str] = Field(default=None, description="The funder id.") - funder_display_name: Optional[str] = Field( - default=None, description="The funder display name." - ) - doi: Optional[str] = Field(default=None, description="The award DOI.") - - -class CitationNormalizedPercentile(OpenAlexModel): - value: Optional[float] = Field( - default=None, description="The normalized citation percentile." - ) - is_in_top_1_percent: Optional[bool] = Field( - default=None, description="Whether the work is in the top 1 percent." - ) - is_in_top_10_percent: Optional[bool] = Field( - default=None, description="Whether the work is in the top 10 percent." - ) - - -class CitedByPercentileYear(OpenAlexModel): - min: Optional[int] = Field(default=None, description="The minimum percentile year.") - max: Optional[int] = Field(default=None, description="The maximum percentile year.") - - -class CountByYear(OpenAlexModel): - year: Optional[int] = Field(default=None, description="The year.") - cited_by_count: int = Field( - default=0, description="The citation count for the year." - ) - - -class SustainableDevelopmentGoal(OpenAlexModel): - id: Optional[str] = Field( - default=None, description="The sustainable development goal id." - ) - display_name: Optional[str] = Field( - default=None, description="The sustainable development goal display name." - ) - score: Optional[float] = Field( - default=None, description="The sustainable development goal score." - ) - - -class Mesh(OpenAlexModel): - descriptor_ui: Optional[str] = Field(default=None, description="The descriptor UI.") - descriptor_name: Optional[str] = Field( - default=None, description="The descriptor name." - ) - qualifier_ui: Optional[str] = Field(default=None, description="The qualifier UI.") - qualifier_name: Optional[str] = Field( - default=None, description="The qualifier name." - ) - is_major_topic: Optional[bool] = Field( - default=None, description="Whether this is a major topic." - ) - - -class HasContent(OpenAlexModel): - pdf: Optional[bool] = Field(default=None, description="Whether PDF content exists.") - grobid_xml: Optional[bool] = Field( - default=None, description="Whether GROBID XML content exists." - ) - - -# class Work(OpenAlexModel): -# id: str = Field(description="The external id of the work.") -# doi: Optional[str] = Field( -# default=None, description="The optional DOI of the work." -# ) -# title: Optional[str] = Field(default=None, description="The title of the work.") -# display_name: Optional[str] = Field( -# default=None, description="The display name of the work." -# ) -# publication_year: Optional[int] = Field( -# default=None, description="The publication year." -# ) -# publication_date: Optional[str] = Field( -# default=None, description="The publication date." -# ) -# type: Optional[str] = Field(default=None, description="The work type.") -# language: Optional[str] = Field(default=None, description="The work language.") -# cited_by_count: int = Field(default=0, description="The number of citations.") -# is_retracted: Optional[bool] = Field( -# default=None, description="Whether the work is retracted." -# ) -# is_paratext: Optional[bool] = Field( -# default=None, description="Whether the work is paratext." -# ) -# primary_location: Optional[Location] = Field( -# default=None, description="The primary location." -# ) -# locations: List[Location] = Field( -# default_factory=list, description="The work locations." -# ) -# best_oa_location: Optional[Location] = Field( -# default=None, description="The best open access location." -# ) -# open_access: Optional[OpenAccess] = Field( -# default=None, description="Open access information." -# ) -# authorships: List[Authorship] = Field( -# default_factory=list, description="The authorships." -# ) -# ids: Optional[WorkIds] = Field(default=None, description="External ids.") -# biblio: Optional[Biblio] = Field( -# default=None, description="Bibliographic information." -# ) -# abstract_inverted_index: dict[str, List[int]] = Field( -# default_factory=dict, description="The inverted abstract index." -# ) -# referenced_works: List[str] = Field( -# default_factory=list, description="Referenced work ids." -# ) -# referenced_works_count: int = Field( -# default=0, description="The number of referenced works." -# ) -# related_works: List[str] = Field( -# default_factory=list, description="Related work ids." -# ) -# topics: List[Topic] = Field(default_factory=list, description="The topics.") -# primary_topic: Optional[Topic] = Field( -# default=None, description="The primary topic." -# ) -# keywords: List[Keyword] = Field(default_factory=list, description="The keywords.") -# funders: List[Funder] = Field(default_factory=list, description="The funders.") -# awards: List[Award] = Field(default_factory=list, description="The awards.") -# fwci: Optional[float] = Field( -# default=None, description="The field weighted citation impact." -# ) -# citation_normalized_percentile: Optional[CitationNormalizedPercentile] = Field( -# default=None, description="The normalized citation percentile." -# ) -# cited_by_percentile_year: Optional[CitedByPercentileYear] = Field( -# default=None, description="The cited by percentile year." -# ) -# counts_by_year: List[CountByYear] = Field( -# default_factory=list, description="Citation counts by year." -# ) -# sustainable_development_goals: List[SustainableDevelopmentGoal] = Field( -# default_factory=list, description="Sustainable development goals." -# ) -# mesh: List[Mesh] = Field(default_factory=list, description="MeSH terms.") -# indexed_in: List[str] = Field( -# default_factory=list, description="Indexes containing the work." -# ) -# has_content: Optional[HasContent] = Field( -# default=None, description="Available content flags." -# ) -# content_url: Optional[str] = Field(default=None, description="The content URL.") -# created_date: Optional[str] = Field(default=None, description="The creation date.") -# updated_date: Optional[str] = Field( -# default=None, description="The last update timestamp." -# ) - - class WorkSummary(BaseModel): doi: Optional[str] = Field( default=None, description="The optional DOI of the work." diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 476f2b9a..127b69a5 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -17,6 +17,7 @@ from .. import security from . import logic from inse.models.work_page import WorkPage from inse.models.works_list_response import WorksListResponse +from inse.models.topic_count import TopicCount from inse.models.topics_by_time import TopicsByTime @@ -71,6 +72,17 @@ async def get_all_author_works( return await logic.get_all_author_works(author_id) +@router.get("/{author_id}/primary-topic-counts", + operation_id="getPrimaryTopicCountsByAuthor", + response_model=list[TopicCount], + summary="Returns work counts per primary topic for an author.") +async def get_primary_topic_counts( + author_id: Annotated[str, Path(description="The author id, for example A5023888391.")], + principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])), +): + return await logic.get_primary_topic_counts(author_id) + + @router.get("/{author_id}/topics-by-time", operation_id="getTopicsByTimeByAuthor", response_model=TopicsByTime, diff --git a/service/uv.lock b/service/uv.lock index b0828716..8564595c 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -145,6 +145,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a2/7b/b0d330852dd5953daee6b15f742f15d9f18e9c0154eb4cfcc8718f0436da/cryptography-42.0.8-cp39-abi3-win_amd64.whl", hash = "sha256:fa76fbb7596cc5839320000cdd5d0955313696d9511debab7ee7278fc8b5c84a", size = 2886038, upload-time = "2024-06-04T19:54:18.707Z" }, ] +[[package]] +name = "distro" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722, upload-time = "2023-12-24T09:54:32.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, +] + [[package]] name = "dotenv" version = "0.9.9" @@ -311,6 +320,97 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "jiter" +version = "0.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/b5/55f06bb281d92fb3cc86d14e1def2bd908bb77693183e7cb1f5a3c388b0c/jiter-0.15.0.tar.gz", hash = "sha256:4251acc80e2b7c9b7b8823456ea0fceeb0734dac2df7636d3c711b38476b5a76", size = 166640, upload-time = "2026-05-19T10:09:48.361Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/44/53/4f6bddbcde3c71e56d0aa1337ec95950f3d27dd4153e25aadf0feac71751/jiter-0.15.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:0e90a1c315a0226ec822d973817967f9223b7701546c8c2a7913e7ab0926294d", size = 308793, upload-time = "2026-05-19T10:07:35.25Z" }, + { url = "https://files.pythonhosted.org/packages/01/84/c01099b59a285a1ebba64ae93f62bfa036675340fd1b0045ae65890a0442/jiter-0.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8c9004af7c8d67cce7f1aae1026fb55607f4aa600710d08ede3a3ce4aeefe7e0", size = 309570, upload-time = "2026-05-19T10:07:36.919Z" }, + { url = "https://files.pythonhosted.org/packages/58/64/8fb7f9d45bb98190355454cd04dad8d8f27223d6bd52f83af07f637168a6/jiter-0.15.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c210f8b35dc6f30aafd4b4365ca89b9d1189f21ab49b8e68fa6322a847aef138", size = 336783, upload-time = "2026-05-19T10:07:38.694Z" }, + { url = "https://files.pythonhosted.org/packages/c3/b6/f5739011d009b3a30f6a53c5240979030ba29ae46a8c67e3a15759f7c37d/jiter-0.15.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5f30bae8bc1c2d613e28e5af3e8cceb09b742f1c8a8a5f839fb67afaffc03b61", size = 363555, upload-time = "2026-05-19T10:07:40.832Z" }, + { url = "https://files.pythonhosted.org/packages/e5/12/98a9d9f766665e8a3b6252454e17cb0c464606a28cf2fa09399b003345fa/jiter-0.15.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c60e71b6d10cfc284c9bf36bd885e8d44c46f688ce50aa91b5edd90181dea687", size = 452255, upload-time = "2026-05-19T10:07:42.62Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d5/60f972840f79c5e7544fce567c56f1e4e50468f996baba3e78d823dd62a6/jiter-0.15.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0ab068bce62a45aa3e7367eceaffb5dde60b7eb853be8dece45132e3d0ff4879", size = 373559, upload-time = "2026-05-19T10:07:44.201Z" }, + { url = "https://files.pythonhosted.org/packages/ee/cf/d46ef1234ba335aabc2f013210db8e0821a22f5e644a2e9449df199ecc23/jiter-0.15.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fa248c9eb220197d363f688818dac2fd4b2f0cd7d843ca7105d652034823427d", size = 346055, upload-time = "2026-05-19T10:07:46.005Z" }, + { url = "https://files.pythonhosted.org/packages/f0/63/4d2749d8d54d230bad9b3a6b0d00cc28c6ff6b2fdffc26a8ccf76cc5a974/jiter-0.15.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:2a77aadd57cac1682e4401a72724d2796d89a4ba129b1a5812aa94ee480826eb", size = 351406, upload-time = "2026-05-19T10:07:47.855Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b9/9965b990035d8773328e0a8c8b457a87bf2b19f6c4126d9d99296be5d16a/jiter-0.15.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2ae901f3a55bfafdde31d289590fa25e3245735a2b1e8c7cc15871710a002871", size = 389357, upload-time = "2026-05-19T10:07:49.665Z" }, + { url = "https://files.pythonhosted.org/packages/2d/55/9ddf903deda1413e87fed792f416b7123daee5b8efbad6a202a7421c36a5/jiter-0.15.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:f0b271b462769543716f92d3a4f90527df6ef5ed05ee95ec4137f513e21e1b77", size = 517263, upload-time = "2026-05-19T10:07:51.537Z" }, + { url = "https://files.pythonhosted.org/packages/e8/76/a0c40ad064d3a20a4fde231e35d56e9a01ce82164278180e82d5daf85469/jiter-0.15.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:2fb6a5d26af81fc0f00f9360a891e05cf755e149bba391c4d563adc54812973d", size = 548646, upload-time = "2026-05-19T10:07:53.196Z" }, + { url = "https://files.pythonhosted.org/packages/23/4f/eca9b954942916ba2f453891b8593ab444cd872396fe66a3936616f236f3/jiter-0.15.0-cp312-cp312-win32.whl", hash = "sha256:c2f6bb8b5216ab9e7873bc08b5d7bef2b8abbb578a3069bf1cd14a45d71d771d", size = 206427, upload-time = "2026-05-19T10:07:55.307Z" }, + { url = "https://files.pythonhosted.org/packages/95/bf/8ead82a87495149542748e828d153fd232a512a22c83b02c4815c1a9c7d8/jiter-0.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:40b2c7e92c44a84d748d21706c68dc6ff8161d80b59c99d774721a0d2317d7c7", size = 197300, upload-time = "2026-05-19T10:07:56.651Z" }, + { url = "https://files.pythonhosted.org/packages/f4/e4/9b8a78fb2d894471bc344e37f1949bdd784bd914d031dba0ba3a40c71dd7/jiter-0.15.0-cp312-cp312-win_arm64.whl", hash = "sha256:cc0bc345cf2df9d1c00ac443f50d543c1ccfa8b0422cb85b1ab70d681c0b255b", size = 192702, upload-time = "2026-05-19T10:07:58.307Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f4/f708c900ecee41b2025ef8413d5351e5649eb2125c506f6720cc69b06f5c/jiter-0.15.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1c11465f97e2abf45a014b83b730222f8f1c5335e802c7055a67d50de6f1f4e3", size = 307829, upload-time = "2026-05-19T10:07:59.704Z" }, + { url = "https://files.pythonhosted.org/packages/86/59/db537c0949e83668c38481d426b9f2fd5ab758c4ee53a811dd0a510626a0/jiter-0.15.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d1e7b1776f0797956c509e123d0952d10d293a9492dea9f288ab9570ec01d1a5", size = 308445, upload-time = "2026-05-19T10:08:01.184Z" }, + { url = "https://files.pythonhosted.org/packages/37/38/ea0e13b18c30ef951da0d47d39e7fa9edb82a93a62990ffbd7cea9b622d4/jiter-0.15.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:351a341c2105aa430b7047e30f1bf7975f6313b00165d3fc07be2edaf741f279", size = 336181, upload-time = "2026-05-19T10:08:02.688Z" }, + { url = "https://files.pythonhosted.org/packages/58/fc/2303901b16c4ba05865588990a420c0b4156270b44379c20931544a1d962/jiter-0.15.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4ab395feec8d249ec4044e228e98a7033f043426a265df439dc3698823f0a4e4", size = 362985, upload-time = "2026-05-19T10:08:04.394Z" }, + { url = "https://files.pythonhosted.org/packages/5b/6f/11bace093c52e7d4d26c8e606ccd7ae8c972189622469ec0d9e28161e28b/jiter-0.15.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a2a438005b6f22d0273413484d6094d7c2c5d10ec1b3a3bf128e0d1d3ba53258", size = 453292, upload-time = "2026-05-19T10:08:05.967Z" }, + { url = "https://files.pythonhosted.org/packages/22/db/987f2f086ca4d7a6582eb4ccd513f9b26b42d9e4243a087609a3137a8fc7/jiter-0.15.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f18f85e4218d1b40f000f42a92239a7a61a902cd42c65e6c360dbd17dcb20894", size = 373501, upload-time = "2026-05-19T10:08:07.857Z" }, + { url = "https://files.pythonhosted.org/packages/8f/7c/89fbcabb2739b7a5b8dc959a1b6c5761f6484f5fed3486854b3c789bb1de/jiter-0.15.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1aa62e277fc1cbd80e6deacae6f4d983b41b3d7728e0645c5d741a6149bba45", size = 344683, upload-time = "2026-05-19T10:08:09.431Z" }, + { url = "https://files.pythonhosted.org/packages/30/6f/6cca7692e7dddfec6d8d76c54dc97f2af2a41df4ac0674b999df1f09a5f3/jiter-0.15.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:6550fa135c7deb8ead6af49ed7ff648532ea8334a1447fe34a36315ef79c5c29", size = 350892, upload-time = "2026-05-19T10:08:11.352Z" }, + { url = "https://files.pythonhosted.org/packages/39/14/0338d6190cb8e6d22e677ab1d4eabd4117f67cca70c54cd04b82ff64e068/jiter-0.15.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:066f8f33f18b2419cd8213b2436fa7fbc9c499f315971cfa3ce1f9820c001b1b", size = 388723, upload-time = "2026-05-19T10:08:12.912Z" }, + { url = "https://files.pythonhosted.org/packages/90/31/cc19f4a1bdb6afb09ce6a2f2615aa8d44d994eba0d8e6105ed1af920e736/jiter-0.15.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:75e8a04e91432dde9f1838373cf93d23726c79d3e908d319acf0e796f85592e7", size = 516648, upload-time = "2026-05-19T10:08:14.808Z" }, + { url = "https://files.pythonhosted.org/packages/49/9f/833c541512cd091b63c10c0381973dfe11bc7a503a818c16384417e0c81e/jiter-0.15.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:a97261f1fccb8e50ecd2890a96e46efdc3f57c80a197324c6777827231eca712", size = 547382, upload-time = "2026-05-19T10:08:16.927Z" }, + { url = "https://files.pythonhosted.org/packages/d2/11/e7b70e91f90bc4477e8eee9e8a5f7cf3cb41b4525d6394dc98a714eb8f7f/jiter-0.15.0-cp313-cp313-win32.whl", hash = "sha256:c77496cb10bd7549690fbbab3e5ec05857b83e49276f4a9423a766ddd2afcd4c", size = 205845, upload-time = "2026-05-19T10:08:18.401Z" }, + { url = "https://files.pythonhosted.org/packages/4b/23/5c20d9ad6f02c493e4023e5d2d09e1c1f15fe2753c9102c544aff068a88e/jiter-0.15.0-cp313-cp313-win_amd64.whl", hash = "sha256:b15741f501469009ae0ae90b7147958a664a7dede40aa7ff174a8a4645f546d0", size = 196842, upload-time = "2026-05-19T10:08:20.131Z" }, + { url = "https://files.pythonhosted.org/packages/6b/11/1eb400ef248e8c925fd883fbe325daf5e42cd1b0d308539dd332bd4f7ffc/jiter-0.15.0-cp313-cp313-win_arm64.whl", hash = "sha256:5d6a60072b44c3c2b797a7ddcbcbbf2b34ea3cfd4721580fbfd2a09d9d9b84ba", size = 192212, upload-time = "2026-05-19T10:08:21.807Z" }, + { url = "https://files.pythonhosted.org/packages/8a/60/2fd8d7c79da8acf9b7b277c7616847773779356b92acfc9bb158452174da/jiter-0.15.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:ef1fd24d9413f6209e00d3d5a453e67acfe004a25cc6c8e8484faed4311ab9e8", size = 315065, upload-time = "2026-05-19T10:08:23.218Z" }, + { url = "https://files.pythonhosted.org/packages/46/f4/008fb7d65e8ac2abf00811651a661e025c4ba80bbc6f378450384ddd3aed/jiter-0.15.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:144f8e72cb53dab146347b91cceac01f5481237f2b93b4a339a1ee8f8878b67c", size = 339444, upload-time = "2026-05-19T10:08:24.701Z" }, + { url = "https://files.pythonhosted.org/packages/00/55/90b0c7b9c6896c0f2a591dd36d36b71d22e09674bfef178fa03ba3f81499/jiter-0.15.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:553fcac2ef2cb990877f9fc0833b8b629a3e6a5670b6b5fd58219b41a653ddc4", size = 347779, upload-time = "2026-05-19T10:08:26.408Z" }, + { url = "https://files.pythonhosted.org/packages/51/6b/69666cec5000fd57734c118437394516c749ae8dbeea9fb66d6fef9c4775/jiter-0.15.0-cp313-cp313t-win_amd64.whl", hash = "sha256:774f93f65031856bf14ad9f59bdcab8b8cad501e5ceabd51ba3525f76937a25b", size = 200395, upload-time = "2026-05-19T10:08:28.055Z" }, + { url = "https://files.pythonhosted.org/packages/39/04/a6aa62cd27e8149b0d28df5561f10f6cceaf7935a9ccf3f1c5a05f9a0cd8/jiter-0.15.0-cp313-cp313t-win_arm64.whl", hash = "sha256:f1e1754960f38ec40613a07e5e372df67acb3b890fb383b6fb3de3e49ddbf3c7", size = 190516, upload-time = "2026-05-19T10:08:29.35Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/079f350ebf7859d081de30aa890f9e3be68516f754f3ba32366ffff4dcee/jiter-0.15.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:ac0d9ddea4350974be7a221fc25895f251a8fee748c889bdced2141c0fec1a49", size = 308884, upload-time = "2026-05-19T10:08:31.667Z" }, + { url = "https://files.pythonhosted.org/packages/04/4e/a2c30a7f69b48c03b20935d647479106fe932f6e63f75faf53937197e05d/jiter-0.15.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:01a8222cf05ab1128e239421156c207949808acaaea2bdfd33130ae666786e86", size = 310028, upload-time = "2026-05-19T10:08:33.304Z" }, + { url = "https://files.pythonhosted.org/packages/40/90/2e7cdfd3cf8ca967be38c48f5cf474d79f089efaf559a40f15984a77ae69/jiter-0.15.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:182226cbc930c9fab81bc2e41a4da672f89539906dadb05e75670ac07b94f71f", size = 337485, upload-time = "2026-05-19T10:08:35.259Z" }, + { url = "https://files.pythonhosted.org/packages/9b/11/15a1aa28b120b8ee5b4f1fb894c125046225f09847738bd64233d3b84883/jiter-0.15.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:71683c38c825452999b5717fcae07ea708e8c93003e808be4319c1b02e3d176e", size = 364223, upload-time = "2026-05-19T10:08:36.694Z" }, + { url = "https://files.pythonhosted.org/packages/b7/25/f442e8af5f3d0dcf47b39e83a0efd9ee45ea946aa6d04625dc3181eae3b6/jiter-0.15.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:30f2218e6a9e5c18bc10fe6d41ac189c442c88eacf11bad9f28ef95a9bef00e6", size = 456387, upload-time = "2026-05-19T10:08:38.143Z" }, + { url = "https://files.pythonhosted.org/packages/da/f4/37f2d2c9f64f49af7da652ed7532bb5a2372e588e6927c3fdd76f911db65/jiter-0.15.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5157de9f76eb4bc5ea74a1219366a25f945ad305641d74e04f59c54087091aa9", size = 374461, upload-time = "2026-05-19T10:08:39.869Z" }, + { url = "https://files.pythonhosted.org/packages/60/28/edcfbbbf0cb15436f36664a8908a0df47ab9006298d4cd937dc08ea932d6/jiter-0.15.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:90c5db5527c221249a876160663ab891ace358c17f7b9c93ec1478b7f0550e5c", size = 345924, upload-time = "2026-05-19T10:08:41.668Z" }, + { url = "https://files.pythonhosted.org/packages/47/13/89fba6398dab7f202b7278c4b4aac122399d2c0183971c4a57a3b7088df5/jiter-0.15.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:3e4540b8e74e4268811ac05db226a6a128ff572e7e0ce3f1163b693cadb184cd", size = 352283, upload-time = "2026-05-19T10:08:43.091Z" }, + { url = "https://files.pythonhosted.org/packages/1b/da/0f6af8cef2c565a1ab44d970f268c43ccaa72707386ea6388e6fe2b6cd26/jiter-0.15.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:62ebd14e47e9aed9df4472afcb2663668ce4d74891cd54f86bf6e44029d6dc89", size = 389985, upload-time = "2026-05-19T10:08:44.915Z" }, + { url = "https://files.pythonhosted.org/packages/a1/ec/b9cb7d6d29e24ee14910266157d2a279d7a8f60ee0df7fa840882976ba64/jiter-0.15.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:0be6f5ad41a809f303f416d17cec92a7a725902fb9b4f3de3d19362ac0ef8554", size = 517695, upload-time = "2026-05-19T10:08:46.486Z" }, + { url = "https://files.pythonhosted.org/packages/64/5e/6d1bda880723aae0ad86b4b763f044362448efe31e3e819635d41cb03451/jiter-0.15.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:813dfbb17d65328bf86e5f0905dd277ba2265d3ca20556e86c0c7035b7182e5a", size = 548868, upload-time = "2026-05-19T10:08:48.026Z" }, + { url = "https://files.pythonhosted.org/packages/0c/72/7de501cf38dcacaf35098796f3a50e0f2e338baba18a58946c618544b809/jiter-0.15.0-cp314-cp314-win32.whl", hash = "sha256:50e51156192722a9c58db112837d3f8ef96fb3c5ecc14e95f409134b08b158ec", size = 206380, upload-time = "2026-05-19T10:08:49.738Z" }, + { url = "https://files.pythonhosted.org/packages/1e/a9/e19addf4b0c1bdce52c6da12351e6bc42c340c45e7c09e2158e46d293ccc/jiter-0.15.0-cp314-cp314-win_amd64.whl", hash = "sha256:30ce1a5d16b5641dc935d50ef775af6a0871e3d14ab05d6fc54dff371b78e558", size = 197687, upload-time = "2026-05-19T10:08:51.088Z" }, + { url = "https://files.pythonhosted.org/packages/f2/c9/776b1db01db25fc6c1d58d1979a37b0a9fe787e5f5b1d062d2eaacb77923/jiter-0.15.0-cp314-cp314-win_arm64.whl", hash = "sha256:510c8b3c17a0ed9ac69850c0438dada3c9b82d9c4d589fcb62002a5a9cf3a866", size = 192571, upload-time = "2026-05-19T10:08:52.451Z" }, + { url = "https://files.pythonhosted.org/packages/a0/f6/45bb4670bacf300fd2c7abadbfb3af376e5f1b6ae75fd9bc069891d15870/jiter-0.15.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7553333dd0930c104a5a0db8df72bf7219fe663d731383b576bb6ed6351c984d", size = 317151, upload-time = "2026-05-19T10:08:53.867Z" }, + { url = "https://files.pythonhosted.org/packages/d7/68/ed635ad5acd7b73e454283083bbb7c8205ad10e88b0d9d7d793b09fe8226/jiter-0.15.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2143ab06181d2b029eedcb6af3cebe95f11bbac62441781860f98ee9330a6a6", size = 341243, upload-time = "2026-05-19T10:08:55.383Z" }, + { url = "https://files.pythonhosted.org/packages/5d/db/3ff4176b817b8ea33879e71e13d8bc2b0d481a7ed3fe9e080f333d415c16/jiter-0.15.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6eac374c5c975709b69c10f09afd199df74150172156ad10c8d4fd785b7da995", size = 363629, upload-time = "2026-05-19T10:08:56.928Z" }, + { url = "https://files.pythonhosted.org/packages/ab/24/5f8270e0ba9c883582f96f722f8a0b58015c7ce1f8c6d4571cf394e99b6b/jiter-0.15.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b3b3b775e33d3bfaec9899edc526ae97b0da0bf9d071a46124ba419149a414f8", size = 456198, upload-time = "2026-05-19T10:08:58.618Z" }, + { url = "https://files.pythonhosted.org/packages/45/5b/76fc02b0b5c54c3d18c60653156e2f76fde1816f9b4722db68d6ee2c897e/jiter-0.15.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eda3071db3346334beae1360b46da4606da57bf3528c167b3c38533afaf9f2c5", size = 373710, upload-time = "2026-05-19T10:09:00.151Z" }, + { url = "https://files.pythonhosted.org/packages/c4/52/4310821b0ea9277994d3e1f49fc6a4b34e4800caebacb2c0af81da59a454/jiter-0.15.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c6694a173ecabc12eb60efbc0b474464ead1951ff65cd8b1e72100715c64512b", size = 349901, upload-time = "2026-05-19T10:09:01.621Z" }, + { url = "https://files.pythonhosted.org/packages/93/fe/67648c35b3594fba8854ac64cc8a826d8bcd18324bbdb53d77697c60b6ef/jiter-0.15.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:a254e10b593624d230c365b6d616b22ca0ad65e63a16e6631c2b3466022e6ba8", size = 352438, upload-time = "2026-05-19T10:09:03.216Z" }, + { url = "https://files.pythonhosted.org/packages/cb/28/0a1879d07ad6b3e025a2750027363452ced93c2d16d1c9d4b153ffd51c91/jiter-0.15.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d8d2955167274e15d79a7a020afdd9b39c990eb80b2d89fca695d92dcfdd38ec", size = 388152, upload-time = "2026-05-19T10:09:04.741Z" }, + { url = "https://files.pythonhosted.org/packages/c1/78/46c6f6b56ba85c90021f4afd72ed42f691f8f84daacb5fe27277070e3858/jiter-0.15.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:acf4ee4d1fc55917239fe72972fb292dd773055d05eb040d36f4326e02cc2c0e", size = 517707, upload-time = "2026-05-19T10:09:06.231Z" }, + { url = "https://files.pythonhosted.org/packages/ca/cb/720662d4c88fcad606e826fef5424365527ba43ce4868a479aed8f8c507e/jiter-0.15.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:e7196e56f1cd69af1dbb07dff02dcfb260a50b45a82d409d92a06fedb32473b5", size = 548241, upload-time = "2026-05-19T10:09:08.093Z" }, + { url = "https://files.pythonhosted.org/packages/60/e3/935b8034fd143f21125c87d51404a9e0e1449186a494405721ff5d1d695e/jiter-0.15.0-cp314-cp314t-win32.whl", hash = "sha256:7f6163c0f10b055245f814dcc59f4818da60dfe72f3e72ab89fc24b6bd5e9c52", size = 207950, upload-time = "2026-05-19T10:09:09.616Z" }, + { url = "https://files.pythonhosted.org/packages/93/59/984fd9ece895953dad3e0880a650e766f5a2da2c5514f0eafdaaabbeb5f9/jiter-0.15.0-cp314-cp314t-win_amd64.whl", hash = "sha256:980c256edb05b78a111b99c4de3b1d32e31634b867fd1fc2cf726e7b7bba9854", size = 200055, upload-time = "2026-05-19T10:09:11.367Z" }, + { url = "https://files.pythonhosted.org/packages/0e/a4/cf8d779feb133a27a2e3bc833bccb9e13aa332cdf820497ebf72c10ce8c3/jiter-0.15.0-cp314-cp314t-win_arm64.whl", hash = "sha256:66b1880df2d01e206e8339769d1c7c1753bcb653efd6289e203f6f24ebada0c0", size = 191244, upload-time = "2026-05-19T10:09:12.74Z" }, + { url = "https://files.pythonhosted.org/packages/73/38/505941b2b092fd5bbbd60a52a880db1173f1690ae6751bed3af1c9ddcb4e/jiter-0.15.0-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:631f13a3d04e97d4e083993b10f4b99530e3a10d953e2eb5e196b7dc7f812ce0", size = 303769, upload-time = "2026-05-19T10:09:42.203Z" }, + { url = "https://files.pythonhosted.org/packages/e7/95/a06692b29e77473f286e1ec1f426d3ca44d7b5843be8ad21d7a5f3fcdcc0/jiter-0.15.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:b6c0ffae686c39bf3737be60793783267628783ea42545632c10b291105aee45", size = 305128, upload-time = "2026-05-19T10:09:43.657Z" }, + { url = "https://files.pythonhosted.org/packages/23/85/7270d7ad41d6061a25b950c6bf91d638bd9aacb113200a8c8d57a055fd67/jiter-0.15.0-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d54fb5b31dea401a41af3f8a7d2512e9b6a6a005491e6166c7e4ffab9639a9c", size = 340459, upload-time = "2026-05-19T10:09:45.452Z" }, + { url = "https://files.pythonhosted.org/packages/c8/8d/302cb2057b7513327b4d575cff6b1d066ee6431a5357fc3f8867cd684406/jiter-0.15.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:54d5d6090cdc1b7c9e780dfb04949a990adb1e301a2fc0bbcee7de4638d33f9a", size = 344469, upload-time = "2026-05-19T10:09:46.864Z" }, +] + +[[package]] +name = "openai" +version = "2.41.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "httpx" }, + { name = "jiter" }, + { name = "pydantic" }, + { name = "sniffio" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3c/a6/5815fe2e2aca74b36c650d1bd43b69827cee568073d0d2d9b6fc5aaac80c/openai-2.41.0.tar.gz", hash = "sha256:db5c362acd6604b84f076abbefa66826ea4b46ecba2954ed866e6a149a1352c0", size = 783525, upload-time = "2026-06-03T22:39:40.719Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/51/d82bb424e8aa372190c5233253a2ceb399a778747d18b42cff487411e663/openai-2.41.0-py3-none-any.whl", hash = "sha256:20cc7952e8501c7e5773dd2ef7be437bae9cb549044902e1041a83a54516e375", size = 1353378, upload-time = "2026-06-03T22:39:38.964Z" }, +] + [[package]] name = "packaging" version = "26.2" @@ -499,6 +599,7 @@ dependencies = [ { name = "elasticsearch" }, { name = "fastapi" }, { name = "httpx" }, + { name = "openai" }, { name = "pydantic" }, { name = "pydantic-settings" }, { name = "pyjwt" }, @@ -516,6 +617,7 @@ requires-dist = [ { name = "elasticsearch", specifier = "~=9.4.0" }, { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, + { name = "openai", specifier = ">=2.41.0" }, { name = "pydantic", specifier = "~=2.7.1" }, { name = "pydantic-settings", specifier = "~=2.2.1" }, { name = "pyjwt", specifier = "~=2.8.0" }, @@ -597,6 +699,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8b/0c/9d30a4ebeb6db2b25a841afbb80f6ef9a854fc3b41be131d249a977b4959/starlette-0.46.2-py3-none-any.whl", hash = "sha256:595633ce89f8ffa71a015caed34a5b2dc1c0cdb3f0f1fbd1e69339cf2abeec35", size = 72037, upload-time = "2025-04-13T13:56:16.21Z" }, ] +[[package]] +name = "tqdm" +version = "4.67.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/09/a9/6ba95a270c6f1fbcd8dac228323f2777d886cb206987444e4bce66338dd4/tqdm-4.67.3.tar.gz", hash = "sha256:7d825f03f89244ef73f1d4ce193cb1774a8179fd96f31d7e1dcde62092b960bb", size = 169598, upload-time = "2026-02-03T17:35:53.048Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/e1/3079a9ff9b8e11b846c6ac5c8b5bfb7ff225eee721825310c91b3b50304f/tqdm-4.67.3-py3-none-any.whl", hash = "sha256:ee1e4c0e59148062281c49d80b25b67771a127c85fc9676d3be5f243206826bf", size = 78374, upload-time = "2026-02-03T17:35:50.982Z" }, +] + [[package]] name = "typing-extensions" version = "4.15.0" diff --git a/webapp/openapitools.json b/webapp/openapitools.json index 061602d3..7af6e36f 100644 --- a/webapp/openapitools.json +++ b/webapp/openapitools.json @@ -11,7 +11,7 @@ "additionalProperties": { "ngVersion": "21.2.14", "providedInRoot": true, - "serviceSuffix": "OpenApiService", + "serviceSuffix": "Service", "withInterfaces": true, "enumPropertyNaming": "original", "fileNaming": "kebab-case" diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 0da98db0..38ffb6ce 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -4,6 +4,7 @@ README.md api.base.service.ts api.module.ts api/api.ts +api/funding.service.ts api/iNSEAccountService.service.ts api/iNSEService.service.ts api/items.service.ts @@ -23,6 +24,7 @@ model/authorAffiliationsInner.ts model/authorCountsByYearInner.ts model/authorIds.ts model/authorParsedLongestName.ts +model/authorPositionCount.ts model/authorSummaryStats.ts model/authorsListResponse.ts model/authorship.ts @@ -32,12 +34,16 @@ model/collaborationNetworkEdge.ts model/collaborationNetworkNode.ts model/collaborationNetworkNodeType.ts model/costUsd.ts +model/customAuthor.ts +model/customAuthorsListResponse.ts model/dehydratedAuthor.ts model/dehydratedFunder.ts model/dehydratedInstitution.ts model/dehydratedSource.ts model/filterInformation.ts model/filterProperties.ts +model/funderByAuthor.ts +model/fundersByAuthorResponse.ts model/fwci.ts model/groupByResult.ts model/hTTPValidationError.ts @@ -52,6 +58,8 @@ model/model2YrMeanCitedness.ts model/models.ts model/openAccess.ts model/personBio.ts +model/publicationIdsByAuthorPosition.ts +model/publicationsByAuthorResponse.ts model/score.ts model/topicCount.ts model/topicsByTime.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index d9409cee..eae43798 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -1,3 +1,5 @@ +export * from './funding.service'; +import { FundingService } from './funding.service'; export * from './iNSEAccountService.service'; import { INSEAccountServiceService } from './iNSEAccountService.service'; export * from './iNSEService.service'; @@ -12,4 +14,4 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService]; +export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, ItemsService, PersonNetworkService, PersonsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/funding.service.ts b/webapp/src/app/api/api/funding.service.ts new file mode 100644 index 00000000..46772768 --- /dev/null +++ b/webapp/src/app/api/api/funding.service.ts @@ -0,0 +1,161 @@ +/** + * 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. + */ +/* 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'; + +// @ts-ignore +import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + + +@Injectable({ + providedIn: 'root' +}) +export class FundingService extends BaseService { + + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); + } + + /** + * Get funding organizations by author. + * @endpoint get /api/inse-service/authors/{author_id}/funders + * @param authorId + * @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 getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.'); + } + + 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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`; + 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 funded publications by author. + * @endpoint get /api/inse-service/authors/{author_id}/publications + * @param authorId + * @param page + * @param pageSize + * @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 getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + + 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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`; + 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/api/api/iNSEService.service.ts b/webapp/src/app/api/api/iNSEService.service.ts index 0fa2f5f0..cf95d68e 100644 --- a/webapp/src/app/api/api/iNSEService.service.ts +++ b/webapp/src/app/api/api/iNSEService.service.ts @@ -16,8 +16,6 @@ import { HttpClient, HttpHeaders, HttpParams, import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; -// @ts-ignore -import { AuthorsListResponse } from '../model/authorsListResponse'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore @@ -26,8 +24,6 @@ import { Item } from '../model/item'; import { ItemCreate } from '../model/itemCreate'; // @ts-ignore import { ItemPage } from '../model/itemPage'; -// @ts-ignore -import { PersonBio } from '../model/personBio'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -295,69 +291,6 @@ export class INSEServiceService extends BaseService { ); } - /** - * Generates a bio for a person by author ID. - * @endpoint get /api/inse-service/persons/bio - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags - * @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 generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorId === null || authorId === undefined) { - throw new Error('Required parameter authorId was null or undefined when calling generatePersonBio.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/bio`; - 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 - } - ); - } - /** * Returns the item with the id. * @endpoint get /api/inse-service/items/{id} @@ -480,27 +413,15 @@ export class INSEServiceService extends BaseService { } /** - * Searches for person by ID. - * @endpoint get /api/inse-service/person/{id} - * @param id OpenAlex author ID - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * 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 getPersonByID(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (id === null || id === undefined) { - throw new Error('Required parameter id was null or undefined when calling getPersonByID.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling getPersonByID.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); + 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; @@ -527,207 +448,11 @@ export class INSEServiceService extends BaseService { } } - let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + let localVarPath = `/api/inse-service/topics/hierarchy`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, + 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 - } - ); - } - - /** - * Searches for persons by ID or name. - * @endpoint get /api/inse-service/persons/search - * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost - * @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 searchPersons(authorId?: string, query?: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersons(authorId?: string, query?: string, include?: 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, - authorId, 'author_id'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/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 - } - ); - } - - /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsByInstitution(institutionName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (institutionName === null || institutionName === undefined) { - throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - institutionName, 'institution_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/searchByInstitution`; - 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 - } - ); - } - - /** - * Searches for person by name. - * @endpoint get /api/inse-service/persons/searchByName - * @param authorName Authors name (e.g., Arman Arzani) - * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... - * @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 searchPersonsByName(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (authorName === null || authorName === undefined) { - throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); - } - if (include === null || include === undefined) { - throw new Error('Required parameter include was null or undefined when calling searchPersonsByName.'); - } - - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - authorName, 'author_name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - include, 'include'); - - 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/persons/searchByName`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, responseType: responseType_, ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index 4df09d02..a45848ef 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -19,6 +19,8 @@ import { Observable } from 'rxjs'; // @ts-ignore import { AuthorsListResponse } from '../model/authorsListResponse'; // @ts-ignore +import { CustomAuthorsListResponse } from '../model/customAuthorsListResponse'; +// @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { PersonBio } from '../model/personBio'; @@ -166,6 +168,70 @@ export class PersonsService extends BaseService { ); } + /** + * Searches for person by ID. + * @endpoint get /api/inse-service/person/{id} + * @param id OpenAlex author ID + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID_1(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPersonByID_1(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID_1(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID_1(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getPersonByID_1.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling getPersonByID_1.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + 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/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 + } + ); + } + /** * Searches for persons by ID or name. * @endpoint get /api/inse-service/persons/search @@ -230,17 +296,151 @@ export class PersonsService extends BaseService { } /** - * Searches for persons by institution name. - * @endpoint get /api/inse-service/persons/searchByInstitution - * @param institutionName Institution name (e.g., MIT, Oxford University) + * Searches for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... * @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 searchPersonsByInstitution(institutionName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + 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/persons/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 + } + ); + } + + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete_2(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete_2.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete_2.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + 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/persons/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 + } + ); + } + + /** + * Searches for persons by institution name. + * @endpoint get /api/inse-service/persons/searchByInstitution + * @param institutionName Institution name (e.g., MIT, Oxford University) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (institutionName === null || institutionName === undefined) { throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); } @@ -253,6 +453,82 @@ export class PersonsService extends BaseService { institutionName, 'institution_name'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); + + 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/persons/searchByInstitution`; + 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 + } + ); + } + + /** + * Searches for persons by institution name. + * @endpoint get /api/inse-service/persons/searchByInstitution + * @param institutionName Institution name (e.g., MIT, Oxford University) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution_3(institutionName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (institutionName === null || institutionName === undefined) { + throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution_3.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution_3.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institution_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); let localVarHeaders = this.defaultHeaders; @@ -300,13 +576,15 @@ export class PersonsService extends BaseService { * @endpoint get /api/inse-service/persons/searchByName * @param authorName Authors name (e.g., Arman Arzani) * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page * @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 searchPersonsByName(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (authorName === null || authorName === undefined) { throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); } @@ -319,6 +597,10 @@ export class PersonsService extends BaseService { authorName, 'author_name'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); let localVarHeaders = this.defaultHeaders; @@ -361,4 +643,246 @@ export class PersonsService extends BaseService { ); } + /** + * Searches for person by name. + * @endpoint get /api/inse-service/persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param limit Limit of search page results + * @param pageOffset Offset of the result page + * @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 searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName_4.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByName_4.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageOffset, 'page_offset'); + + 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/persons/searchByName`; + 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 + } + ); + } + + /** + * Searches for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionName Filter by institution name + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param strict Strict institution search by target year + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, 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, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institutionName'); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + strict, 'strict'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterMode, 'filterMode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterYear, 'filterYear'); + + 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/persons/search-list`; + 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 + } + ); + } + + /** + * Searches for persons with advanced filters (Topic & Institution) and pagination. + * @endpoint get /api/inse-service/persons/search-list + * @param query Search query (e.g., Arman AND Arzani) + * @param institutionName Filter by institution name + * @param topic Filter by topic display names + * @param page Page number (1-indexed) + * @param pageSize Results per page + * @param include Comma-separated include tags + * @param strict Strict institution search by target year + * @param filterMode Filter mode: \'in\' or \'from\' + * @param filterYear Filter year + * @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 searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, 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, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institutionName'); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'pageSize'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + strict, 'strict'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterMode, 'filterMode'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filterYear, 'filterYear'); + + 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/persons/search-list`; + 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/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 68afe965..fdd4b44c 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -159,4 +159,55 @@ export class TopicsService extends BaseService { ); } + /** + * 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 + } + ); + } + } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 6b6dd9fa..62474a83 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -19,6 +19,8 @@ import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { TopicCount } from '../model/topicCount'; +// @ts-ignore import { TopicsByTime } from '../model/topicsByTime'; // @ts-ignore import { WorkPage } from '../model/workPage'; @@ -187,6 +189,64 @@ export class WorksService extends BaseService { ); } + /** + * Returns work counts per primary topic for an author. + * @endpoint get /api/works/{author_id}/primary-topic-counts + * @param authorId The author id, for example A5023888391. + * @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 getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.'); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (bearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer '); + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-topic-counts`; + 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 + } + ); + } + /** * Returns topics grouped by publication year for an author. * @endpoint get /api/works/{author_id}/topics-by-time diff --git a/webapp/src/app/api/model/authorPositionCount.ts b/webapp/src/app/api/model/authorPositionCount.ts new file mode 100644 index 00000000..a02e3749 --- /dev/null +++ b/webapp/src/app/api/model/authorPositionCount.ts @@ -0,0 +1,18 @@ +/** + * 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 AuthorPositionCount { + first?: number; + middle?: number; + last?: number; + unknown?: number; +} + diff --git a/webapp/src/app/api/model/customAuthor.ts b/webapp/src/app/api/model/customAuthor.ts new file mode 100644 index 00000000..1117cd53 --- /dev/null +++ b/webapp/src/app/api/model/customAuthor.ts @@ -0,0 +1,39 @@ +/** + * 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 { AuthorAffiliationsInner } from './authorAffiliationsInner'; +import { AuthorParsedLongestName } from './authorParsedLongestName'; +import { DehydratedInstitution } from './dehydratedInstitution'; +import { AuthorCountsByYearInner } from './authorCountsByYearInner'; +import { AuthorIds } from './authorIds'; +import { AuthorSummaryStats } from './authorSummaryStats'; +import { WorkTopic } from './workTopic'; + + +export interface CustomAuthor { + id?: string | null; + orcid?: string | null; + display_name?: string | null; + display_name_alternatives?: Array | null; + longest_name?: string | null; + parsed_longest_name?: AuthorParsedLongestName | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + affiliations?: Array | null; + last_known_institutions?: Array | null; + topics?: Array | null; + counts_by_year?: Array | null; + ids?: AuthorIds | null; + works_api_url?: string | null; + created_date?: string | null; + updated_date?: string | null; + relevance_rating?: string | null; +} + diff --git a/webapp/src/app/api/model/customAuthorsListResponse.ts b/webapp/src/app/api/model/customAuthorsListResponse.ts new file mode 100644 index 00000000..b5584b7c --- /dev/null +++ b/webapp/src/app/api/model/customAuthorsListResponse.ts @@ -0,0 +1,22 @@ +/** + * 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 { Meta } from './meta'; +import { CustomAuthor } from './customAuthor'; +import { Author } from './author'; +import { GroupByResult } from './groupByResult'; + + +export interface CustomAuthorsListResponse { + meta?: Meta | null; + results?: Array | null; + group_by?: Array | null; + foo_author?: CustomAuthor | null; +} + diff --git a/webapp/src/app/api/model/funderByAuthor.ts b/webapp/src/app/api/model/funderByAuthor.ts new file mode 100644 index 00000000..fbcbf475 --- /dev/null +++ b/webapp/src/app/api/model/funderByAuthor.ts @@ -0,0 +1,23 @@ +/** + * 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 { PublicationIdsByAuthorPosition } from './publicationIdsByAuthorPosition'; +import { AuthorPositionCount } from './authorPositionCount'; + + +export interface FunderByAuthor { + funder_id?: string | null; + funder_name?: string | null; + publication_count: number; + author_position_count: AuthorPositionCount; + publication_ids: PublicationIdsByAuthorPosition; + publication_urls?: { [key: string]: string; }; + publication_titles?: { [key: string]: string; }; +} + diff --git a/webapp/src/app/api/model/fundersByAuthorResponse.ts b/webapp/src/app/api/model/fundersByAuthorResponse.ts new file mode 100644 index 00000000..1286429e --- /dev/null +++ b/webapp/src/app/api/model/fundersByAuthorResponse.ts @@ -0,0 +1,19 @@ +/** + * 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 { FunderByAuthor } from './funderByAuthor'; + + +export interface FundersByAuthorResponse { + author_id: string; + author_name?: string | null; + funder_count: number; + funders: Array; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 859f206d..a81bc77d 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -6,6 +6,7 @@ export * from './authorAffiliationsInner'; export * from './authorCountsByYearInner'; export * from './authorIds'; export * from './authorParsedLongestName'; +export * from './authorPositionCount'; export * from './authorSummaryStats'; export * from './authorsListResponse'; export * from './authorship'; @@ -15,12 +16,16 @@ export * from './collaborationNetworkEdge'; export * from './collaborationNetworkNode'; export * from './collaborationNetworkNodeType'; export * from './costUsd'; +export * from './customAuthor'; +export * from './customAuthorsListResponse'; export * from './dehydratedAuthor'; export * from './dehydratedFunder'; export * from './dehydratedInstitution'; export * from './dehydratedSource'; export * from './filterInformation'; export * from './filterProperties'; +export * from './funderByAuthor'; +export * from './fundersByAuthorResponse'; export * from './fwci'; export * from './groupByResult'; export * from './hTTPValidationError'; @@ -34,6 +39,8 @@ export * from './meta'; export * from './model2YrMeanCitedness'; export * from './openAccess'; export * from './personBio'; +export * from './publicationIdsByAuthorPosition'; +export * from './publicationsByAuthorResponse'; export * from './score'; export * from './topicCount'; export * from './topicsByTime'; diff --git a/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts new file mode 100644 index 00000000..c35050ef --- /dev/null +++ b/webapp/src/app/api/model/publicationIdsByAuthorPosition.ts @@ -0,0 +1,18 @@ +/** + * 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 PublicationIdsByAuthorPosition { + first?: Array; + middle?: Array; + last?: Array; + unknown?: Array; +} + diff --git a/webapp/src/app/api/model/publicationsByAuthorResponse.ts b/webapp/src/app/api/model/publicationsByAuthorResponse.ts new file mode 100644 index 00000000..5176fe39 --- /dev/null +++ b/webapp/src/app/api/model/publicationsByAuthorResponse.ts @@ -0,0 +1,21 @@ +/** + * 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 PublicationsByAuthorResponse { + author_id: string; + page: number; + page_size: number; + total_works: number; + total: number; + results_count: number; + results: Array; +} + diff --git a/webapp/src/app/api/model/topicCount.ts b/webapp/src/app/api/model/topicCount.ts index d6c3c481..c4e4ef18 100644 --- a/webapp/src/app/api/model/topicCount.ts +++ b/webapp/src/app/api/model/topicCount.ts @@ -10,6 +10,7 @@ export interface TopicCount { + id?: string | null; /** * The topic display name. */ diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 3c869a34..ae314ae3 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -80,6 +80,13 @@ export const routes: Routes = [ (mod) => mod.PersonPublicationsComponent, ), }, + { + path: 'funding', + loadComponent: () => + import('./modules/person-funding/person-funding.component').then( + (mod) => mod.PersonFundingComponent, + ), + }, ], }, { diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html new file mode 100644 index 00000000..6b2b0ce4 --- /dev/null +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -0,0 +1,180 @@ +@if (loading) { +

Lade Förderungen...

+} @else if (error) { +

Fehler beim Laden der Förderungen.

+} @else if (funders.length === 0) { +

Keine Förderungen gefunden.

+} @else { +
+
+

+ {{ getUniquePublicationCount() }} + Einzigartige Publikationen +

+

+ {{ filteredFunders.length }} + Förderer +

+
+ + +
+ Filter nach Position: + + + + +
+ +
+ +
+ + + + + + + + + @for (funder of getPagedFunders(); track funder.funder_id) { + + + + + } + +
FördererPublikationen
{{ funder.funder_name }}{{ getPublicationCount(funder) }}
+ @if (hasFunderListPagination()) { +
+ + Seite {{ selectedFunderListPage }} von + {{ getFunderListPageCount() }} + +
+ } +
+ + + @if (selectedFunder) { +
+

{{ selectedFunder.funder_name }}

+ +
+ @if (shouldShowPosition("first")) { +
+ Erstautor + {{ + selectedFunder.author_position_count.first + }} +
+ } + @if (shouldShowPosition("middle")) { +
+ Mitautor + {{ + selectedFunder.author_position_count.middle + }} +
+ } + @if (shouldShowPosition("last")) { +
+ Letztautor + {{ + selectedFunder.author_position_count.last + }} +
+ } +
+ +

Publikationen

+
    + @for (id of getSelectedPublicationIdsPage(); track id) { +
  • + {{ + getPublicationTitle(id) + }} + @if (expandedPublicationId === id) { +
    + Mehr Infos + + open_in_new + +
    + } +
  • + } +
+ @if (hasPublicationPagination()) { +
+ + Seite {{ selectedPublicationPage }} von + {{ getSelectedPublicationPageCount() }} + +
+ } +
+ } @else { +
+

Klicke auf einen Förderer für Details.

+
+ } +
+
+} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.scss b/webapp/src/app/modules/person-funding/person-funding.component.scss new file mode 100644 index 00000000..c1a80450 --- /dev/null +++ b/webapp/src/app/modules/person-funding/person-funding.component.scss @@ -0,0 +1,298 @@ +.message { + padding: 16px; + color: #666; +} + +.funding-container { + padding: 16px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.filter-bar { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + + span { + font-weight: 500; + color: #555; + } + + button { + padding: 6px 14px; + border: 1px solid #ccc; + border-radius: 20px; + background: white; + cursor: pointer; + font-size: 14px; + transition: all 0.2s; + + &:hover { + background: #f0f0f0; + } + } + button:nth-child(2) { + background: #f0f6ff; + color: #0b63ce; + border-color: #bdd4ff; +} + +button:nth-child(3) { + background: #effaf3; + color: #24834f; + border-color: #bdebcf; +} + +button:nth-child(4) { + background: #f6f0ff; + color: #7255d9; + border-color: #d8cafe; +} + +button:nth-child(5) { + background: #fff7e8; + color: #c67500; + border-color: #ffd796; +} +} + +.funding-content { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.funding-list { + flex: 1; + + table { + width: 100%; + border-collapse: collapse; + + th { + text-align: left; + padding: 10px 12px; + border-bottom: 2px solid #e0e0e0; + font-weight: 600; + color: #333; + } + + tr { + cursor: pointer; + transition: background 0.15s; + + &:hover { + background: #f5f5f5; + } + + &.selected { + background: #f0f0f0; + } + } + + td { + padding: 10px 12px; + border-bottom: 1px solid #f0f0f0; + } + + .funder-name { + color: #333; + font-weight: 500; + } + } +} + +.funding-detail { + width: 440px; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 20px; + background: #fafafa; + + &.empty { + display: flex; + align-items: center; + justify-content: center; + color: #999; + min-height: 200px; + } + + h3 { + margin: 0 0 16px 0; + font-size: 16px; + color: #333; + } + + h4 { + margin: 16px 0 8px 0; + font-size: 14px; + color: #555; + } +} + +.position-stats { + display: flex; + gap: 12px; + margin-bottom: 16px; + width: fit-content; + margin-left: auto; + margin-right: auto; + + .stat { + flex: 0.0 auto; + min-width: 100px; + text-align: center; + background: white; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 10px; + + .stat-label { + display: block; + font-size: 12px; + color: #666; + margin-bottom: 4px; + } + + .stat-value { + display: block; + font-size: 22px; + font-weight: bold; + color: #333; + } + } + .stat-first { + background: #effaf3; + border-color: #bdebcf; + } + + .stat-middle { + background: #f6f0ff; + border-color: #d8cafe; + } + + .stat-last { + background: #fff7e8; + border-color: #ffd796; + } +} + +.publication-list { + list-style: none; + padding: 0; + margin: 0; + max-height: 300px; + overflow-y: auto; + + li { + padding: 6px 0; + border-bottom: 1px solid #5b5555; + font-size: 13px; + + a { + color: #2563eb; + text-decoration: none; + word-break: break-all; + + &:hover { + color: #1d4ed8; + text-decoration: underline; + } + } + } +} + +.publication-pagination { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 12px; + + button { + padding: 4px 10px; + border: 1px solid #d0d0d0; + border-radius: 6px; + background: white; + cursor: pointer; + font-size: 12px; + + &:disabled { + opacity: 0.5; + cursor: default; + } + } + + span { + font-size: 12px; + color: #666; + } +} + +.funding-summary { + margin-bottom: 16px; + + .summary-line { + margin: 0 0 4px 0; + font-size: 14px; + color: #333; + } + + .summary-label { + color: #333; + } + + .summary-value { + font-weight: 600; + color: #333; + } +} +.publication-item { + padding: 8px 0; + border-bottom: 2px solid #5b5555; + cursor: pointer; + + &:hover { + background: #f9f9f9; + } +} + +.publication-title { + font-size: 0.875rem; + color: #333; + white-space: normal; + word-break: break-word; + display: block; +} +.publication-more-info { + display: flex; + align-items: center; + flex-direction: row; + gap: 4px; + margin-top: 6px; +} + +.mehr-infos-label { + font-size: 0.8rem; + color: #1976d2; + font-weight: 500; +} + +.publication-link-icon { + display: flex; + align-items: center; + color: #1976d2; + text-decoration: none; + flex-shrink: 0; + + .material-icons { + font-size: 16px; + } + + &:hover { + color: #0d47a1; + } +} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.ts b/webapp/src/app/modules/person-funding/person-funding.component.ts new file mode 100644 index 00000000..72609509 --- /dev/null +++ b/webapp/src/app/modules/person-funding/person-funding.component.ts @@ -0,0 +1,270 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute } from '@angular/router'; +import { Router } from '@angular/router'; +import { PersonsService } from '../../api'; +import { FundingService } from '../../api'; +@Component({ + selector: 'app-person-funding', + imports: [CommonModule], + templateUrl: './person-funding.component.html', + styleUrl: './person-funding.component.scss', +}) +export class PersonFundingComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private fundingApi = inject(FundingService); + private initialSelectedFunderKey: string | null = null; + private initialPublicationPage = 1; + private initialFunderListPage = 1; + + funders: any[] = []; + filteredFunders: any[] = []; + selectedFunder: any = null; + selectedFunderListPage = 1; + selectedPublicationPage = 1; + readonly funderListPageSize = 10; + readonly publicationPageSize = 10; + activeFilter: 'all' | 'first' | 'middle' | 'last' = 'all'; + loading = true; + error = false; + expandedPublicationId: string | null = null; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe(params => { + const authorId = params.get('id') ?? ''; + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); + this.initialPublicationPage = this.parsePageParam( + this.route.snapshot.queryParamMap.get('publicationPage') ?? this.route.snapshot.queryParamMap.get('page') + ); + this.initialFunderListPage = this.parsePageParam(this.route.snapshot.queryParamMap.get('funderPage')); + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + + if (authorId) { + this.fundingApi.getFundersByAuthor(authorId).subscribe({ + next: (result: any) => { + this.funders = result.funders ?? []; + this.applyFilter(); + this.selectedFunderListPage = this.clampPage(this.initialFunderListPage, this.getFunderListPageCount()); + this.restoreSelectedFunderFromUrl(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + } + }); + } + }); +} + + selectFunder(funder: any): void { + this.selectedFunder = funder; + this.selectedPublicationPage = 1; + this.updateQueryParams(); + } + + setFilter(filter: 'all' | 'first' | 'middle' | 'last'): void { + this.activeFilter = filter; + this.applyFilter(); + this.updateQueryParams(); + } + + private applyFilter(): void { + this.selectedFunder = null; + this.selectedFunderListPage = 1; + this.selectedPublicationPage = 1; + if (this.activeFilter === 'all') { + this.filteredFunders = this.funders; + } else { + this.filteredFunders = this.funders.filter( + f => f.author_position_count[this.activeFilter] > 0 + ); + } + } + + private restoreSelectedFunderFromUrl(): void { + if (!this.initialSelectedFunderKey) { + return; + } + + const matchedFunder = this.filteredFunders.find( + (funder: any) => this.getFunderKey(funder) === this.initialSelectedFunderKey + ); + + if (matchedFunder) { + this.selectedFunder = matchedFunder; + const matchedIndex = this.filteredFunders.findIndex( + (funder: any) => this.getFunderKey(funder) === this.getFunderKey(matchedFunder) + ); + if (matchedIndex >= 0) { + this.selectedFunderListPage = Math.floor(matchedIndex / this.funderListPageSize) + 1; + } + this.selectedPublicationPage = this.clampPublicationPage( + this.initialPublicationPage, + this.getPublicationPageCountForFunder(matchedFunder), + ); + this.updateQueryParams(); + } else { + this.updateQueryParams(); + } + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + funder: this.selectedFunder ? this.getFunderKey(this.selectedFunder) : null, + publicationPage: this.selectedFunder ? this.selectedPublicationPage : null, + funderPage: this.selectedFunderListPage + }, + queryParamsHandling: 'merge', + replaceUrl: true + }); + } + + private getFunderKey(funder: any): string { + return funder.funder_id ?? funder.funder_name ?? ''; + } + + private isValidFilter(value: string | null): value is 'all' | 'first' | 'middle' | 'last' { + return value === 'all' || value === 'first' || value === 'middle' || value === 'last'; + } + + getPublicationCount(funder: any): number { + if (this.activeFilter === 'all') { + return funder.publication_count ?? 0; + } + return funder.author_position_count?.[this.activeFilter] ?? 0; + } + + getPublicationIds(funder: any): string[] { + if (this.activeFilter === 'all') { + return [ + ...funder.publication_ids.first, + ...funder.publication_ids.middle, + ...funder.publication_ids.last, + ...funder.publication_ids.unknown + ]; + } + return funder.publication_ids[this.activeFilter] ?? []; + } + + getPagedFunders(): any[] { + const startIndex = (this.selectedFunderListPage - 1) * this.funderListPageSize; + return this.filteredFunders.slice(startIndex, startIndex + this.funderListPageSize); + } + + hasFunderListPagination(): boolean { + return this.getFunderListPageCount() > 1; + } + + getFunderListPageCount(): number { + return Math.max(1, Math.ceil(this.filteredFunders.length / this.funderListPageSize)); + } + + setFunderListPage(page: number): void { + this.selectedFunderListPage = this.clampPage(page, this.getFunderListPageCount()); + this.updateQueryParams(); + } + + getSelectedPublicationIdsPage(): string[] { + if (!this.selectedFunder) { + return []; + } + const allPublicationIds = this.getPublicationIds(this.selectedFunder); + const startIndex = (this.selectedPublicationPage - 1) * this.publicationPageSize; + return allPublicationIds.slice(startIndex, startIndex + this.publicationPageSize); + } + + hasPublicationPagination(): boolean { + return this.getSelectedPublicationPageCount() > 1; + } + + getSelectedPublicationPageCount(): number { + if (!this.selectedFunder) { + return 1; + } + return this.getPublicationPageCountForFunder(this.selectedFunder); + } + + setPublicationPage(page: number): void { + const totalPages = this.getSelectedPublicationPageCount(); + this.selectedPublicationPage = this.clampPublicationPage(page, totalPages); + this.updateQueryParams(); + } + + openPublication(event: MouseEvent, publicationId: string): void { + event.preventDefault(); + const url = this.getPublicationUrl(publicationId); + window.open(url, '_blank', 'noopener'); + } + + getPositionLabel(position: string): string { + const labels: Record = { + first: 'Erstautor', + middle: 'Mitautor', + last: 'Letztautor', + unknown: 'Unbekannt' + }; + return labels[position] ?? position; + } + + shouldShowPosition(position: 'first' | 'middle' | 'last'): boolean { + return this.activeFilter === 'all' || this.activeFilter === position; + } + + getUniquePublicationCount(): number { + const allIds = new Set(); + for (const funder of this.funders) { + if (this.activeFilter === 'all') { + for (const ids of Object.values(funder.publication_ids) as string[][]) { + ids.forEach((id: string) => allIds.add(id)); + } + } else { + (funder.publication_ids[this.activeFilter] ?? []).forEach((id: string) => + allIds.add(id), + ); + } + } + return allIds.size; + } + + getPublicationUrl(publicationId: string): string { + return this.selectedFunder?.publication_urls?.[publicationId] ?? publicationId; + } + + private getPublicationPageCountForFunder(funder: any): number { + const publicationCount = this.getPublicationIds(funder).length; + return Math.max(1, Math.ceil(publicationCount / this.publicationPageSize)); + } + + private clampPublicationPage(page: number, totalPages: number): number { + return this.clampPage(page, totalPages); + } + + private clampPage(page: number, totalPages: number): number { + return Math.min(Math.max(page, 1), totalPages); + } + + private parsePageParam(value: string | null): number { + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < 1) { + return 1; + } + return parsed; + } + getPublicationTitle(publicationId: string): string { + const title = this.selectedFunder?.publication_titles?.[publicationId]; + if (title) return title; + const parts = publicationId.split('/'); + return parts[parts.length - 1] ?? publicationId; + } + togglePublication(id: string): void { + this.expandedPublicationId = this.expandedPublicationId === id ? null : id; +} +} 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 7f79895c..14767892 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -1,9 +1,14 @@ From efd9d624770a0f526267df7bfdf256e967c2f970 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 8 Jun 2026 15:17:39 +0200 Subject: [PATCH 33/33] fixed FormControl <-> Query Params binding --- .../app-searchbar/app-searchbar.component.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts index 711c0211..3196c3b5 100644 --- a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts @@ -1,4 +1,4 @@ -import { Component, inject, ViewChild, DestroyRef} from '@angular/core'; +import { Component, inject, ViewChild, DestroyRef } from '@angular/core'; import { MatIcon } from '@angular/material/icon'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; @@ -43,11 +43,19 @@ export class AppSearchbarComponent { private readonly router = inject(Router); private readonly route = inject(ActivatedRoute); private readonly personService = inject(PersonsService); - constructor() { - const params = new URLSearchParams(window.location.search); - const currentSearch = params.get('query') ?? ''; - this.searchControl.setValue(currentSearch, { emitEvent: false }); + const route = inject(ActivatedRoute); + const router = inject(Router); + + // Sync searchControl from query param on every URL change + route.queryParams + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const query = params['query'] ?? ''; + if (this.searchControl.value !== query) { + this.searchControl.setValue(query, { emitEvent: false }); + } + }); // Autocomplete suggestions this.searchControl.valueChanges