From c5d62faf2fb99b994385deb08c854b4af3e4bec8 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 10 Jul 2026 10:19:23 +0200 Subject: [PATCH 01/20] added shared year slider --- .../year-range-slider.component.html | 45 ++++++ .../year-range-slider.component.scss | 150 ++++++++++++++++++ .../year-range-slider.component.ts | 61 +++++++ 3 files changed, 256 insertions(+) create mode 100644 webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html create mode 100644 webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.scss create mode 100644 webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.ts diff --git a/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html new file mode 100644 index 00000000..5450b4a4 --- /dev/null +++ b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.html @@ -0,0 +1,45 @@ +
+
+ Zeitraum + + {{ startYear() }} bis {{ endYear() }} + + +
+ +
+
+ + + + +
+ +
+ {{ minYear() }} + {{ maxYear() }} +
+
diff --git a/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.scss b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.scss new file mode 100644 index 00000000..37c26635 --- /dev/null +++ b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.scss @@ -0,0 +1,150 @@ +.year-filter { + --accent: #3b82f6; + width: 100%; + padding: 8px 12px; + border: 1px solid #dbe5f6; + border-radius: 10px; + background: #fbfdff; + box-sizing: border-box; + + button { + font-family: inherit; + border: 0; + background: transparent; + padding: 0; + cursor: pointer; + transition: all 0.2s ease; + + &:hover:not(:disabled) { + color: var(--accent); + text-decoration: underline; + } + + &:disabled { + cursor: default; + } + } +} + +.year-filter-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 6px; +} + +.year-filter-label { + color: #07163d; + font-size: 12px; + font-weight: 700; +} + +.reset-range-button { + color: var(--accent); + font-size: 11px; + + &:disabled { + color: #9aa5bc; + } +} + +.year-filter-values { + display: flex; + align-items: center; + gap: 5px; + color: #40506f; + font-size: 12px; + font-weight: 600; + white-space: nowrap; +} + +.year-filter-bounds { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 2px; + color: #7c88a3; + font-size: 10px; +} + +.year-range-slider { + --range-start: 0%; + --range-end: 100%; + + position: relative; + height: 16px; +} + +.range-track { + position: absolute; + top: 50%; + left: 0; + right: 0; + height: 5px; + transform: translateY(-50%); + border-radius: 999px; + background: linear-gradient( + to right, + #d8e2f4 0%, + #d8e2f4 var(--range-start), + var(--accent) var(--range-start), + var(--accent) var(--range-end), + #d8e2f4 var(--range-end), + #d8e2f4 100% + ); +} + +.range-input { + position: absolute; + inset: 0; + width: 100%; + height: 22px; + margin: 0; + appearance: none; + background: transparent; + pointer-events: none; +} + +.range-input::-webkit-slider-runnable-track, +.range-input::-moz-range-track { + height: 5px; + background: transparent; + border: none; +} + +.range-input::-webkit-slider-thumb { + appearance: none; + width: 15px; + height: 15px; + margin-top: -5px; + border: 2px solid #ffffff; + border-radius: 50%; + background: var(--accent); + box-shadow: + 0 0 0 1px #9ab7ff, + 0 2px 6px rgba(0, 87, 255, 0.22); + cursor: pointer; + pointer-events: auto; +} + +.range-input::-moz-range-thumb { + width: 15px; + height: 15px; + border: 2px solid #ffffff; + border-radius: 50%; + background: var(--accent); + box-shadow: + 0 0 0 1px #9ab7ff, + 0 2px 6px rgba(0, 87, 255, 0.22); + cursor: pointer; + pointer-events: auto; +} + +.range-input-start { + z-index: 2; +} + +.range-input-end { + z-index: 3; +} diff --git a/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.ts b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.ts new file mode 100644 index 00000000..0e073937 --- /dev/null +++ b/webapp/src/app/shared/ui/year-range-slider/year-range-slider.component.ts @@ -0,0 +1,61 @@ +import { Component, input, model, computed } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +@Component({ + selector: 'app-year-range-slider', + standalone: true, + imports: [CommonModule], + templateUrl: './year-range-slider.component.html', + styleUrl: './year-range-slider.component.scss', +}) +export class YearRangeSliderComponent { + readonly minYear = input(2000); + readonly maxYear = input(2025); + readonly startYear = model(2000); + readonly endYear = model(2025); + + readonly rangeStartPercent = computed(() => { + return `${this.calculatePercent(this.startYear())}%`; + }); + + readonly rangeEndPercent = computed(() => { + return `${this.calculatePercent(this.endYear())}%`; + }); + + readonly canReset = computed(() => { + return ( + this.startYear() !== this.minYear() || this.endYear() !== this.maxYear() + ); + }); + + reset(): void { + this.startYear.set(this.minYear()); + this.endYear.set(this.maxYear()); + } + + onStartInput(event: Event): void { + const val = Number((event.target as HTMLInputElement).value); + if (val <= this.endYear()) { + this.startYear.set(val); + } else { + this.startYear.set(this.endYear()); + (event.target as HTMLInputElement).value = String(this.endYear()); + } + } + + onEndInput(event: Event): void { + const val = Number((event.target as HTMLInputElement).value); + if (val >= this.startYear()) { + this.endYear.set(val); + } else { + this.endYear.set(this.startYear()); + (event.target as HTMLInputElement).value = String(this.startYear()); + } + } + + private calculatePercent(year: number): number { + const totalRange = this.maxYear() - this.minYear(); + if (totalRange <= 0) return 0; + return ((year - this.minYear()) / totalRange) * 100; + } +} -- 2.56.1 From 72a1dc27bc151c5568c453a66c853ee7d3177e8d Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 10 Jul 2026 10:19:44 +0200 Subject: [PATCH 02/20] added shared location selector --- .../location-selector.component.html | 112 +++++++++++++ .../location-selector.component.scss | 156 ++++++++++++++++++ .../location-selector.component.ts | 50 ++++++ 3 files changed, 318 insertions(+) create mode 100644 webapp/src/app/shared/ui/location-selector/location-selector.component.html create mode 100644 webapp/src/app/shared/ui/location-selector/location-selector.component.scss create mode 100644 webapp/src/app/shared/ui/location-selector/location-selector.component.ts diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.html b/webapp/src/app/shared/ui/location-selector/location-selector.component.html new file mode 100644 index 00000000..10c70cea --- /dev/null +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.html @@ -0,0 +1,112 @@ +
+

Länder/Kontinente vergleichen

+ +
+ @if (comparisonCountries().length > 0 || comparisonRegions().length > 0) { + + @for (c of comparisonCountries(); track c.id) { +
+ + flag {{ c.name }} + +
+ + +
+
+ } + + + @for (r of comparisonRegions(); track r.id) { +
+ + public {{ r.name }} + +
+ + +
+
+ } + } @else { +
+ Keine Länder/Kontinente ausgewählt. Suchen zum Hinzufügen. +
+ } +
+ + + +
diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss new file mode 100644 index 00000000..acf0b1a7 --- /dev/null +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss @@ -0,0 +1,156 @@ +.control-card { + background: white; + border-radius: 10px; + padding: 1.25rem; + border: 1px solid #e5e7eb; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); + box-sizing: border-box; + + h3 { + font-size: 0.8rem; + font-weight: 600; + text-transform: uppercase; + color: #6b7280; + margin: 0 0 0.75rem 0; + letter-spacing: 0.05em; + } +} + +.comparison-list { + display: flex; + flex-direction: column; + gap: 0.4rem; + max-height: 200px; + overflow-y: auto; + margin-bottom: 0.75rem; + + .empty-list-info { + font-size: 0.75rem; + color: #9ca3af; + text-align: center; + padding: 8px 0; + border: 1px dashed #e5e7eb; + border-radius: 5px; + } +} + +.comparison-item { + display: flex; + justify-content: space-between; + align-items: center; + border: 1px solid #e5e7eb; + border-radius: 5px; + padding: 0.3rem 0.5rem; + transition: all 0.2s ease; + + .item-name { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 170px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + } + + .item-actions { + display: flex; + align-items: center; + gap: 4px; + } + + .action-btn { + background: none; + border: none; + cursor: pointer; + padding: 2px; + border-radius: 3px; + display: inline-flex; + align-items: center; + justify-content: center; + transition: all 0.15s ease; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + + &:hover { + background: rgba(0, 0, 0, 0.05); + } + + &.remove-btn:hover { + color: #ef4444 !important; + background: #fee2e2; + } + } +} + +.autocomplete-search { + position: relative; + width: 100%; + + input { + width: 100%; + padding: 0.5rem; + border-radius: 5px; + border: 1px solid #d1d5db; + font-size: 0.8125rem; + outline: none; + box-sizing: border-box; + &:focus { + border-color: #3b82f6; + } + } +} + +.autocomplete-results { + position: absolute; + top: 100%; + left: 0; + right: 0; + z-index: 50; + background: white; + border: 1px solid #e5e7eb; + border-radius: 5px; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + margin-top: 3px; + padding: 0; + list-style: none; + max-height: 180px; + overflow-y: auto; + + li button { + width: 100%; + text-align: left; + background: none; + border: none; + padding: 0.5rem 0.75rem; + cursor: pointer; + display: flex; + flex-direction: column; + &:hover { + background: #f3f4f6; + } + + .name { + font-size: 0.75rem; + font-weight: 500; + color: #1f2937; + } + .hint { + font-size: 0.65rem; + color: #9ca3af; + margin-top: 1px; + } + } +} diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.ts b/webapp/src/app/shared/ui/location-selector/location-selector.component.ts new file mode 100644 index 00000000..3d08fbce --- /dev/null +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.ts @@ -0,0 +1,50 @@ +import { Component, input, output } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { MatIconModule } from '@angular/material/icon'; +import { AutocompleteLocationItem } from '../../../api'; + +export interface CompareItem { + id: string; + name: string; +} + +@Component({ + selector: 'app-location-selector', + standalone: true, + imports: [CommonModule, MatIconModule], + templateUrl: './location-selector.component.html', + styleUrl: './location-selector.component.scss', +}) +export class LocationSelectorComponent { + readonly comparisonCountries = input([]); + readonly comparisonRegions = input([]); + readonly locationQuery = input(''); + readonly locationSearchResults = input([]); + readonly getEntityColor = input<(id: string) => string>(() => '#9ca3af'); + readonly isVisible = input<(id: string) => boolean>(() => true); + + readonly addLocation = output(); + readonly removeLocation = output<{ + id: string; + type: 'country' | 'continent'; + }>(); + readonly searchChange = output(); + readonly toggleVisibility = output(); + + onSearchInput(event: Event): void { + const val = (event.target as HTMLInputElement).value; + this.searchChange.emit(val); + } + + onSelectResult(loc: AutocompleteLocationItem): void { + this.addLocation.emit(loc); + } + + onRemove(id: string, type: 'country' | 'continent'): void { + this.removeLocation.emit({ id, type }); + } + + onToggleVisibility(id: string): void { + this.toggleVisibility.emit(id); + } +} -- 2.56.1 From aa473a652360aecfb7291bc75453e11fdaff7489 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 10 Jul 2026 10:49:55 +0200 Subject: [PATCH 03/20] added shared institution selector --- .../institution-selector.component.html | 131 +++++++ .../institution-selector.component.scss | 340 ++++++++++++++++++ .../institution-selector.component.ts | 67 ++++ 3 files changed, 538 insertions(+) create mode 100644 webapp/src/app/shared/ui/institution-selector/institution-selector.component.html create mode 100644 webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss create mode 100644 webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html new file mode 100644 index 00000000..a4203df9 --- /dev/null +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html @@ -0,0 +1,131 @@ +
+ +
+
+

Einrichtungen vergleichen

+ @if (primaryInstitutionName()) { +
+ Zugewiesen: + {{ primaryInstitutionName() }} +
+ } +
+ + + + + +
+ @if (comparisonInstitutions().length > 0) { +
+ @for (inst of comparisonInstitutions(); track inst.id) { +
+ + apartment {{ inst.name }} + +
+ + +
+
+ } +
+ } @else { +
+ Keine weiteren Einrichtungen ausgewählt. Suchen zum Hinzufügen. +
+ } +
+
+ + +
+

+ Empfohlene Top-Einrichtungen für das Thema: {{ activeChartTopic() }} +

+ +
+ @if (isSuggestionsLoading()) { +
+
+ Empfehlungen werden geladen... +
+ } @else { + @if (topSuggestions().length === 0) { +

+ Keine Empfehlungen für dieses Thema gefunden. +

+ } @else { +
+ @for (item of topSuggestions(); track item.id || '') { + + } +
+ } + } +
+
+
diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss new file mode 100644 index 00000000..a9fe0b99 --- /dev/null +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss @@ -0,0 +1,340 @@ +.institution-selector-container { + display: grid; + grid-template-columns: 1fr 1.5fr; + gap: 24px; + background: white; + border: 1px solid #d7e4ff; + border-radius: 16px; + padding: 24px; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + box-sizing: border-box; + margin-top: 20px; + + @media (max-width: 1024px) { + grid-template-columns: 1fr; + gap: 20px; + padding: 16px; + } +} + +.search-compare-section, +.recommendations-section { + display: flex; + flex-direction: column; + box-sizing: border-box; + + h3 { + font-size: 0.9rem; + font-weight: 700; + color: #07163d; + margin: 0 0 1rem 0; + line-height: 1.2; + } +} + +.section-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 0.5rem; + + h3 { + margin: 0; + } +} + +.primary-inst-badge { + display: inline-flex; + align-items: center; + gap: 6px; + background: #f0fdf4; + border: 1px solid #bbf7d0; + padding: 3px 8px; + border-radius: 6px; + font-size: 0.7rem; + + .label { + color: #166534; + font-weight: 500; + } + + .name { + color: #15803d; + } +} + +/* Autocomplete Search input */ +.autocomplete-search { + position: relative; + width: 100%; + margin-bottom: 1rem; + + .search-icon { + position: absolute; + left: 10px; + top: 50%; + transform: translateY(-50%); + font-size: 18px; + width: 18px; + height: 18px; + color: #9ca3af; + pointer-events: none; + } + + input { + width: 100%; + padding: 0.6rem 0.6rem 0.6rem 2.2rem; + border-radius: 8px; + border: 1px solid #d1d5db; + font-size: 0.8125rem; + outline: none; + box-sizing: border-box; + transition: all 0.2s ease; + + &:focus { + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); + } + } +} + +.autocomplete-results { + position: absolute; + top: 100%; + left: 0; + right: 0; + z-index: 50; + background: white; + border: 1px solid #e5e7eb; + border-radius: 8px; + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); + margin-top: 4px; + padding: 4px 0; + list-style: none; + max-height: 200px; + overflow-y: auto; + + li button { + width: 100%; + text-align: left; + background: none; + border: none; + padding: 0.6rem 1rem; + cursor: pointer; + display: flex; + flex-direction: column; + transition: background 0.15s ease; + + &:hover { + background: #f3f4f6; + } + + .name { + font-size: 0.75rem; + font-weight: 600; + color: #1f2937; + } + .hint { + font-size: 0.65rem; + color: #6b7280; + margin-top: 2px; + } + } +} + +/* Comparison list & chips */ +.comparison-list { + flex: 1; + min-height: 80px; + + .empty-list-info { + font-size: 0.75rem; + color: #9ca3af; + text-align: center; + padding: 16px; + border: 1px dashed #e5e7eb; + border-radius: 8px; + } +} + +.chips-flex { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + max-height: 180px; + overflow-y: auto; + padding-right: 4px; +} + +.comparison-item { + display: inline-flex; + justify-content: space-between; + align-items: center; + border: 1px solid #e5e7eb; + border-radius: 6px; + padding: 0.35rem 0.6rem; + gap: 8px; + transition: all 0.2s ease; + max-width: 100%; + + .item-name { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + } + + .item-actions { + display: flex; + align-items: center; + gap: 4px; + } + + .action-btn { + background: none; + border: none; + cursor: pointer; + padding: 2px; + border-radius: 4px; + display: inline-flex; + align-items: center; + justify-content: center; + transition: all 0.15s ease; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + + &:hover { + background: rgba(0, 0, 0, 0.05); + } + + &.remove-btn:hover { + color: #ef4444 !important; + background: #fee2e2; + } + } +} + +/* Recommendations suggestions section */ +.suggestions-grid { + flex: 1; + display: flex; + flex-direction: column; +} + +.suggestions-flex { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 10px; + max-height: 250px; + overflow-y: auto; + padding-right: 4px; + + @media (max-width: 600px) { + grid-template-columns: 1fr; + } +} + +.suggestion-item-horizontal { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 12px; + border: 1px solid #e5e7eb; + border-radius: 8px; + background: #f9fafb; + text-align: left; + cursor: pointer; + transition: all 0.2s ease; + box-sizing: border-box; + + &:hover:not(:disabled) { + background: #f3f4f6; + border-color: #3b82f6; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02); + } + + &:disabled { + opacity: 0.5; + cursor: not-allowed; + background: #f3f4f6; + } + + .add-icon { + color: #3b82f6; + font-size: 18px; + width: 18px; + height: 18px; + flex-shrink: 0; + } + + .info { + display: flex; + flex-direction: column; + min-width: 0; + + .name { + font-size: 0.75rem; + font-weight: 600; + color: #1f2937; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .meta { + font-size: 0.65rem; + color: #6b7280; + margin-top: 2px; + } + } +} + +.no-suggestions-msg { + font-size: 0.75rem; + color: #6b7280; + margin: 12px 0 0 0; +} + +.suggestions-loader { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.75rem; + color: #6b7280; + margin-top: 12px; +} + +.spinner-small { + width: 16px; + height: 16px; + border: 2px solid #e5e7eb; + border-top: 2px solid #3b82f6; + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts new file mode 100644 index 00000000..c72629a7 --- /dev/null +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts @@ -0,0 +1,67 @@ +import { Component, input, output } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { MatIconModule } from '@angular/material/icon'; + +export interface CompareItem { + id: string; + name: string; +} + +@Component({ + selector: 'app-institution-selector', + standalone: true, + imports: [CommonModule, MatIconModule], + templateUrl: './institution-selector.component.html', + styleUrl: './institution-selector.component.scss', +}) +export class InstitutionSelectorComponent { + readonly comparisonInstitutions = input([]); + readonly primaryInstitution = input(null); + readonly primaryInstitutionName = input(null); + readonly topSuggestions = input([]); + readonly isSuggestionsLoading = input(false); + readonly activeChartTopic = input(''); + readonly searchQuery = input(''); + readonly searchResults = input([]); + readonly getEntityColor = input<(id: string) => string>(() => '#9ca3af'); + readonly isVisible = input<(id: string) => boolean>(() => true); + + readonly addInstitution = output<{ id: string; name: string }>(); + readonly removeInstitution = output(); + readonly searchChange = output(); + readonly toggleVisibility = output(); + + onSearchInput(event: Event): void { + const val = (event.target as HTMLInputElement).value; + this.searchChange.emit(val); + } + + onSelectResult(result: any): void { + this.addInstitution.emit({ + id: result.id || '', + name: result.display_name || '', + }); + } + + onSelectSuggestion(item: any): void { + this.addInstitution.emit({ + id: item.id || '', + name: item.display_name || '', + }); + } + + onRemove(id: string): void { + this.removeInstitution.emit(id); + } + + onToggleVisibility(id: string): void { + this.toggleVisibility.emit(id); + } + + isAlreadyAdded(id: string | undefined): boolean { + if (!id) return false; + const isPrimary = this.primaryInstitution() === id; + const isComp = this.comparisonInstitutions().some((i) => i.id === id); + return isPrimary || isComp; + } +} -- 2.56.1 From 1980bde9ce4ebddc114e2849ddade41a7e37c9a5 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 10 Jul 2026 13:12:06 +0200 Subject: [PATCH 04/20] implemented shared components & databinding of legend to buttons --- .../uni-trend-chart.component.ts | 19 +- .../uni-trend-parent.component.html | 236 ++-------- .../uni-trend-parent.component.scss | 438 +----------------- .../uni-trend-parent.component.ts | 186 ++++++-- 4 files changed, 194 insertions(+), 685 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 8dfdc67b..41664237 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -76,6 +76,9 @@ export class UniTrendChartComponent { // Build series: Line in top grid, growth volume bars and S-Curve in bottom grid trendData.series.forEach((entity, entityIdx) => { const color = getEntityColor(entityIdx); + if ((entity as any).visible === false) { + return; + } const yrTopicData = entity.topic_data[selectedTopic] || []; // 1. Add line series for the currently selected topic (placed in Grid 0) @@ -194,6 +197,9 @@ export class UniTrendChartComponent { trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { const color = getEntityColor(entityIdx); + if ((entity as any).visible === false) { + return; + } const yrTopicData = entity.topic_data[selectedTopic] || []; // Recalculate cumulative sum map for this entity @@ -329,14 +335,7 @@ export class UniTrendChartComponent { }, }, legend: { - orient: 'vertical', - right: 10, - top: 'middle', - type: 'scroll', - textStyle: { color: '#4b5563' }, - formatter: (name: string) => { - return name.length > 22 ? name.substring(0, 20) + '...' : name; - }, + show: false, }, axisPointer: { link: [{ xAxisIndex: 'all' }], @@ -345,13 +344,13 @@ export class UniTrendChartComponent { grid: [ { left: 80, - right: 220, + right: 50, top: 80, height: 230, }, { left: 80, - right: 220, + right: 50, top: 360, height: 70, }, diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 69c6a181..405ba5c1 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -21,162 +21,28 @@ -
-

2. Zeitraum

-
- - bis - -
-
+ + -
-

3. Länder/Kontinente vergleichen

- -
- @if ( - comparisonCountries().length > 0 || comparisonRegions().length > 0 - ) { - @for (c of comparisonCountries(); track c.id) { -
- flag {{ c.name }} - -
- } - @for (r of comparisonRegions(); track r.id) { -
- public {{ r.name }} - -
- } - } @else { -
- Keine Länder/Kontinente ausgewählt. Suchen zum Hinzufügen. -
- } -
- - - -
- - -
-

4. Einrichtungen vergleichen

- - @if (primaryInstitutionName()) { -
- Zugewiesen: - {{ primaryInstitutionName() }} -
- } - -
- @if (comparisonInstitutions().length > 0) { - @for (inst of comparisonInstitutions(); track inst.id) { -
- apartment {{ inst.name }} - -
- } - } @else { -
- Keine weiteren Einrichtungen ausgewählt. Suchen zum Hinzufügen. -
- } -
- - -
- - -
- -
+ + @@ -232,50 +98,22 @@ [endYear]="endYear()"> - -
-

- Empfohlene Top-Einrichtungen für das Thema: {{ activeChartTopic() }} -

-
- @if (isSuggestionsLoading()) { -
-
- Empfehlungen werden geladen... -
- } @else { - @if (topSuggestions().length === 0) { -

- Keine Empfehlungen für dieses Thema gefunden. -

- } @else { -
- @for (item of topSuggestions(); track item.id || '') { - - } -
- } - } -
-
+ + + diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 68ec8b97..0e630880 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -31,10 +31,6 @@ margin: 0 0 0.75rem 0; letter-spacing: 0.05em; } - - &.suggestions-card { - background: #fafafa; - } } .checkbox-group { @@ -59,211 +55,13 @@ } } -.comparison-list { - display: flex; - flex-direction: column; - gap: 0.4rem; - max-height: 140px; - overflow-y: auto; - margin-bottom: 0.75rem; - - .empty-list-info { - font-size: 0.75rem; - color: #9ca3af; - text-align: center; - padding: 8px 0; - border: 1px dashed #e5e7eb; - border-radius: 5px; - } -} - -.comparison-item { - display: flex; - justify-content: space-between; - align-items: center; - background: #f3f4f6; - border: 1px solid #e5e7eb; +.empty-list-info { + font-size: 0.75rem; + color: #9ca3af; + text-align: center; + padding: 8px 0; + border: 1px dashed #e5e7eb; border-radius: 5px; - padding: 0.3rem 0.5rem; - - .item-name { - display: inline-flex; - align-items: center; - gap: 4px; - font-size: 0.75rem; - color: #374151; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - max-width: 210px; - - mat-icon { - font-size: 14px; - width: 14px; - height: 14px; - } - } - - .remove-btn { - background: none; - border: none; - color: #9ca3af; - cursor: pointer; - padding: 1px 4px; - border-radius: 3px; - display: inline-flex; - align-items: center; - justify-content: center; - - mat-icon { - font-size: 12px; - width: 12px; - height: 12px; - } - - &:hover { - color: #ef4444; - background: #fee2e2; - } - } - - &.location-item { - &.font-country { - background: #f0fdf4 !important; - border-color: #bbf7d0 !important; - .item-name { - color: #166534 !important; - } - } - &.font-region { - background: #eff6ff !important; - border-color: #bfdbfe !important; - .item-name { - color: #1e40af !important; - } - } - } -} - -.autocomplete-search { - position: relative; - width: 100%; - - input { - width: 100%; - padding: 0.5rem; - border-radius: 5px; - border: 1px solid #d1d5db; - font-size: 0.8125rem; - outline: none; - box-sizing: border-box; - &:focus { - border-color: #3b82f6; - } - } -} - -.autocomplete-results { - position: absolute; - top: 100%; - left: 0; - right: 0; - z-index: 50; - background: white; - border: 1px solid #e5e7eb; - border-radius: 5px; - box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); - margin-top: 3px; - padding: 0; - list-style: none; - max-height: 180px; - overflow-y: auto; - - li button { - width: 100%; - text-align: left; - background: none; - border: none; - padding: 0.5rem 0.75rem; - cursor: pointer; - display: flex; - flex-direction: column; - &:hover { - background: #f3f4f6; - } - - .name { - font-size: 0.75rem; - font-weight: 500; - color: #1f2937; - } - .hint { - font-size: 0.65rem; - color: #9ca3af; - margin-top: 1px; - } - } -} - -.suggestions-list { - display: flex; - flex-direction: column; - gap: 0.4rem; - - .suggestions-loader { - font-size: 0.75rem; - color: #9ca3af; - text-align: center; - padding: 8px 0; - } -} - -.suggestion-item { - display: flex; - justify-content: space-between; - align-items: center; - background: white; - border: 1px solid #e5e7eb; - border-radius: 6px; - padding: 0.4rem 0.6rem; - text-align: left; - cursor: pointer; - - &:hover:not([disabled]) { - border-color: #3b82f6; - background: #f0f9ff; - transform: translateY(-1px); - } - - &[disabled] { - opacity: 0.5; - cursor: not-allowed; - background: #f3f4f6; - } - - .info { - display: flex; - flex-direction: column; - max-width: 210px; - - .name { - font-size: 0.75rem; - color: #374151; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } - .meta { - font-size: 0.65rem; - color: #9ca3af; - margin-top: 1px; - } - } - .add-icon { - font-size: 1rem; - color: #3b82f6; - font-weight: 600; - } } .trend-main { @@ -341,40 +139,6 @@ padding: 0.6rem 1rem; background: #f9fafb; border-bottom: 1px solid #e5e7eb; - - button { - padding: 0.3rem 0.6rem; - border: 1px solid #e5e7eb; - background: white; - color: #4b5563; - border-radius: 5px; - font-size: 0.75rem; - font-weight: 500; - cursor: pointer; - transition: all 0.15s ease; - display: inline-flex; - align-items: center; - gap: 4px; - - mat-icon { - font-size: 14px; - width: 14px; - height: 14px; - } - - &:hover { - border-color: #3b82f6; - color: #3b82f6; - background: #f0f9ff; - } - - &.active { - background: #3b82f6; - border-color: #3b82f6; - color: white; - font-weight: 600; - } - } } .loader-overlay { @@ -407,193 +171,11 @@ } } -.search-trend-btn-container { - display: flex; - justify-content: flex-end; - padding: 0.5rem 0; -} - -.search-trend-btn { - display: flex; - align-items: center; - gap: 0.5rem; - padding: 0.6rem 1.2rem; - border-radius: 6px; - font-size: 0.875rem; - font-weight: 600; - cursor: pointer; - border: 1px solid #3b82f6; - background-color: #3b82f6; - color: white; - transition: all 0.2s ease; - - mat-icon { - font-size: 18px; - width: 18px; - height: 18px; - } - - &:hover:not([disabled]) { - background-color: #2563eb; - border-color: #2563eb; - box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.2); - } - - &[disabled] { - opacity: 0.6; - cursor: not-allowed; - background-color: #9ca3af; - border-color: #9ca3af; - } - - &.dirty { - animation: pulse-border 2s infinite; - background-color: #2563eb; - border-color: #1d4ed8; - } -} - -.year-selectors { - display: flex; - gap: 0.5rem; - align-items: center; - - select { - flex: 1; - padding: 0.4rem; - border-radius: 5px; - border: 1px solid #d1d5db; - font-size: 0.8125rem; - background: white; - outline: none; - &:focus { - border-color: #3b82f6; - } - } -} - @keyframes spin { - to { + 0% { + transform: rotate(0deg); + } + 100% { transform: rotate(360deg); } } - -@keyframes pulse-border { - 0% { - box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); - } - 70% { - box-shadow: 0 0 0 6px rgba(59, 130, 246, 0); - } - 100% { - box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); - } -} - -.suggestions-below-card { - background: white; - border-radius: 10px; - padding: 1.25rem; - border: 1px solid #e5e7eb; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); - margin-top: 1rem; - - h3 { - font-size: 0.875rem; - font-weight: 600; - color: #374151; - margin: 0 0 1rem 0; - } - - .suggestions-loader { - display: flex; - align-items: center; - gap: 0.5rem; - color: #6b7280; - font-size: 0.8125rem; - padding: 1rem 0; - - .spinner-small { - width: 16px; - height: 16px; - border: 2px solid rgba(59, 130, 246, 0.1); - border-radius: 50%; - border-top-color: #3b82f6; - animation: spin 0.8s linear infinite; - } - } - - .no-suggestions-msg { - font-size: 0.8125rem; - color: #6b7280; - text-align: center; - padding: 1rem 0; - } - - .suggestions-flex { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); - gap: 0.75rem; - } -} - -.suggestion-item-horizontal { - display: flex; - align-items: center; - gap: 0.75rem; - background: #f9fafb; - border: 1px solid #e5e7eb; - border-radius: 8px; - padding: 0.6rem 0.8rem; - text-align: left; - cursor: pointer; - transition: all 0.2s ease; - width: 100%; - box-sizing: border-box; - - &:hover:not([disabled]) { - border-color: #3b82f6; - background: #f0f9ff; - transform: translateY(-1px); - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); - } - - &[disabled] { - opacity: 0.5; - cursor: not-allowed; - background: #f3f4f6; - } - - .add-icon { - color: #3b82f6; - display: flex; - align-items: center; - justify-content: center; - width: 20px; - height: 20px; - border-radius: 50%; - background: rgba(59, 130, 246, 0.1); - flex-shrink: 0; - font-size: 14px; - } - - .info { - display: flex; - flex-direction: column; - overflow: hidden; - - .name { - font-size: 0.8125rem; - color: #374151; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - font-weight: 600; - } - .meta { - font-size: 0.7rem; - color: #6b7280; - margin-top: 2px; - } - } -} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 2aa8650c..1e7ae1fe 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -35,6 +35,9 @@ import { } from '../../../api'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { YearRangeSliderComponent } from '../../../shared/ui/year-range-slider/year-range-slider.component'; +import { LocationSelectorComponent } from '../../../shared/ui/location-selector/location-selector.component'; +import { InstitutionSelectorComponent } from '../../../shared/ui/institution-selector/institution-selector.component'; export interface CompareItem { id: string; @@ -47,15 +50,14 @@ export interface CompareItem { CommonModule, FormsModule, UniTrendChartComponent, - MatFormFieldModule, - MatInputModule, - MatSelectModule, MatCheckboxModule, MatButtonModule, MatIconModule, MatProgressSpinnerModule, - MatAutocompleteModule, TopicChipComponent, + YearRangeSliderComponent, + LocationSelectorComponent, + InstitutionSelectorComponent, ], templateUrl: './uni-trend-parent.component.html', styleUrl: './uni-trend-parent.component.scss', @@ -113,6 +115,58 @@ export class UniTrendParentComponent implements OnInit { // Years array for selects readonly availableYears: number[] = []; + readonly entityVisibilityMap = signal>(new Map()); + + isVisible(id: string): boolean { + return this.entityVisibilityMap().get(id) !== false; + } + + toggleVisibility(id: string): void { + this.entityVisibilityMap.update((map) => { + const newMap = new Map(map); + const current = newMap.get(id) !== false; + newMap.set(id, !current); + return newMap; + }); + } + + getEntityColor(entityId: string): string { + const defaultInstId = 'https://openalex.org/I62318514'; + const primaryId = this.primaryInstitution() || defaultInstId; + const insts = this.comparisonInstitutions().map((i) => i.id); + const countries = this.comparisonCountries().map((c) => c.id); + const regions = this.comparisonRegions().map((r) => r.id); + + const orderedIds = [primaryId, ...insts, ...countries, ...regions]; + + const idx = orderedIds.indexOf(entityId); + if (idx === -1) return '#9ca3af'; + + const entityColors = [ + '#3b82f6', + '#10b981', + '#f59e0b', + '#ec4899', + '#8b5cf6', + '#06b6d4', + '#6366f1', + '#ef4444', + '#14b8a6', + '#f97316', + '#d946ef', + '#84cc16', + '#22c55e', + '#a855f7', + '#eab308', + '#f43f5e', + ]; + + return entityColors[idx % entityColors.length]; + } + + readonly boundGetEntityColor = (id: string) => this.getEntityColor(id); + readonly boundIsVisible = (id: string) => this.isVisible(id); + // Computed: filters out items locally if they were removed from list readonly trendResponse = computed(() => { const raw = this.rawTrendResponse(); @@ -129,63 +183,46 @@ export class UniTrendParentComponent implements OnInit { ); const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase(); - const filteredSeries = raw.series.filter((s: TrendSeries) => { + const primaryInstSeries: TrendSeries[] = []; + const compInstSeries: TrendSeries[] = []; + const countrySeries: TrendSeries[] = []; + const regionSeries: TrendSeries[] = []; + + raw.series.forEach((s: TrendSeries) => { const id = s.entity_id.toLowerCase(); if (s.entity_type === 'institution') { - return id === defaultInstId || currentInstIds.has(id); + if (id === defaultInstId) { + primaryInstSeries.push(s); + } else if (currentInstIds.has(id)) { + compInstSeries.push(s); + } } else if (s.entity_type === 'country') { - return currentCountryIds.has(id); + if (currentCountryIds.has(id)) { + countrySeries.push(s); + } } else if (s.entity_type === 'region') { - return currentRegionIds.has(id); + if (currentRegionIds.has(id)) { + regionSeries.push(s); + } } - return false; }); + const filteredSeries = [ + ...primaryInstSeries, + ...compInstSeries, + ...countrySeries, + ...regionSeries, + ].map((s) => ({ + ...s, + visible: this.isVisible(s.entity_id), + })); + return { ...raw, series: filteredSeries, }; }); - // Computed dirty state to enable "Search" button - readonly isDirty = computed(() => { - const fetchedInsts = this.fetchedInstitutions() - .map((i: CompareItem) => i.id) - .sort() - .join(','); - const currentInsts = this.comparisonInstitutions() - .map((i: CompareItem) => i.id) - .sort() - .join(','); - if (fetchedInsts !== currentInsts) return true; - - const fetchedC = this.fetchedCountries() - .map((c: CompareItem) => c.id) - .sort() - .join(','); - const currentC = this.comparisonCountries() - .map((c: CompareItem) => c.id) - .sort() - .join(','); - if (fetchedC !== currentC) return true; - - const fetchedR = this.fetchedRegions() - .map((r: CompareItem) => r.id) - .sort() - .join(','); - const currentR = this.comparisonRegions() - .map((r: CompareItem) => r.id) - .sort() - .join(','); - if (fetchedR !== currentR) return true; - - const fetchedT = this.fetchedTopics().sort().join(','); - const currentT = this.selectedTrendTopics().sort().join(','); - if (fetchedT !== currentT) return true; - - return false; - }); - constructor() { // Generate year range from 2000 to current year const currentYear = new Date().getFullYear(); @@ -238,6 +275,59 @@ export class UniTrendParentComponent implements OnInit { }); }); + // Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive) + effect(() => { + const topics = this.selectedTrendTopics(); + const insts = this.comparisonInstitutions(); + const countries = this.comparisonCountries(); + const regions = this.comparisonRegions(); + + if (topics.length === 0) return; + + const topicsStr = [...topics].sort().join(','); + const fetchedT = untracked(() => this.fetchedTopics()) + .sort() + .join(','); + + const instsStr = insts + .map((i) => i.id) + .sort() + .join(','); + const fetchedI = untracked(() => this.fetchedInstitutions()) + .map((i) => i.id) + .sort() + .join(','); + + const countriesStr = countries + .map((c) => c.id) + .sort() + .join(','); + const fetchedC = untracked(() => this.fetchedCountries()) + .map((c) => c.id) + .sort() + .join(','); + + const regionsStr = regions + .map((r) => r.id) + .sort() + .join(','); + const fetchedR = untracked(() => this.fetchedRegions()) + .map((r) => r.id) + .sort() + .join(','); + + if ( + topicsStr === fetchedT && + instsStr === fetchedI && + countriesStr === fetchedC && + regionsStr === fetchedR + ) { + return; + } + + untracked(() => this.fetchTrendData()); + }); + // Handle initialization and synchronization of URL state this.route.queryParams.subscribe((params) => { // Parse institutions serialized as id|name -- 2.56.1 From bfa91a684ede259238ee251af9191351622a9b83 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 10 Jul 2026 13:52:26 +0200 Subject: [PATCH 05/20] changed year slider to provide final value instead of updating everything on the way. Fixed parent component to not call api on change if information is already available --- .../uni-trend-parent.component.html | 19 --- .../uni-trend-parent.component.ts | 115 ++++++++++++------ .../year-range-slider.component.html | 8 +- .../year-range-slider.component.ts | 51 ++++++-- 4 files changed, 123 insertions(+), 70 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 405ba5c1..7fd2abbb 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -1,25 +1,6 @@
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 0e630880..6146c6cc 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -179,3 +179,47 @@ transform: rotate(360deg); } } + +.strategy-toggles-bar { + display: flex; + flex-wrap: wrap; + gap: 8px; + background: #f8fafc; + border-radius: 12px; + padding: 6px; + border: 1px solid #e2e8f0; + margin-bottom: 0.5rem; + + button { + padding: 0.5rem 1rem; + border: none; + background: none; + font-size: 0.75rem; + font-weight: 600; + color: #64748b; + border-radius: 8px; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; + transition: all 0.2s ease; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &:hover:not(.active) { + color: #0f172a; + background: #f1f5f9; + } + &.active { + background: white; + color: #3b82f6; + box-shadow: + 0 4px 6px -1px rgba(0, 0, 0, 0.05), + 0 2px 4px -1px rgba(0, 0, 0, 0.03); + } + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 879b30ce..e145ecd6 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -32,20 +32,78 @@ import { AutocompleteResponseResultsInner, UniversityRankingsService, InstitutionsService, + PersonsService, } from '../../../api'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { YearRangeSliderComponent } from '../../../shared/ui/year-range-slider/year-range-slider.component'; import { LocationSelectorComponent } from '../../../shared/ui/location-selector/location-selector.component'; import { InstitutionSelectorComponent } from '../../../shared/ui/institution-selector/institution-selector.component'; +import { AuthorSelectorComponent } from '../../../shared/ui/author-selector/author-selector.component'; +import { AuthorInstitutionSelectorComponent } from '../../../shared/ui/author-institution-selector/author-institution-selector.component'; +import { SearchResultsStateService } from '../../keywords-search/search-results/search-results-state.service'; export interface CompareItem { id: string; name: string; } +export interface TrendStrategyConfig { + showInstitutionSelector: boolean; + showLocationSelector: boolean; + showAuthorSelector: boolean; + yAxisLabel: string; + chartTitle: string; +} + +export const TREND_CONFIGS: Record = { + publications: { + showInstitutionSelector: true, + showLocationSelector: true, + showAuthorSelector: false, + yAxisLabel: 'Publikationen', + chartTitle: 'Publikationstrends', + }, + authors: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: true, + yAxisLabel: 'Publikationen von Autoren', + chartTitle: 'Autorentrends', + }, + patents: { + showInstitutionSelector: true, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Patentanmeldungen', + chartTitle: 'Patentrecherche-Trends', + }, + projects: { + showInstitutionSelector: true, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Projektförderung (Anz)', + chartTitle: 'Drittmittelförderung-Trends', + }, + news: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Pressemitteilungen', + chartTitle: 'Nachrichtentrends', + }, + all: { + showInstitutionSelector: false, + showLocationSelector: false, + showAuthorSelector: false, + yAxisLabel: 'Aktivitäts-Index', + chartTitle: 'Cross-Domain-Themenlebenszyklus (UDE)', + }, +}; + @Component({ selector: 'app-uni-trend-parent', + standalone: true, imports: [ CommonModule, FormsModule, @@ -58,6 +116,8 @@ export interface CompareItem { YearRangeSliderComponent, LocationSelectorComponent, InstitutionSelectorComponent, + AuthorSelectorComponent, + AuthorInstitutionSelectorComponent, ], templateUrl: './uni-trend-parent.component.html', styleUrl: './uni-trend-parent.component.scss', @@ -66,13 +126,22 @@ export interface CompareItem { export class UniTrendParentComponent implements OnInit { private readonly apiService = inject(UniversityRankingsService); private readonly institutionsApiService = inject(InstitutionsService); + private readonly personsApiService = inject(PersonsService); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); + // Inject SearchResultsStateService optionally if loaded in keywords search + private readonly state = inject(SearchResultsStateService, { + optional: true, + }); + // Input containing extracted/selected keywords from parent readonly keywords = input([]); // Trend settings signals + readonly selectedSearchType = signal< + 'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all' + >('publications'); readonly selectedTrendTopics = signal([]); readonly primaryInstitution = signal(null); readonly primaryInstitutionName = signal( @@ -83,6 +152,7 @@ export class UniTrendParentComponent implements OnInit { { id: 'DE', name: 'Deutschland' }, ]); readonly comparisonRegions = signal([]); + readonly comparisonAuthors = signal([]); readonly startYear = signal(2010); readonly endYear = signal(2025); readonly chartMode = signal<'normalized' | 'total' | 'cumulative'>( @@ -90,16 +160,24 @@ export class UniTrendParentComponent implements OnInit { ); readonly activeChartTopic = signal(''); + // Config mapper for active strategy UI representation + readonly activeConfig = computed( + () => TREND_CONFIGS[this.selectedSearchType()], + ); + // Cached parameters of the last active search request to track "isDirty" + readonly fetchedSearchType = signal(null); readonly fetchedTopics = signal([]); readonly fetchedInstitutions = signal([]); readonly fetchedCountries = signal([]); readonly fetchedRegions = signal([]); + readonly fetchedAuthors = signal([]); // Results & Loading signals readonly rawTrendResponse = signal(null); readonly isTrendLoading = signal(false); readonly topSuggestions = signal([]); + readonly recommendedAuthors = signal([]); readonly isSuggestionsLoading = signal(false); getTopicColor(topic: string): string { @@ -111,6 +189,12 @@ export class UniTrendParentComponent implements OnInit { readonly searchResults = signal([]); readonly locationQuery = signal(''); readonly locationSearchResults = signal([]); + readonly authorSearchQuery = signal(''); + readonly authorSearchResults = signal([]); + readonly authorInstSearchQuery = signal(''); + readonly authorInstSearchResults = signal( + [], + ); // Years array for selects readonly availableYears: number[] = []; @@ -136,8 +220,15 @@ export class UniTrendParentComponent implements OnInit { const insts = this.comparisonInstitutions().map((i) => i.id); const countries = this.comparisonCountries().map((c) => c.id); const regions = this.comparisonRegions().map((r) => r.id); + const authors = this.comparisonAuthors().map((a) => a.id); - const orderedIds = [primaryId, ...insts, ...countries, ...regions]; + const orderedIds = [ + primaryId, + ...insts, + ...countries, + ...regions, + ...authors, + ]; const idx = orderedIds.indexOf(entityId); if (idx === -1) return '#9ca3af'; @@ -172,6 +263,34 @@ export class UniTrendParentComponent implements OnInit { const raw = this.rawTrendResponse(); if (!raw) return null; + const type = this.selectedSearchType(); + if (type === 'news' || type === 'all') { + return { + ...raw, + series: raw.series.map((s) => ({ + ...s, + visible: this.isVisible(s.entity_id), + })), + }; + } + + if (type === 'authors') { + const currentAuthorIds = new Set( + this.comparisonAuthors().map((a) => a.id.toLowerCase()), + ); + const filtered = raw.series + .filter((s) => currentAuthorIds.has(s.entity_id.toLowerCase())) + .map((s) => ({ + ...s, + visible: this.isVisible(s.entity_id), + })); + return { + ...raw, + series: filtered, + }; + } + + // Default: publications, patents, projects const currentInstIds = new Set( this.comparisonInstitutions().map((i: CompareItem) => i.id.toLowerCase()), ); @@ -235,6 +354,7 @@ export class UniTrendParentComponent implements OnInit { const kws = this.keywords(); const currentSelections = untracked(() => this.selectedTrendTopics()); const currentActive = untracked(() => this.activeChartTopic()); + const searchType = this.selectedSearchType(); if (kws.length > 0) { // Find existing selections that are still in keywords, or default to all @@ -254,10 +374,17 @@ export class UniTrendParentComponent implements OnInit { this.activeChartTopic.set(updatedSelections[0] || ''); } - // If comparison list is empty, initialize default institutions dynamically - const currentInsts = untracked(() => this.comparisonInstitutions()); - if (currentInsts.length === 0) { - untracked(() => this.initializeDefaultInstitutions()); + // If comparison list is empty, initialize default institutions/authors dynamically + if (searchType === 'authors') { + const currentAuthors = untracked(() => this.comparisonAuthors()); + if (currentAuthors.length === 0) { + untracked(() => this.initializeDefaultAuthors()); + } + } else { + const currentInsts = untracked(() => this.comparisonInstitutions()); + if (currentInsts.length === 0) { + untracked(() => this.initializeDefaultInstitutions()); + } } } else { this.selectedTrendTopics.set([]); @@ -275,46 +402,62 @@ export class UniTrendParentComponent implements OnInit { }); }); - // Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive) + // Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with subset check) effect(() => { const topics = this.selectedTrendTopics(); const insts = this.comparisonInstitutions(); const countries = this.comparisonCountries(); const regions = this.comparisonRegions(); + const authors = this.comparisonAuthors(); + const searchType = this.selectedSearchType(); if (topics.length === 0) return; - // Check if all requested topics and entities are subsets of what was already fetched const fetchedT = new Set(untracked(() => this.fetchedTopics())); - const fetchedI = new Set( - untracked(() => this.fetchedInstitutions()).map((i) => - i.id.toLowerCase(), - ), - ); - const fetchedC = new Set( - untracked(() => this.fetchedCountries()).map((c) => c.id.toLowerCase()), - ); - const fetchedR = new Set( - untracked(() => this.fetchedRegions()).map((r) => r.id.toLowerCase()), - ); + const fetchedType = untracked(() => this.fetchedSearchType()); const allTopicsFetched = topics.every((t) => fetchedT.has(t)); - const allInstsFetched = insts.every((i) => - fetchedI.has(i.id.toLowerCase()), - ); - const allCountriesFetched = countries.every((c) => - fetchedC.has(c.id.toLowerCase()), - ); - const allRegionsFetched = regions.every((r) => - fetchedR.has(r.id.toLowerCase()), - ); + const sameType = searchType === fetchedType; - if ( - allTopicsFetched && - allInstsFetched && - allCountriesFetched && - allRegionsFetched - ) { + let allEntitiesFetched = false; + if (sameType) { + if (searchType === 'authors') { + const fetchedA = new Set( + untracked(() => this.fetchedAuthors()).map((a) => + a.id.toLowerCase(), + ), + ); + allEntitiesFetched = authors.every((a) => + fetchedA.has(a.id.toLowerCase()), + ); + } else if (searchType === 'news' || searchType === 'all') { + allEntitiesFetched = true; + } else { + // publications, patents, projects + const fetchedI = new Set( + untracked(() => this.fetchedInstitutions()).map((i) => + i.id.toLowerCase(), + ), + ); + const fetchedC = new Set( + untracked(() => this.fetchedCountries()).map((c) => + c.id.toLowerCase(), + ), + ); + const fetchedR = new Set( + untracked(() => this.fetchedRegions()).map((r) => + r.id.toLowerCase(), + ), + ); + allEntitiesFetched = + insts.every((i) => fetchedI.has(i.id.toLowerCase())) && + countries.every((c) => fetchedC.has(c.id.toLowerCase())) && + regions.every((r) => fetchedR.has(r.id.toLowerCase())); + } + } + + const hasResponse = !!untracked(() => this.rawTrendResponse()); + if (allTopicsFetched && sameType && allEntitiesFetched && hasResponse) { // All requested data is already present in rawTrendResponse, so skip backend call! return; } @@ -324,6 +467,10 @@ export class UniTrendParentComponent implements OnInit { // Handle initialization and synchronization of URL state this.route.queryParams.subscribe((params) => { + if (params['search_type']) { + this.selectedSearchType.set(params['search_type'] as any); + } + // Parse institutions serialized as id|name if (params['institutions']) { const insts = Array.isArray(params['institutions']) @@ -405,6 +552,33 @@ export class UniTrendParentComponent implements OnInit { } } + // Parse authors + if (params['authors']) { + const auths = Array.isArray(params['authors']) + ? params['authors'] + : [params['authors']]; + const parsed = auths.map((a: string) => { + const parts = a.split('|'); + return { id: parts[0], name: parts[1] || parts[0] }; + }); + + const currentIds = this.comparisonAuthors() + .map((a) => a.id) + .sort() + .join(','); + const parsedIds = parsed + .map((a) => a.id) + .sort() + .join(','); + if (currentIds !== parsedIds) { + this.comparisonAuthors.set(parsed); + } + } else { + if (this.comparisonAuthors().length > 0) { + this.comparisonAuthors.set([]); + } + } + if (params['start_year']) { this.startYear.set(Number(params['start_year'])); } @@ -429,7 +603,9 @@ export class UniTrendParentComponent implements OnInit { const kws = this.keywords(); if (kws.length === 0) return; - const topic = kws[0]; + // Use mapped topic names if softSearch is false + const topics = this.state?.topicsList() ?? kws; + const topic = topics[0] || kws[0] || 'Artificial Intelligence'; this.isSuggestionsLoading.set(true); forkJoin({ @@ -457,13 +633,11 @@ export class UniTrendParentComponent implements OnInit { }) => { const uniqueInsts = new Map(); - // Add DE ones deInsts.forEach((inst: TopInstitutionItem) => { if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); }); - // Add overall ones overallInsts.forEach((inst: TopInstitutionItem) => { if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); @@ -476,7 +650,6 @@ export class UniTrendParentComponent implements OnInit { this.comparisonInstitutions.set(list); this.isSuggestionsLoading.set(false); - // Auto-fetch trend data on first load if we don't have it yet if (!this.rawTrendResponse()) { this.fetchTrendData(); } @@ -488,15 +661,62 @@ export class UniTrendParentComponent implements OnInit { }); } - // Fetch recommended institutions for comparison based on current topics - loadTrendSuggestions() { + // Dynamically load top authors for UDE to initialize comparison list + initializeDefaultAuthors() { + const kws = this.keywords(); + if (kws.length === 0) return; + + const topics = this.state?.topicsList() ?? kws; + const topic = topics[0] || kws[0] || 'Artificial Intelligence'; this.isSuggestionsLoading.set(true); + + this.personsApiService + .searchPersonsList( + undefined, // query + 'University of Duisburg-Essen', // primary institution + undefined, // sortBy + undefined, // sortOrder + [topic], // topic + 1, // page + 3, // pageSize + undefined, // include (fetch all fields!) + ) + .subscribe({ + next: (res) => { + const list = (res.results || []).map((author: any) => ({ + id: author.id, + name: author.display_name || 'Unbekannt', + })); + this.comparisonAuthors.set(list); + this.isSuggestionsLoading.set(false); + + if (!this.rawTrendResponse()) { + this.fetchTrendData(); + } + }, + error: (err) => { + console.error('Failed to load default authors:', err); + this.isSuggestionsLoading.set(false); + }, + }); + } + + // Fetch recommended institutions or authors for comparison based on current topics + loadTrendSuggestions() { + if (this.selectedSearchType() === 'authors') { + this.loadRecommendedAuthors(); + return; + } + + this.isSuggestionsLoading.set(true); + const kws = this.keywords(); + const topics = this.state?.topicsList() ?? kws; const topic = this.activeChartTopic() || (this.selectedTrendTopics().length > 0 ? this.selectedTrendTopics()[0] - : this.keywords().length > 0 - ? this.keywords()[0] + : topics.length > 0 + ? topics[0] : 'Artificial Intelligence'); const countryFilter = @@ -526,18 +746,57 @@ export class UniTrendParentComponent implements OnInit { }); } - // Trigger search trend data (only when "Search" is clicked) + // Load UDE recommended authors for selected topic + loadRecommendedAuthors() { + this.isSuggestionsLoading.set(true); + const kws = this.keywords(); + const topics = this.state?.topicsList() ?? kws; + const topic = + this.activeChartTopic() || + (this.selectedTrendTopics().length > 0 + ? this.selectedTrendTopics()[0] + : topics.length > 0 + ? topics[0] + : 'Artificial Intelligence'); + + this.personsApiService + .searchPersonsList( + undefined, // query + 'University of Duisburg-Essen', // UDE + undefined, // sortBy + undefined, // sortOrder + [topic], // topic + 1, // page + 6, // pageSize + undefined, // include (fetch all fields!) + ) + .subscribe({ + next: (res) => { + this.recommendedAuthors.set(res.results || []); + this.isSuggestionsLoading.set(false); + }, + error: () => { + this.isSuggestionsLoading.set(false); + }, + }); + } + + // Trigger search trend data fetchTrendData() { const topics = this.selectedTrendTopics(); if (topics.length === 0) return; this.isTrendLoading.set(true); - // Save parameters of this request to check dirty state later + this.fetchedSearchType.set(this.selectedSearchType()); this.fetchedTopics.set([...topics]); this.fetchedInstitutions.set([...this.comparisonInstitutions()]); this.fetchedCountries.set([...this.comparisonCountries()]); this.fetchedRegions.set([...this.comparisonRegions()]); + this.fetchedAuthors.set([...this.comparisonAuthors()]); + + const kws = this.state?.keywordsList() ?? []; + const softSearch = this.state?.softSearch() ?? true; this.apiService .getTrendApiInseServiceUniversityRankingsTrendGet( @@ -545,6 +804,10 @@ export class UniTrendParentComponent implements OnInit { this.comparisonInstitutions().map((i: CompareItem) => i.id), this.comparisonCountries().map((c: CompareItem) => c.id), this.comparisonRegions().map((r: CompareItem) => r.id), + kws, + softSearch, + this.selectedSearchType(), + this.comparisonAuthors().map((a: CompareItem) => a.id), ) .subscribe({ next: (response: TrendResponse) => { @@ -561,6 +824,7 @@ export class UniTrendParentComponent implements OnInit { // Update query params to synchronize state updateUrlParams() { const queryParams: any = { + search_type: this.selectedSearchType(), trend_topics: this.selectedTrendTopics(), institutions: this.comparisonInstitutions().length > 0 @@ -580,6 +844,12 @@ export class UniTrendParentComponent implements OnInit { (r: CompareItem) => `${r.id}|${r.name}`, ) : null, + authors: + this.comparisonAuthors().length > 0 + ? this.comparisonAuthors().map( + (a: CompareItem) => `${a.id}|${a.name}`, + ) + : null, start_year: this.startYear(), end_year: this.endYear(), chart_mode: this.chartMode(), @@ -613,13 +883,36 @@ export class UniTrendParentComponent implements OnInit { this.selectedTrendTopics.set(updated); - // Auto-update active tab selection if previous was removed const active = this.activeChartTopic(); if (!updated.includes(active)) { this.activeChartTopic.set(updated[0] || ''); } } + // Strategy SearchType changes + setSearchType( + type: 'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all', + ) { + this.selectedSearchType.set(type); + + // Auto-initialize default lists if empty for the target type + const kws = this.keywords(); + if (kws.length > 0) { + if (type === 'authors' && this.comparisonAuthors().length === 0) { + this.initializeDefaultAuthors(); + } else if ( + type !== 'authors' && + type !== 'news' && + type !== 'all' && + this.comparisonInstitutions().length === 0 + ) { + this.initializeDefaultInstitutions(); + } + } + + this.updateUrlParams(); + } + // Add comparison institution addInstitution(id: string, name: string) { const current = this.comparisonInstitutions(); @@ -633,7 +926,6 @@ export class UniTrendParentComponent implements OnInit { this.searchResults.set([]); } - // Remove comparison institution (data reuses instantly via computed) removeInstitution(id: string) { const current = this.comparisonInstitutions(); this.comparisonInstitutions.set( @@ -665,7 +957,6 @@ export class UniTrendParentComponent implements OnInit { this.loadTrendSuggestions(); } - // Remove country or region removeLocation(id: string, type: 'country' | 'continent') { if (type === 'country') { const current = this.comparisonCountries(); @@ -681,6 +972,63 @@ export class UniTrendParentComponent implements OnInit { this.loadTrendSuggestions(); } + // Add Top 3 Authors for a selected institution from institutions autocomplete + addInstitutionAuthors(id: string, name: string) { + const kws = this.keywords(); + const topics = this.state?.topicsList() ?? kws; + const topic = + this.activeChartTopic() || topics[0] || 'Artificial Intelligence'; + + this.isSuggestionsLoading.set(true); + + this.personsApiService + .searchPersonsList( + undefined, // query + name, // institutionName + undefined, // sortBy + undefined, // sortOrder + [topic], // topic + 1, // page + 3, // pageSize + undefined, // include + ) + .subscribe({ + next: (res) => { + const current = this.comparisonAuthors(); + const updated = [...current]; + (res.results || []).forEach((author: any) => { + if (author.id && !updated.some((a) => a.id === author.id)) { + updated.push({ + id: author.id, + name: author.display_name || 'Unbekannt', + }); + } + }); + this.comparisonAuthors.set(updated); + this.isSuggestionsLoading.set(false); + }, + error: (err) => { + console.error('Failed to load top authors for institution:', err); + this.isSuggestionsLoading.set(false); + }, + }); + + this.authorInstSearchQuery.set(''); + this.authorInstSearchResults.set([]); + } + + addAuthor(id: string, name: string) { + const current = this.comparisonAuthors(); + if (!current.some((a) => a.id === id)) { + this.comparisonAuthors.set([...current, { id, name }]); + } + } + + removeAuthor(id: string) { + const current = this.comparisonAuthors(); + this.comparisonAuthors.set(current.filter((a: CompareItem) => a.id !== id)); + } + // Scaling mode toggle (data reuses instantly) setChartMode(mode: 'normalized' | 'total' | 'cumulative') { this.chartMode.set(mode); @@ -732,4 +1080,45 @@ export class UniTrendParentComponent implements OnInit { this.locationSearchResults.set([]); } } + + // Autocomplete query changes for authors in the authors tab (direct search) + onAuthorSearchChange(query: string) { + this.authorSearchQuery.set(query); + if (query.trim().length >= 3) { + this.personsApiService + .searchPersonsAutocomplete( + query, + 'display_name,last_known_institutions', + ) + .subscribe({ + next: (res: any) => { + this.authorSearchResults.set(res.results || []); + }, + error: () => { + this.authorSearchResults.set([]); + }, + }); + } else { + this.authorSearchResults.set([]); + } + } + + // Autocomplete query changes for institutions inside the top-authors selector + onAuthorInstSearchChange(query: string) { + this.authorInstSearchQuery.set(query); + if (query.trim().length >= 3) { + this.institutionsApiService + .autocompleteInstitutions(query, undefined, 'education', 10) + .subscribe({ + next: (res: AutocompleteResponse) => { + this.authorInstSearchResults.set(res.results || []); + }, + error: () => { + this.authorInstSearchResults.set([]); + }, + }); + } else { + this.authorInstSearchResults.set([]); + } + } } diff --git a/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.html b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.html new file mode 100644 index 00000000..5cad7734 --- /dev/null +++ b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.html @@ -0,0 +1,32 @@ +
+
+
+

Top-Autoren einer Einrichtung hinzufügen

+
+ + + +
+
diff --git a/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss new file mode 100644 index 00000000..99442ae2 --- /dev/null +++ b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.scss @@ -0,0 +1,117 @@ +.author-institution-selector-container { + display: flex; + flex-direction: column; + background: white; + border: 1px solid #d7e4ff; + border-radius: 16px; + padding: 24px; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + box-sizing: border-box; + margin-top: 20px; + width: 100%; +} + +.search-compare-section { + display: flex; + flex-direction: column; + box-sizing: border-box; + + h3 { + font-size: 0.9rem; + font-weight: 700; + color: #07163d; + margin: 0 0 1rem 0; + line-height: 1.2; + } +} + +.section-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 0.5rem; + + h3 { + margin: 0; + } +} + +/* Autocomplete Search input */ +.autocomplete-search { + position: relative; + width: 100%; + + .search-icon { + position: absolute; + left: 10px; + top: 50%; + transform: translateY(-50%); + font-size: 18px; + width: 18px; + height: 18px; + color: #9ca3af; + pointer-events: none; + } + + input { + width: 100%; + padding: 0.6rem 0.6rem 0.6rem 2.2rem; + border-radius: 8px; + border: 1px solid #d1d5db; + font-size: 0.8125rem; + outline: none; + box-sizing: border-box; + transition: all 0.2s ease; + + &:focus { + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); + } + } +} + +.autocomplete-results { + position: absolute; + top: 100%; + left: 0; + right: 0; + z-index: 50; + background: white; + border: 1px solid #e5e7eb; + border-radius: 8px; + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); + margin-top: 4px; + padding: 4px 0; + list-style: none; + max-height: 200px; + overflow-y: auto; + + li button { + width: 100%; + text-align: left; + background: none; + border: none; + padding: 0.6rem 1rem; + cursor: pointer; + display: flex; + flex-direction: column; + transition: background 0.15s ease; + + &:hover { + background: #f3f4f6; + } + + .name { + font-size: 0.75rem; + font-weight: 600; + color: #1f2937; + } + .hint { + font-size: 0.65rem; + color: #6b7280; + margin-top: 2px; + } + } +} diff --git a/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.ts b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.ts new file mode 100644 index 00000000..d4600f5a --- /dev/null +++ b/webapp/src/app/shared/ui/author-institution-selector/author-institution-selector.component.ts @@ -0,0 +1,30 @@ +import { Component, input, output } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { MatIconModule } from '@angular/material/icon'; + +@Component({ + selector: 'app-author-institution-selector', + standalone: true, + imports: [CommonModule, MatIconModule], + templateUrl: './author-institution-selector.component.html', + styleUrl: './author-institution-selector.component.scss', +}) +export class AuthorInstitutionSelectorComponent { + readonly searchQuery = input(''); + readonly searchResults = input([]); + + readonly addInstitutionAuthors = output<{ id: string; name: string }>(); + readonly searchChange = output(); + + onSearchInput(event: Event): void { + const val = (event.target as HTMLInputElement).value; + this.searchChange.emit(val); + } + + onSelectResult(result: any): void { + this.addInstitutionAuthors.emit({ + id: result.id || '', + name: result.display_name || '', + }); + } +} diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.html b/webapp/src/app/shared/ui/author-selector/author-selector.component.html new file mode 100644 index 00000000..349f3c91 --- /dev/null +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.html @@ -0,0 +1,128 @@ +
+ +
+
+

Autoren vergleichen

+
+ + + + + +
+ @if (comparisonAuthors().length > 0) { +
+ @for (auth of comparisonAuthors(); track auth.id) { +
+ + person {{ auth.name }} + +
+ + +
+
+ } +
+ } @else { +
+ Keine Autoren ausgewählt. Suchen Sie nach Autoren, um sie zu + vergleichen. +
+ } +
+
+ + +
+

+ Empfohlene Top-Autoren (UDE) für das Thema: {{ activeChartTopic() }} +

+ +
+ @if (isSuggestionsLoading()) { +
+
+ Empfehlungen werden geladen... +
+ } @else { + @if (topSuggestions().length === 0) { +

+ Keine Autorenempfehlungen für dieses Thema gefunden. +

+ } @else { +
+ @for (item of topSuggestions(); track item.id || '') { + + } +
+ } + } +
+
+
diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.scss b/webapp/src/app/shared/ui/author-selector/author-selector.component.scss new file mode 100644 index 00000000..83d3db84 --- /dev/null +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.scss @@ -0,0 +1,320 @@ +.author-selector-container { + display: grid; + grid-template-columns: 1fr 1.5fr; + gap: 24px; + background: white; + border: 1px solid #d7e4ff; + border-radius: 16px; + padding: 24px; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + box-sizing: border-box; + margin-top: 20px; + + @media (max-width: 1024px) { + grid-template-columns: 1fr; + gap: 20px; + padding: 16px; + } +} + +.search-compare-section, +.recommendations-section { + display: flex; + flex-direction: column; + box-sizing: border-box; + + h3 { + font-size: 0.9rem; + font-weight: 700; + color: #07163d; + margin: 0 0 1rem 0; + line-height: 1.2; + } +} + +.section-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 0.5rem; + + h3 { + margin: 0; + } +} + +/* Autocomplete Search input */ +.autocomplete-search { + position: relative; + width: 100%; + margin-bottom: 1rem; + + .search-icon { + position: absolute; + left: 10px; + top: 50%; + transform: translateY(-50%); + font-size: 18px; + width: 18px; + height: 18px; + color: #9ca3af; + pointer-events: none; + } + + input { + width: 100%; + padding: 0.6rem 0.6rem 0.6rem 2.2rem; + border-radius: 8px; + border: 1px solid #d1d5db; + font-size: 0.8125rem; + outline: none; + box-sizing: border-box; + transition: all 0.2s ease; + + &:focus { + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); + } + } +} + +.autocomplete-results { + position: absolute; + top: 100%; + left: 0; + right: 0; + z-index: 50; + background: white; + border: 1px solid #e5e7eb; + border-radius: 8px; + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); + margin-top: 4px; + padding: 4px 0; + list-style: none; + max-height: 200px; + overflow-y: auto; + + li button { + width: 100%; + text-align: left; + background: none; + border: none; + padding: 0.6rem 1rem; + cursor: pointer; + display: flex; + flex-direction: column; + transition: background 0.15s ease; + + &:hover { + background: #f3f4f6; + } + + .name { + font-size: 0.75rem; + font-weight: 600; + color: #1f2937; + } + .hint { + font-size: 0.65rem; + color: #6b7280; + margin-top: 2px; + } + } +} + +/* Comparison list & chips */ +.comparison-list { + flex: 1; + min-height: 80px; + + .empty-list-info { + font-size: 0.75rem; + color: #9ca3af; + text-align: center; + padding: 16px; + border: 1px dashed #e5e7eb; + border-radius: 8px; + } +} + +.chips-flex { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + max-height: 180px; + overflow-y: auto; + padding-right: 4px; +} + +.comparison-item { + display: inline-flex; + justify-content: space-between; + align-items: center; + border: 1px solid #e5e7eb; + border-radius: 6px; + padding: 0.35rem 0.6rem; + gap: 8px; + transition: all 0.2s ease; + max-width: 100%; + + .item-name { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + } + + .item-actions { + display: flex; + align-items: center; + gap: 4px; + } + + .action-btn { + background: none; + border: none; + cursor: pointer; + padding: 2px; + border-radius: 4px; + display: inline-flex; + align-items: center; + justify-content: center; + transition: all 0.15s ease; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + + &:hover { + background: rgba(0, 0, 0, 0.05); + } + + &.remove-btn:hover { + color: #ef4444 !important; + background: #fee2e2; + } + } +} + +/* Recommendations suggestions section */ +.suggestions-grid { + flex: 1; + display: flex; + flex-direction: column; +} + +.suggestions-flex { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 10px; + max-height: 250px; + overflow-y: auto; + padding-right: 4px; + + @media (max-width: 600px) { + grid-template-columns: 1fr; + } +} + +.suggestion-item-horizontal { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 12px; + border: 1px solid #e5e7eb; + border-radius: 8px; + background: #f9fafb; + text-align: left; + cursor: pointer; + transition: all 0.2s ease; + box-sizing: border-box; + + &:hover:not(:disabled) { + background: #f3f4f6; + border-color: #3b82f6; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02); + } + + &:disabled { + opacity: 0.5; + cursor: not-allowed; + background: #f3f4f6; + } + + .add-icon { + color: #3b82f6; + font-size: 18px; + width: 18px; + height: 18px; + flex-shrink: 0; + } + + .info { + display: flex; + flex-direction: column; + min-width: 0; + + .name { + font-size: 0.75rem; + font-weight: 600; + color: #1f2937; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .meta { + font-size: 0.65rem; + color: #6b7280; + margin-top: 2px; + } + } +} + +.no-suggestions-msg { + font-size: 0.75rem; + color: #6b7280; + margin: 12px 0 0 0; +} + +.suggestions-loader { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.75rem; + color: #6b7280; + margin-top: 12px; +} + +.spinner-small { + width: 16px; + height: 16px; + border: 2px solid #e5e7eb; + border-top: 2px solid #3b82f6; + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.ts b/webapp/src/app/shared/ui/author-selector/author-selector.component.ts new file mode 100644 index 00000000..9e2f74f5 --- /dev/null +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.ts @@ -0,0 +1,63 @@ +import { Component, input, output } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { MatIconModule } from '@angular/material/icon'; + +export interface CompareItem { + id: string; + name: string; +} + +@Component({ + selector: 'app-author-selector', + standalone: true, + imports: [CommonModule, MatIconModule], + templateUrl: './author-selector.component.html', + styleUrl: './author-selector.component.scss', +}) +export class AuthorSelectorComponent { + readonly comparisonAuthors = input([]); + readonly topSuggestions = input([]); + readonly isSuggestionsLoading = input(false); + readonly searchQuery = input(''); + readonly searchResults = input([]); + readonly activeChartTopic = input(''); + readonly getEntityColor = input<(id: string) => string>(() => '#9ca3af'); + readonly isVisible = input<(id: string) => boolean>(() => true); + + readonly addAuthor = output<{ id: string; name: string }>(); + readonly removeAuthor = output(); + readonly searchChange = output(); + readonly toggleVisibility = output(); + + onSearchInput(event: Event): void { + const val = (event.target as HTMLInputElement).value; + this.searchChange.emit(val); + } + + onSelectResult(result: any): void { + this.addAuthor.emit({ + id: result.id || '', + name: result.display_name || '', + }); + } + + onSelectSuggestion(item: any): void { + this.addAuthor.emit({ + id: item.id || '', + name: item.display_name || 'Unbekannt', + }); + } + + onRemove(id: string): void { + this.removeAuthor.emit(id); + } + + onToggleVisibility(id: string): void { + this.toggleVisibility.emit(id); + } + + isAlreadyAdded(id: string | undefined): boolean { + if (!id) return false; + return this.comparisonAuthors().some((i) => i.id === id); + } +} -- 2.56.1 From 2bacb8e0f9839af00399f04ee382ec2579346066 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 10:30:38 +0200 Subject: [PATCH 07/20] changed filter to should in query --- .../src/main/inse/persons/query_builder.py | 67 ++++++++++--------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/service/src/main/inse/persons/query_builder.py b/service/src/main/inse/persons/query_builder.py index 7431558d..9938a970 100644 --- a/service/src/main/inse/persons/query_builder.py +++ b/service/src/main/inse/persons/query_builder.py @@ -365,42 +365,43 @@ def build_authors_search_rescored( }) else: filter_clauses.append({ - "bool": { - "filter": [ - { - "nested": { - "path": "last_known_institutions", - "query": { - "match_phrase": { - "last_known_institutions.display_name": institution_name + "bool": { + "should": [ + { + "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 + } + } + ] + } } } } - }, - { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "filter": [ - { - "match_phrase": { - "affiliations.institution.display_name": institution_name - } - }, - { - "range": { - "affiliations.years": range_query - } - } - ] - } - } - } - } - ] - } - }) + ], + "minimum_should_match": 1 + } + }) if topics: for t in topics: -- 2.56.1 From 4e66e581e17e136d3e767631324dc044d225d2b6 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 10:31:20 +0200 Subject: [PATCH 08/20] Strategy pattern in backend (mock for patent and projects for now) --- .../src/main/inse/university_ranking/model.py | 9 + .../main/inse/university_ranking/service.py | 44 +- .../university_ranking/trend_strategies.py | 894 ++++++++++++++++++ .../app/api/api/universityRankings.service.ts | 48 + .../search-results-state.service.ts | 12 + 5 files changed, 1001 insertions(+), 6 deletions(-) create mode 100644 service/src/main/inse/university_ranking/trend_strategies.py diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py index 18a2fb32..fbc403c0 100644 --- a/service/src/main/inse/university_ranking/model.py +++ b/service/src/main/inse/university_ranking/model.py @@ -4,6 +4,15 @@ from inse.models.openalex.topic import Topic DashboardMetric = Literal['publications', 'citations'] +from enum import Enum +class TrendSearchType(str, Enum): + PUBLICATIONS = "publications" + AUTHORS = "authors" + PATENTS = "patents" + PROJECTS = "projects" + NEWS = "news" + ALL = "all" + class YearlyData(BaseModel): year: int publications: int diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py index c81ae0ee..c5c7c9e5 100644 --- a/service/src/main/inse/university_ranking/service.py +++ b/service/src/main/inse/university_ranking/service.py @@ -1,6 +1,6 @@ import logging from typing import List, Optional -from fastapi import APIRouter, Query +from fastapi import APIRouter, Query, Depends from inse.tags import Tags from . import logic, trend_logic @@ -9,8 +9,10 @@ from .model import ( DashboardMetric, TrendResponse, TopInstitutionItem, - AutocompleteLocationItem + AutocompleteLocationItem, + TrendSearchType ) +from .trend_strategies import TrendStrategy logger = logging.getLogger(__name__) @@ -19,6 +21,29 @@ router = APIRouter( tags=[Tags.UNIVERSITY_RANKINGS] ) +def get_trend_strategy(search_type: TrendSearchType = Query(TrendSearchType.PUBLICATIONS)) -> TrendStrategy: + from .trend_strategies import ( + PublicationsTrendStrategy, + AuthorsTrendStrategy, + PatentsTrendStrategy, + ProjectsTrendStrategy, + NewsTrendStrategy, + AllTrendStrategy, + ) + if search_type == TrendSearchType.PUBLICATIONS: + return PublicationsTrendStrategy() + elif search_type == TrendSearchType.AUTHORS: + return AuthorsTrendStrategy() + elif search_type == TrendSearchType.PATENTS: + return PatentsTrendStrategy() + elif search_type == TrendSearchType.PROJECTS: + return ProjectsTrendStrategy() + elif search_type == TrendSearchType.NEWS: + return NewsTrendStrategy() + elif search_type == TrendSearchType.ALL: + return AllTrendStrategy() + raise ValueError(f"Unknown search type: {search_type}") + @router.get( "", response_model=RankingResponse, @@ -36,19 +61,26 @@ async def get_rankings( @router.get( "/trend", response_model=TrendResponse, - summary="Returns timeseries publication data for compared institutions, countries and regions." + summary="Returns timeseries publication data for compared institutions, countries, and regions." ) async def get_trend( topics: List[str] = Query(..., description="List of topics to analyze"), + keywords: Optional[List[str]] = Query(None, description="List of raw keywords corresponding to topics"), + soft_search: bool = Query(True, description="True if using mapped topics, False if using raw keywords"), institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"), countries: Optional[List[str]] = Query(None, description="List of country codes"), - regions: Optional[List[str]] = Query(None, description="List of region identifiers") + regions: Optional[List[str]] = Query(None, description="List of region identifiers"), + authors: Optional[List[str]] = Query(None, description="List of OpenAlex Author IDs"), + strategy: TrendStrategy = Depends(get_trend_strategy) ): - return await trend_logic.get_trend_data( + return await strategy.get_trend( topics=topics, + keywords=keywords, + soft_search=soft_search, institutions=institutions, countries=countries, - regions=regions + regions=regions, + authors=authors ) @router.get( diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py new file mode 100644 index 00000000..f7d65825 --- /dev/null +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -0,0 +1,894 @@ +import abc +import asyncio +import logging +import datetime +from typing import List, Dict, Any, Optional +import numpy as np +from sklearn.preprocessing import MinMaxScaler + +from inse.integrations import elasticsearch +from inse.model import ESIndex, ESCluster +from .model import ( + TrendResponse, + TrendSeries, + TopicYearlyData +) +from .trend_logic import ( + DEFAULT_INSTITUTION_ID, + DEFAULT_INSTITUTION_NAME +) + +logger = logging.getLogger(__name__) + +class TrendStrategy(abc.ABC): + @abc.abstractmethod + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + pass + + def _normalize_series( + self, + years_range: List[int], + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]], + topics: List[str] + ) -> Dict[tuple, Dict[str, List[float]]]: + series_keys = [] + raw_lists = [] + cumsum_lists = [] + + for entity_key, topic_dict in accumulated_data.items(): + for topic, year_dict in topic_dict.items(): + raw_counts = [] + for yr in years_range: + count, _ = year_dict[yr] + raw_counts.append(count) + + cumulative_counts = list(np.cumsum(raw_counts)) + series_keys.append((entity_key, topic)) + raw_lists.append(raw_counts) + cumsum_lists.append(cumulative_counts) + + normalized_lookup = {} + if raw_lists: + raw_matrix = np.array(raw_lists, dtype=float).T + cumsum_matrix = np.array(cumsum_lists, dtype=float).T + + scaler_raw = MinMaxScaler() + normalized_matrix = scaler_raw.fit_transform(raw_matrix) + + scaler_cumsum = MinMaxScaler() + normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix) + + normalized_lists = normalized_matrix.T.tolist() + normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist() + + for idx, (entity_key, topic) in enumerate(series_keys): + normalized_lookup[(entity_key, topic)] = { + "normalized": normalized_lists[idx], + "cumulative": normalized_cumsum_lists[idx] + } + return normalized_lookup + + +class PublicationsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + start_year = 2000 + end_year = datetime.datetime.now().year - 1 + years_range = list(range(start_year, end_year + 1)) + + primary_inst_id = DEFAULT_INSTITUTION_ID + primary_inst_name = DEFAULT_INSTITUTION_NAME + + query_institutions = [] + if institutions: + query_institutions = [i.strip() for i in institutions] + if primary_inst_id not in query_institutions: + query_institutions.insert(0, primary_inst_id) + + query_countries = countries or [] + query_regions = regions or [] + + clean_countries = [c.strip().upper() for c in query_countries] + clean_regions = [r.strip() for r in query_regions] + ids_to_resolve = list(set(query_institutions)) + + # Resolution lookups + async def fetch_institutions(): + names = {primary_inst_id: primary_inst_name} + codes = {} + if not ids_to_resolve: + return names, codes + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": ids_to_resolve}}, + size=len(ids_to_resolve), + source=["id", "display_name", "country_code"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + names[source["id"]] = source.get("display_name", source["id"]) + codes[source["id"]] = source.get("country_code", "") + except Exception as e: + logger.warning("Failed to resolve institution details from ES: %s", e) + return names, codes + + async def fetch_countries(): + names = {} + if not clean_countries: + return names + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_COUNTRIES), + query={"terms": {"country_code": clean_countries}}, + size=len(clean_countries), + source=["country_code", "display_name"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + names[source["country_code"]] = source["display_name"] + except Exception as e: + logger.warning("Failed to resolve country names from ES: %s", e) + return names + + async def fetch_continents(): + names = {} + ccodes = {} + if not clean_regions: + return names, ccodes + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_CONTINENTS), + query={ + "bool": { + "should": [ + {"terms": {"wikidata_id.keyword": clean_regions}}, + {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} + ] + } + }, + size=len(clean_regions), + source=["id", "display_name", "wikidata_id", "countries"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + c_code = source.get("wikidata_id") or source["id"].split("/")[-1] + names[c_code] = source["display_name"] + ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])] + except Exception as e: + logger.warning("Failed to resolve continent names from ES: %s", e) + return names, ccodes + + async def fetch_topics(): + t_ids = {} + try: + res = await elasticsearch.search( + index="openalex-topics", + query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}}, + size=len(topics) * 2, + source=["id", "display_name"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + for t in topics: + if t.lower() in source["display_name"].lower(): + t_ids[t] = source["id"] + except Exception as e: + logger.warning("Failed to resolve topic IDs from ES: %s", e) + return t_ids + + ( + (resolved_names, resolved_country_codes), + resolved_country_names, + (resolved_continent_names, continent_country_codes), + resolved_topic_ids + ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics()) + + location_mappings = continent_country_codes.copy() + + filters_map = {} + for inst_id in query_institutions: + filters_map[f"inst_{inst_id}"] = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.id": inst_id}} + } + } + for cc in clean_countries: + filters_map[f"country_{cc}"] = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.country_code": cc}} + } + } + for r_code, member_ccs in continent_country_codes.items(): + if member_ccs: + filters_map[f"region_{r_code}"] = { + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": member_ccs}} + } + } + + if not filters_map: + return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) + + accumulated_data = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + topic_clauses = [] + topic_filters = {} + for idx, t in enumerate(topics): + if not soft_search and keywords and idx < len(keywords): + clause = { + "nested": { + "path": "keywords", + "query": {"match_phrase": {"keywords.display_name": keywords[idx]}} + } + } + else: + tid = resolved_topic_ids.get(t) + if tid: + clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}}, + {"term": {"primary_topic.id": tid}} + ], + "minimum_should_match": 1 + } + } + else: + clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}}, + {"match_phrase": {"primary_topic.display_name": t}} + ], + "minimum_should_match": 1 + } + } + topic_clauses.append(clause) + topic_filters[t] = clause + + entity_should_clauses = [] + if query_institutions: + entity_should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.id": query_institutions}} + } + }) + if clean_countries: + entity_should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": clean_countries}} + } + }) + all_continent_countries = [] + for member_ccs in continent_country_codes.values(): + all_continent_countries.extend(member_ccs) + if all_continent_countries: + entity_should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": list(set(all_continent_countries))}} + } + }) + + filter_clauses = [ + {"range": {"publication_year": {"gte": start_year, "lte": end_year}}}, + {"bool": {"should": topic_clauses, "minimum_should_match": 1}} + ] + if entity_should_clauses: + filter_clauses.append({"bool": {"should": entity_should_clauses, "minimum_should_match": 1}}) + + query = {"bool": {"filter": filter_clauses}} + aggregations = { + "topics_agg": { + "filters": {"filters": topic_filters}, + "aggs": { + "entities_agg": { + "filters": {"filters": filters_map}, + "aggs": { + "by_year": { + "terms": {"field": "publication_year", "size": len(years_range) * 2} + } + } + } + } + } + } + + try: + res = await elasticsearch.search( + index=f"{str(ESIndex.OPENALEX_WORKS)}*", + body={"query": query, "aggs": aggregations}, + size=0, + cluster="nes" + ) + topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) + for t_name, t_bucket in topics_buckets.items(): + entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) + for entity_key, e_bucket in entities_buckets.items(): + year_buckets = e_bucket.get("by_year", {}).get("buckets", []) + for yr_bucket in year_buckets: + yr = int(yr_bucket.get("key")) + count = int(yr_bucket.get("doc_count", 0)) + if yr in years_range: + accumulated_data[entity_key][t_name][yr] = (count, 1) + except Exception as e: + logger.error("Error executing Elasticsearch publication trend: %s", e) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) + + series_list = [] + for entity_key, topic_dict in accumulated_data.items(): + if entity_key.startswith("inst_"): + entity_id = entity_key[len("inst_"):] + entity_name = resolved_names.get(entity_id, entity_id) + entity_type = "institution" + elif entity_key.startswith("country_"): + entity_id = entity_key[len("country_"):] + entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") + entity_type = "country" + elif entity_key.startswith("region_"): + entity_id = entity_key[len("region_"):] + entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") + entity_type = "region" + else: + continue + + topic_data_map = {} + for topic, year_dict in topic_dict.items(): + yearly_data_items = [] + lookup = normalized_lookup.get((entity_key, topic), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + + for idx, yr in enumerate(years_range): + count, _ = year_dict[yr] + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1 + )) + topic_data_map[topic] = yearly_data_items + + series_list.append(TrendSeries( + entity_id=entity_id, + entity_name=entity_name, + entity_type=entity_type, + country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, + topic_data=topic_data_map + )) + + return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) + + +class AuthorsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + start_year = 2000 + end_year = datetime.datetime.now().year - 1 + years_range = list(range(start_year, end_year + 1)) + + query_authors = authors or [] + if not query_authors: + return TrendResponse(series=[], years=years_range) + + # Resolve author names from openalex-authors index using document ids + resolved_names = {} + try: + res = await elasticsearch.search( + index="openalex-authors", + body={"query": {"ids": {"values": query_authors}}}, + size=len(query_authors), + source=["display_name"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + resolved_names[hit["_id"]] = hit["_source"].get("display_name", hit["_id"]) + except Exception as e: + logger.warning("Failed to resolve author details from ES: %s", e) + + # Fetch topic IDs + resolved_topic_ids = {} + try: + res = await elasticsearch.search( + index="openalex-topics", + query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}}, + size=len(topics) * 2, + source=["id", "display_name"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + for t in topics: + if t.lower() in source["display_name"].lower(): + resolved_topic_ids[t] = source["id"] + except Exception as e: + logger.warning("Failed to resolve topic IDs from ES: %s", e) + + query_authors_full = [ + a if a.startswith("https://openalex.org/") else f"https://openalex.org/{a.upper()}" + for a in query_authors + ] + + filters_map = {} + for auth_id in query_authors: + auth_url = auth_id if auth_id.startswith("https://openalex.org/") else f"https://openalex.org/{auth_id.upper()}" + filters_map[f"author_{auth_id}"] = { + "nested": { + "path": "authorships", + "query": {"term": {"authorships.author.id": auth_url}} + } + } + + accumulated_data = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + topic_clauses = [] + topic_filters = {} + for idx, t in enumerate(topics): + if not soft_search and keywords and idx < len(keywords): + clause = { + "nested": { + "path": "keywords", + "query": {"match_phrase": {"keywords.display_name": keywords[idx]}} + } + } + else: + tid = resolved_topic_ids.get(t) + if tid: + clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}}, + {"term": {"primary_topic.id": tid}} + ], + "minimum_should_match": 1 + } + } + else: + clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}}, + {"match_phrase": {"primary_topic.display_name": t}} + ], + "minimum_should_match": 1 + } + } + topic_clauses.append(clause) + topic_filters[t] = clause + + entity_should_clauses = [{ + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": query_authors_full}} + } + }] + + filter_clauses = [ + {"range": {"publication_year": {"gte": start_year, "lte": end_year}}}, + {"bool": {"should": topic_clauses, "minimum_should_match": 1}}, + {"bool": {"should": entity_should_clauses, "minimum_should_match": 1}} + ] + + query = {"bool": {"filter": filter_clauses}} + aggregations = { + "topics_agg": { + "filters": {"filters": topic_filters}, + "aggs": { + "entities_agg": { + "filters": {"filters": filters_map}, + "aggs": { + "by_year": { + "terms": {"field": "publication_year", "size": len(years_range) * 2} + } + } + } + } + } + } + + try: + res = await elasticsearch.search( + index=f"{str(ESIndex.OPENALEX_WORKS)}*", + body={"query": query, "aggs": aggregations}, + size=0, + cluster="nes" + ) + topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) + for t_name, t_bucket in topics_buckets.items(): + entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) + for entity_key, e_bucket in entities_buckets.items(): + year_buckets = e_bucket.get("by_year", {}).get("buckets", []) + for yr_bucket in year_buckets: + yr = int(yr_bucket.get("key")) + count = int(yr_bucket.get("doc_count", 0)) + if yr in years_range: + accumulated_data[entity_key][t_name][yr] = (count, 1) + except Exception as e: + logger.error("Error executing Elasticsearch author trend: %s", e) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) + + series_list = [] + for entity_key, topic_dict in accumulated_data.items(): + entity_id = entity_key[len("author_"):] + entity_name = resolved_names.get(entity_id, entity_id) + + topic_data_map = {} + for topic, year_dict in topic_dict.items(): + yearly_data_items = [] + lookup = normalized_lookup.get((entity_key, topic), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + + for idx, yr in enumerate(years_range): + count, _ = year_dict[yr] + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1 + )) + topic_data_map[topic] = yearly_data_items + + series_list.append(TrendSeries( + entity_id=entity_id, + entity_name=entity_name, + entity_type="institution", + topic_data=topic_data_map + )) + + return TrendResponse(series=series_list, years=years_range) + + +class PatentsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + # Stub for new patent-topic matching index. Returns a simulated matching curve. + start_year = 2000 + end_year = datetime.datetime.now().year - 1 + years_range = list(range(start_year, end_year + 1)) + + primary_inst_name = DEFAULT_INSTITUTION_NAME + entities = [primary_inst_name] + if institutions: + entities.extend(institutions) + + series_list = [] + for entity in entities: + topic_data_map = {} + for topic in topics: + yearly_data_items = [] + # Simple simulated growth with noise + seed = hash(entity + topic) % 100 + np.random.seed(seed) + counts = np.sort(np.random.randint(0, 15, size=len(years_range))) + cum_counts = list(np.cumsum(counts)) + max_cum = cum_counts[-1] if cum_counts[-1] > 0 else 1 + + for idx, yr in enumerate(years_range): + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=int(counts[idx]), + normalized=float(counts[idx] / 15.0), + cumulative=float(cum_counts[idx] / max_cum), + institutions_count=1 + )) + topic_data_map[topic] = yearly_data_items + + series_list.append(TrendSeries( + entity_id=entity, + entity_name=entity.split("/")[-1], + entity_type="institution", + topic_data=topic_data_map + )) + + return TrendResponse(series=series_list, years=years_range) + + +class ProjectsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + # Stub for third-party funding counts. Returns a simulated funding curve. + start_year = 2000 + end_year = datetime.datetime.now().year - 1 + years_range = list(range(start_year, end_year + 1)) + + primary_inst_name = DEFAULT_INSTITUTION_NAME + entities = [primary_inst_name] + if institutions: + entities.extend(institutions) + + series_list = [] + for entity in entities: + topic_data_map = {} + for topic in topics: + yearly_data_items = [] + seed = hash(entity + topic + "proj") % 100 + np.random.seed(seed) + counts = np.sort(np.random.randint(0, 10, size=len(years_range))) + cum_counts = list(np.cumsum(counts)) + max_cum = cum_counts[-1] if cum_counts[-1] > 0 else 1 + + for idx, yr in enumerate(years_range): + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=int(counts[idx]), + normalized=float(counts[idx] / 10.0), + cumulative=float(cum_counts[idx] / max_cum), + institutions_count=1 + )) + topic_data_map[topic] = yearly_data_items + + series_list.append(TrendSeries( + entity_id=entity, + entity_name=entity.split("/")[-1], + entity_type="institution", + topic_data=topic_data_map + )) + + return TrendResponse(series=series_list, years=years_range) + + +class NewsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + start_year = 2000 + end_year = datetime.datetime.now().year - 1 + years_range = list(range(start_year, end_year + 1)) + + search_terms = keywords if keywords else topics + + # Each series will map all topic keys to its data. + accumulated_data = { + f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} + for t in topics + } + + # Query UDE news postprocessed index to get matching news IDs + async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]: + term = search_terms[idx] if idx < len(search_terms) else t_name + try: + res = await elasticsearch.search( + index="aktuell_postproc", + query={"match": {"keywords": term}}, + size=10000, + source=["news_id"], + cluster="inse" + ) + return [ + hit["_source"]["news_id"] + for hit in res.get("hits", {}).get("hits", []) + if hit.get("_source", {}).get("news_id") + ] + except Exception as e: + logger.warning("Failed to search UDE news postproc keywords: %s", e) + return [] + + # Find all matching news IDs concurrently + matching_ids_list = await asyncio.gather(*[ + fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics) + ]) + + async def count_by_year(t_name: str, news_ids: List[str]): + if not news_ids: + return + try: + # Query aktuell index using matching news IDs and aggregate by date_year + res = await elasticsearch.search( + index="aktuell", + body={ + "query": {"bool": {"filter": [ + {"ids": {"values": news_ids}}, + {"range": {"date_year": {"gte": start_year, "lte": end_year}}} + ]}}, + "aggs": { + "by_year": { + "terms": {"field": "date_year", "size": len(years_range) * 2} + } + } + }, + size=0, + cluster="inse" + ) + buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) + for b in buckets: + yr = int(b.get("key")) + count = int(b.get("doc_count", 0)) + if yr in years_range: + entity_key = f"news_topic_{t_name}" + # Set this count for all topic keys in this topic's series + for top in topics: + accumulated_data[entity_key][top] = dict(accumulated_data[entity_key][top]) + accumulated_data[entity_key][top][yr] = (count, 1) + except Exception as e: + logger.warning("Failed to aggregate news years from ES: %s", e) + + # Aggregate news publication years concurrently + await asyncio.gather(*[ + count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list) + ]) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) + + series_list = [] + for t_name in topics: + entity_key = f"news_topic_{t_name}" + topic_data_map = {} + for topic in topics: + yearly_data_items = [] + lookup = normalized_lookup.get((entity_key, topic), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + + for idx, yr in enumerate(years_range): + count, _ = accumulated_data[entity_key][topic][yr] + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1 + )) + topic_data_map[topic] = yearly_data_items + + series_list.append(TrendSeries( + entity_id=entity_key, + entity_name=t_name, + entity_type="institution", + topic_data=topic_data_map + )) + + return TrendResponse(series=series_list, years=years_range) + + +class AllTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + soft_search: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + # Runs Publications, Patents, Projects, and News strategies concurrently + # overlays their curves to display a Topic Lifecycle dashboard for UDE + pub_strat = PublicationsTrendStrategy() + pat_strat = PatentsTrendStrategy() + proj_strat = ProjectsTrendStrategy() + news_strat = NewsTrendStrategy() + + # Query UDE publications data only + pub_task = pub_strat.get_trend(topics, keywords, soft_search, institutions=[DEFAULT_INSTITUTION_ID]) + pat_task = pat_strat.get_trend(topics, keywords, soft_search) + proj_task = proj_strat.get_trend(topics, keywords, soft_search) + news_task = news_strat.get_trend(topics, keywords, soft_search) + + pub_res, pat_res, proj_res, news_res = await asyncio.gather(pub_task, pat_task, proj_task, news_task) + + start_year = 2000 + end_year = datetime.datetime.now().year - 1 + years_range = list(range(start_year, end_year + 1)) + + # Extract UDE publications series + pub_series = next((s for s in pub_res.series if s.entity_id == DEFAULT_INSTITUTION_ID), None) + pat_series = pat_res.series[0] if pat_res.series else None + proj_series = proj_res.series[0] if proj_res.series else None + + # Reconstruct a single news series containing the correct data for each topic + merged_news_topic_data = {} + for topic in topics: + term_key = f"news_topic_{topic}" + matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) + if matching_series and topic in matching_series.topic_data: + merged_news_topic_data[topic] = matching_series.topic_data[topic] + else: + merged_news_topic_data[topic] = [ + TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) + for yr in years_range + ] + + news_series = TrendSeries( + entity_id="news", + entity_name="UDE Campus Aktuell Beiträge", + entity_type="institution", + topic_data=merged_news_topic_data + ) + + # Build composite TrendSeries + composite_series = [] + + # Helper to construct TrendSeries + def add_composite(series_obj: Optional[TrendSeries], c_id: str, c_name: str): + topic_data_map = {} + for topic in topics: + if series_obj and topic in series_obj.topic_data: + topic_data_map[topic] = series_obj.topic_data[topic] + else: + # Fallback empty list + topic_data_map[topic] = [ + TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) + for yr in years_range + ] + composite_series.append(TrendSeries( + entity_id=c_id, + entity_name=c_name, + entity_type="institution", + topic_data=topic_data_map + )) + + add_composite(pub_series, "publications", "Akademische Publikationen (UDE)") + add_composite(pat_series, "patents", "Patentanmeldungen (UDE)") + add_composite(proj_series, "projects", "Drittmittelförderung (UDE)") + add_composite(news_series, "news", "UDE Campus Aktuell Beiträge") + + return TrendResponse(series=composite_series, years=years_range) diff --git a/webapp/src/app/api/api/universityRankings.service.ts b/webapp/src/app/api/api/universityRankings.service.ts index 4ed6111d..0df23ac9 100644 --- a/webapp/src/app/api/api/universityRankings.service.ts +++ b/webapp/src/app/api/api/universityRankings.service.ts @@ -435,6 +435,10 @@ export class UniversityRankingsService extends BaseService { institutions?: Array, countries?: Array, regions?: Array, + keywords?: Array, + softSearch?: boolean, + searchType?: string, + authors?: Array, observe?: 'body', reportProgress?: boolean, options?: { @@ -448,6 +452,10 @@ export class UniversityRankingsService extends BaseService { institutions?: Array, countries?: Array, regions?: Array, + keywords?: Array, + softSearch?: boolean, + searchType?: string, + authors?: Array, observe?: 'response', reportProgress?: boolean, options?: { @@ -461,6 +469,10 @@ export class UniversityRankingsService extends BaseService { institutions?: Array, countries?: Array, regions?: Array, + keywords?: Array, + softSearch?: boolean, + searchType?: string, + authors?: Array, observe?: 'events', reportProgress?: boolean, options?: { @@ -474,6 +486,10 @@ export class UniversityRankingsService extends BaseService { institutions?: Array, countries?: Array, regions?: Array, + keywords?: Array, + softSearch?: boolean, + searchType?: string, + authors?: Array, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -525,6 +541,38 @@ export class UniversityRankingsService extends BaseService { ); }); } + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', + ); + }); + } + if (softSearch !== undefined && softSearch !== null) { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + softSearch, + 'soft_search', + ); + } + if (searchType) { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + searchType, + 'search_type', + ); + } + if (authors) { + authors.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'authors', + ); + }); + } let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index b5b91234..3d917a48 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -38,6 +38,18 @@ export class SearchResultsStateService { () => this._payload()?.manualKeywords ?? [], ); + // Compute parallel keywords and topic names for trend dashboard strategies + readonly keywordsList = computed(() => this.keywords()); + readonly topicsList = computed(() => { + const ext = this.extractedKeywords(); + const man = this.manualKeywords(); + const all = [...ext, ...man]; + return this.keywords().map((kw) => { + const match = all.find((e) => e.llm_keyword?.keyword === kw); + return match?.topic_mapping?.topic?.display_name ?? kw; + }); + }); + setPayload(payload: SearchResultsPayload): void { this._payload.set(payload); } -- 2.56.1 From c2942906dbec0635d32873c985f36e211b09d1a3 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 12:14:00 +0200 Subject: [PATCH 09/20] added unnecessary author ID checking (refactor complete project later to use the same represenation everywhere pls) & changed backend to make additional query --- .../src/main/inse/university_ranking/model.py | 9 +- .../main/inse/university_ranking/service.py | 25 ++++- .../inse/university_ranking/trend_logic.py | 103 ++++++++++++++++++ .../university_ranking/trend_strategies.py | 14 ++- 4 files changed, 145 insertions(+), 6 deletions(-) diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py index fbc403c0..b61c2e66 100644 --- a/service/src/main/inse/university_ranking/model.py +++ b/service/src/main/inse/university_ranking/model.py @@ -69,4 +69,11 @@ class AutocompleteLocationItem(BaseModel): id: str display_name: str code: str - type: Literal['country', 'continent'] \ No newline at end of file + type: Literal['country', 'continent'] + +class TopTopicItem(BaseModel): + name: str + count: int + +class TopTopicsResponse(BaseModel): + items: List[TopTopicItem] \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py index c5c7c9e5..0bd2b823 100644 --- a/service/src/main/inse/university_ranking/service.py +++ b/service/src/main/inse/university_ranking/service.py @@ -10,7 +10,8 @@ from .model import ( TrendResponse, TopInstitutionItem, AutocompleteLocationItem, - TrendSearchType + TrendSearchType, + TopTopicsResponse ) from .trend_strategies import TrendStrategy @@ -109,4 +110,24 @@ async def get_top_institutions( async def get_autocomplete_locations( query: str = Query(..., description="Query text to search for countries/continents") ): - return await trend_logic.autocomplete_locations(query) \ No newline at end of file + return await trend_logic.autocomplete_locations(query) + +@router.get( + "/top-topics", + response_model=TopTopicsResponse, + summary="Returns top 10 research topics for a selected entity." +) +async def get_top_topics( + entity_id: str = Query(..., description="Entity ID"), + entity_type: str = Query(..., description="Entity type: institution, author, country, region"), + start_year: int = Query(2010, description="Start year"), + end_year: int = Query(2025, description="End year"), + search_type: str = Query("publications", description="Search strategy type") +): + return await trend_logic.get_top_topics_for_entity( + entity_id=entity_id, + entity_type=entity_type, + start_year=start_year, + end_year=end_year, + search_type=search_type + ) \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 8e1365d7..e99df5f7 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -654,3 +654,106 @@ async def get_trend_data( return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) +async def get_top_topics_for_entity( + entity_id: str, + entity_type: str, + start_year: int, + end_year: int, + search_type: str +) -> Dict[str, Any]: + from inse.university_ranking.trend_logic import continent_country_codes + + # 1. Normalize ID and prepare filter clause + if entity_type == "institution": + entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}" + filter_clause = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.id": entity_url}} + } + } + elif entity_type == "author": + entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id.upper()}" + filter_clause = { + "nested": { + "path": "authorships", + "query": {"term": {"authorships.author.id": entity_url}} + } + } + elif entity_type == "country": + filter_clause = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.country_code": entity_id.strip().upper()}} + } + } + elif entity_type == "region": + ccs = continent_country_codes.get(entity_id, []) + if not ccs: + ccs = [entity_id.strip().upper()] + filter_clause = { + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": [c.upper() for c in ccs]}} + } + } + else: + return {"items": []} + + query = { + "bool": { + "filter": [ + filter_clause, + {"range": {"publication_year": {"gte": start_year, "lte": end_year}}} + ] + } + } + + aggs = { + "top_topics": { + "terms": { + "field": "primary_topic.id", + "size": 10 + }, + "aggs": { + "top_topic_hits": { + "top_hits": { + "size": 1, + "_source": ["primary_topic.display_name"] + } + } + } + } + } + + try: + res = await elasticsearch.search( + index="openalex-works*", + body={"query": query, "aggs": aggs}, + size=0, + cluster="nes" + ) + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + + items = [] + for b in buckets: + topic_id = b["key"] + doc_count = b["doc_count"] + hits = b["top_topic_hits"]["hits"]["hits"] + topic_name = "Unknown" + if hits: + topic_name = hits[0]["_source"]["primary_topic"]["display_name"] + items.append({"name": topic_name, "count": doc_count}) + + # Calculate "Other" + total_hits = res.get("hits", {}).get("total", {}).get("value", 0) + sum_top_10 = sum(b["count"] for b in items) + other_count = max(0, total_hits - sum_top_10) + if other_count > 0: + items.append({"name": "Andere Themen", "count": other_count}) + + return {"items": items} + except Exception as e: + logger.error("Failed to query top topics for entity in ES: %s", e) + return {"items": []} + diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index f7d65825..e4cd6ebf 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -412,17 +412,25 @@ class AuthorsTrendStrategy(TrendStrategy): return TrendResponse(series=[], years=years_range) # Resolve author names from openalex-authors index using document ids + query_authors_clean = [ + a.split("/")[-1].upper() if a.startswith("http") else a.upper() + for a in query_authors + ] resolved_names = {} try: res = await elasticsearch.search( index="openalex-authors", - body={"query": {"ids": {"values": query_authors}}}, - size=len(query_authors), + body={"query": {"ids": {"values": query_authors_clean}}}, + size=len(query_authors_clean), source=["display_name"], cluster="nes" ) for hit in res.get("hits", {}).get("hits", []): - resolved_names[hit["_id"]] = hit["_source"].get("display_name", hit["_id"]) + short_id = hit["_id"] + full_id = f"https://openalex.org/{short_id}" + display_name = hit["_source"].get("display_name", short_id) + resolved_names[short_id] = display_name + resolved_names[full_id] = display_name except Exception as e: logger.warning("Failed to resolve author details from ES: %s", e) -- 2.56.1 From 0fd028c6cb7eb072015f8e56bfe7f045ed69adc0 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 12:14:42 +0200 Subject: [PATCH 10/20] added pie chart for authors and institutions --- .../uni-pie-chart.component.html | 3 + .../uni-pie-chart.component.scss | 17 ++ .../uni-pie-chart/uni-pie-chart.component.ts | 155 ++++++++++++++++++ .../uni-trend-parent.component.html | 29 +++- .../uni-trend-parent.component.ts | 59 ++++++- .../author-selector.component.html | 11 +- .../author-selector.component.ts | 6 + .../institution-selector.component.html | 31 +++- .../institution-selector.component.ts | 6 + .../location-selector.component.html | 22 ++- .../location-selector.component.ts | 6 + 11 files changed, 328 insertions(+), 17 deletions(-) create mode 100644 webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.html create mode 100644 webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.scss create mode 100644 webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts diff --git a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.html b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.html new file mode 100644 index 00000000..86b3f2a6 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.html @@ -0,0 +1,3 @@ +
+
+
diff --git a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.scss b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.scss new file mode 100644 index 00000000..20a76242 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.scss @@ -0,0 +1,17 @@ +.pie-chart-holder { + display: flex; + flex-direction: column; + background: white; + border: 1px solid #d7e4ff; + border-radius: 16px; + padding: 16px; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + box-sizing: border-box; + width: 100%; + height: 300px; +} + +.pie-chart-container { + width: 100%; + height: 100%; +} diff --git a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts new file mode 100644 index 00000000..f8106798 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts @@ -0,0 +1,155 @@ +import { + Component, + input, + computed, + ChangeDetectionStrategy, +} from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; +import { TrendResponse } from '../../../api'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; + +@Component({ + selector: 'app-uni-pie-chart', + templateUrl: './uni-pie-chart.component.html', + styleUrl: './uni-pie-chart.component.scss', + imports: [NgxEchartsDirective, CommonModule], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class UniPieChartComponent { + readonly data = input(null); + readonly entityId = input(null); + readonly entityName = input(null); + readonly startYear = input(2010); + readonly endYear = input(2025); + + getTopicColor(topic: string): string { + return topicHierarchyColor({ name: topic }); + } + + readonly chartOptions = computed(() => { + const trendData = this.data(); + const entityIdVal = this.entityId(); + if (!trendData || !entityIdVal) { + return {}; + } + + // Find the series for the selected entity (resilient matching) + const series = trendData.series.find((s) => { + const sId = s.entity_id; + const targetId = entityIdVal; + return ( + sId === targetId || + sId.toUpperCase() === targetId.toUpperCase() || + sId.split('/').pop()?.toUpperCase() === targetId.toUpperCase() || + targetId.split('/').pop()?.toUpperCase() === sId.toUpperCase() + ); + }); + + if (!series || !series.topic_data) { + return { + title: { + text: 'Keine Daten vorhanden', + left: 'center', + top: 'center', + textStyle: { color: '#6b7280', fontSize: 13 }, + }, + }; + } + + const startYr = this.startYear(); + const endYr = this.endYear(); + + const pieDataList: any[] = []; + Object.entries(series.topic_data).forEach(([topicName, yearlyItems]) => { + const filtered = (yearlyItems || []).filter( + (y) => y.year >= startYr && y.year <= endYr, + ); + const totalRaw = filtered.reduce((sum, item) => sum + item.raw, 0); + + if (totalRaw > 0) { + pieDataList.push({ + value: totalRaw, + name: topicName, + itemStyle: { + color: this.getTopicColor(topicName), + }, + }); + } + }); + + if (pieDataList.length === 0) { + return { + title: { + text: `Keine Daten im Zeitraum ${startYr} - ${endYr}`, + left: 'center', + top: 'center', + textStyle: { color: '#6b7280', fontSize: 13 }, + }, + }; + } + + return { + title: { + text: `Verteilung: ${this.entityName()}`, + subtext: `Zeitraum: ${startYr} - ${endYr}`, + left: 'center', + top: 10, + textStyle: { + fontSize: 13, + fontWeight: 600, + color: '#1f2937', + }, + subtextStyle: { + fontSize: 10, + color: '#6b7280', + }, + }, + tooltip: { + trigger: 'item', + formatter: '{b}: {c} ({d}%)', + }, + legend: { + show: false, // Hide default legend to keep layout clean and readable in small containers + }, + series: [ + { + name: 'Themenverteilung', + type: 'pie', + radius: ['45%', '75%'], + avoidLabelOverlap: true, + top: 40, + bottom: 10, + itemStyle: { + borderRadius: 6, + borderColor: '#fff', + borderWidth: 2, + }, + label: { + show: true, + position: 'outside', + fontSize: 9, + formatter: '{b}: {d}%', + color: '#374151', + }, + labelLine: { + show: true, + length: 8, + length2: 5, + smooth: true, + }, + emphasis: { + label: { + show: true, + fontSize: 10, + fontWeight: 'bold', + formatter: '{b}\n{c} ({d}%)', + }, + }, + data: pieDataList, + }, + ], + }; + }); +} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 629a11c9..bb8d5e1c 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -55,10 +55,12 @@ [locationSearchResults]="locationSearchResults()" [getEntityColor]="boundGetEntityColor" [isVisible]="boundIsVisible" + [selectedPieEntityId]="selectedPieEntity()?.id ?? null" (addLocation)="addLocation($event)" (removeLocation)="removeLocation($event.id, $event.type)" (searchChange)="onLocationSearchChange($event)" - (toggleVisibility)="toggleVisibility($event)"> + (toggleVisibility)="toggleVisibility($event)" + (selectPie)="onSelectPieEntity($event)"> } @@ -130,6 +132,23 @@ [endYear]="endYear()"> + + @if ( + selectedPieEntity() && + selectedSearchType() !== 'news' && + selectedSearchType() !== 'all' + ) { +
+ + +
+ } + @if (activeConfig().showInstitutionSelector) { + (toggleVisibility)="toggleVisibility($event)" + (selectPie)="onSelectPieEntity($event)"> } @@ -161,10 +182,12 @@ [searchResults]="authorSearchResults()" [getEntityColor]="boundGetEntityColor" [isVisible]="boundIsVisible" + [selectedPieEntityId]="selectedPieEntity()?.id ?? null" (addAuthor)="addAuthor($event.id, $event.name)" (removeAuthor)="removeAuthor($event)" (searchChange)="onAuthorSearchChange($event)" - (toggleVisibility)="toggleVisibility($event)"> + (toggleVisibility)="toggleVisibility($event)" + (selectPie)="onSelectPieEntity($event)"> } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index e145ecd6..45bbc8bf 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -22,6 +22,7 @@ import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component'; +import { UniPieChartComponent } from '../uni-pie-chart/uni-pie-chart.component'; import { TrendResponse, TrendSeries, @@ -108,6 +109,7 @@ export const TREND_CONFIGS: Record = { CommonModule, FormsModule, UniTrendChartComponent, + UniPieChartComponent, MatCheckboxModule, MatButtonModule, MatIconModule, @@ -159,6 +161,9 @@ export class UniTrendParentComponent implements OnInit { 'normalized', ); readonly activeChartTopic = signal(''); + readonly selectedPieEntity = signal<{ id: string; name: string } | null>( + null, + ); // Config mapper for active strategy UI representation readonly activeConfig = computed( @@ -255,6 +260,10 @@ export class UniTrendParentComponent implements OnInit { return entityColors[idx % entityColors.length]; } + onSelectPieEntity(event: { id: string; name: string }) { + this.selectedPieEntity.set(event); + } + readonly boundGetEntityColor = (id: string) => this.getEntityColor(id); readonly boundIsVisible = (id: string) => this.isVisible(id); @@ -592,6 +601,43 @@ export class UniTrendParentComponent implements OnInit { this.activeChartTopic.set(params['active_chart_topic']); } }); + + // Effect: automatically select/sync selectedPieEntity with active trendResponse series list + effect(() => { + const data = this.trendResponse(); + const currentPie = untracked(() => this.selectedPieEntity()); + + if (!data || data.series.length === 0) { + this.selectedPieEntity.set(null); + return; + } + + if (currentPie) { + const stillExists = data.series.some((s) => { + const sId = s.entity_id; + const targetId = currentPie.id; + return ( + sId === targetId || + sId.toUpperCase() === targetId.toUpperCase() || + sId.split('/').pop()?.toUpperCase() === targetId.toUpperCase() || + targetId.split('/').pop()?.toUpperCase() === sId.toUpperCase() + ); + }); + if (stillExists) { + return; + } + } + + const firstSeries = data.series[0]; + if (firstSeries) { + this.selectedPieEntity.set({ + id: firstSeries.entity_id, + name: firstSeries.entity_name, + }); + } else { + this.selectedPieEntity.set(null); + } + }); } ngOnInit() { @@ -997,9 +1043,13 @@ export class UniTrendParentComponent implements OnInit { const current = this.comparisonAuthors(); const updated = [...current]; (res.results || []).forEach((author: any) => { - if (author.id && !updated.some((a) => a.id === author.id)) { + const shortId = + author.id && author.id.includes('/') + ? author.id.split('/').pop() || author.id + : author.id; + if (shortId && !updated.some((a) => a.id === shortId)) { updated.push({ - id: author.id, + id: shortId, name: author.display_name || 'Unbekannt', }); } @@ -1018,9 +1068,10 @@ export class UniTrendParentComponent implements OnInit { } addAuthor(id: string, name: string) { + const shortId = id.includes('/') ? id.split('/').pop() || id : id; const current = this.comparisonAuthors(); - if (!current.some((a) => a.id === id)) { - this.comparisonAuthors.set([...current, { id, name }]); + if (!current.some((a) => a.id === shortId)) { + this.comparisonAuthors.set([...current, { id: shortId, name }]); } } diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.html b/webapp/src/app/shared/ui/author-selector/author-selector.component.html index 349f3c91..cd347469 100644 --- a/webapp/src/app/shared/ui/author-selector/author-selector.component.html +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.html @@ -45,8 +45,15 @@ ' 8%, #ffffff)' " [style.color]="getEntityColor()(auth.id)"> - - person {{ auth.name }} + + {{ + selectedPieEntityId() === auth.id ? 'pie_chart' : 'person' + }} + {{ auth.name }}
- + @if ( selectedPieEntity() && selectedSearchType() !== 'news' && selectedSearchType() !== 'all' ) { -
+
+ [endYear]="endYear()" + [getTopicColor]="boundGetTopicColor"> + + +
} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 6146c6cc..03d0fa32 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -223,3 +223,15 @@ } } } + +.pie-charts-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1.5rem; + width: 100%; + box-sizing: border-box; + + @media (max-width: 768px) { + grid-template-columns: 1fr; + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 45bbc8bf..b23e7f8c 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -161,9 +161,11 @@ export class UniTrendParentComponent implements OnInit { 'normalized', ); readonly activeChartTopic = signal(''); - readonly selectedPieEntity = signal<{ id: string; name: string } | null>( - null, - ); + readonly selectedPieEntity = signal<{ + id: string; + name: string; + type: 'institution' | 'author' | 'country' | 'region'; + } | null>(null); // Config mapper for active strategy UI representation readonly activeConfig = computed( @@ -184,11 +186,32 @@ export class UniTrendParentComponent implements OnInit { readonly topSuggestions = signal([]); readonly recommendedAuthors = signal([]); readonly isSuggestionsLoading = signal(false); + readonly topTopicsData = signal<{ value: number; name: string }[]>([]); + readonly isTopTopicsLoading = signal(false); + readonly topTopicsError = signal(false); getTopicColor(topic: string): string { + const ext = this.state?.extractedKeywords() ?? []; + const man = this.state?.manualKeywords() ?? []; + const all = [...ext, ...man]; + const match = all.find( + (e) => e.topic_mapping?.topic?.display_name === topic, + ); + if (match && match.topic_mapping?.topic) { + return topicHierarchyColor({ + name: match.topic_mapping.topic.display_name, + field_name: match.topic_mapping.topic.field?.display_name, + domain_name: match.topic_mapping.topic.domain?.display_name, + field_id: match.topic_mapping.topic.field?.id, + domain_id: match.topic_mapping.topic.domain?.id, + id: match.topic_mapping.topic.id, + }); + } return topicHierarchyColor({ name: topic }); } + readonly boundGetTopicColor = this.getTopicColor.bind(this); + // Autocomplete UI state readonly searchQuery = signal(''); readonly searchResults = signal([]); @@ -260,7 +283,11 @@ export class UniTrendParentComponent implements OnInit { return entityColors[idx % entityColors.length]; } - onSelectPieEntity(event: { id: string; name: string }) { + onSelectPieEntity(event: { + id: string; + name: string; + type: 'institution' | 'author' | 'country' | 'region'; + }) { this.selectedPieEntity.set(event); } @@ -633,11 +660,53 @@ export class UniTrendParentComponent implements OnInit { this.selectedPieEntity.set({ id: firstSeries.entity_id, name: firstSeries.entity_name, + type: firstSeries.entity_type as any, }); } else { this.selectedPieEntity.set(null); } }); + + // Effect: load top 10 overall topics for selected pie entity + effect(() => { + const entity = this.selectedPieEntity(); + const start = this.startYear(); + const end = this.endYear(); + const strategy = this.selectedSearchType(); + + if (!entity || strategy === 'news' || strategy === 'all') { + this.topTopicsData.set([]); + return; + } + + this.isTopTopicsLoading.set(true); + this.topTopicsError.set(false); + + this.apiService + .getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + entity.id, + entity.type, + start, + end, + strategy, + ) + .subscribe({ + next: (res) => { + const mapped = (res.items || []).map((item) => ({ + value: item.count, + name: item.name, + })); + this.topTopicsData.set(mapped); + this.isTopTopicsLoading.set(false); + }, + error: (err) => { + console.error('Failed to load top topics:', err); + this.topTopicsError.set(true); + this.isTopTopicsLoading.set(false); + this.topTopicsData.set([]); + }, + }); + }); } ngOnInit() { @@ -847,13 +916,13 @@ export class UniTrendParentComponent implements OnInit { this.apiService .getTrendApiInseServiceUniversityRankingsTrendGet( topics, + kws, + softSearch, this.comparisonInstitutions().map((i: CompareItem) => i.id), this.comparisonCountries().map((c: CompareItem) => c.id), this.comparisonRegions().map((r: CompareItem) => r.id), - kws, - softSearch, - this.selectedSearchType(), this.comparisonAuthors().map((a: CompareItem) => a.id), + this.selectedSearchType(), ) .subscribe({ next: (response: TrendResponse) => { diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.ts b/webapp/src/app/shared/ui/author-selector/author-selector.component.ts index 11cffc74..6d4b452d 100644 --- a/webapp/src/app/shared/ui/author-selector/author-selector.component.ts +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.ts @@ -29,10 +29,10 @@ export class AuthorSelectorComponent { readonly removeAuthor = output(); readonly searchChange = output(); readonly toggleVisibility = output(); - readonly selectPie = output<{ id: string; name: string }>(); + readonly selectPie = output<{ id: string; name: string; type: 'author' }>(); onSelectPie(id: string, name: string): void { - this.selectPie.emit({ id, name }); + this.selectPie.emit({ id, name, type: 'author' }); } onSearchInput(event: Event): void { diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts index cb1f2311..40be9329 100644 --- a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts @@ -31,10 +31,14 @@ export class InstitutionSelectorComponent { readonly removeInstitution = output(); readonly searchChange = output(); readonly toggleVisibility = output(); - readonly selectPie = output<{ id: string; name: string }>(); + readonly selectPie = output<{ + id: string; + name: string; + type: 'institution'; + }>(); onSelectPie(id: string, name: string): void { - this.selectPie.emit({ id, name }); + this.selectPie.emit({ id, name, type: 'institution' }); } onSearchInput(event: Event): void { diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.html b/webapp/src/app/shared/ui/location-selector/location-selector.component.html index 7b3de352..618ef2da 100644 --- a/webapp/src/app/shared/ui/location-selector/location-selector.component.html +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.html @@ -15,7 +15,7 @@ {{ selectedPieEntityId() === c.id ? 'pie_chart' : 'flag' @@ -61,7 +61,7 @@ {{ selectedPieEntityId() === r.id ? 'pie_chart' : 'public' diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.ts b/webapp/src/app/shared/ui/location-selector/location-selector.component.ts index d887f59c..0a6f9644 100644 --- a/webapp/src/app/shared/ui/location-selector/location-selector.component.ts +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.ts @@ -31,10 +31,14 @@ export class LocationSelectorComponent { }>(); readonly searchChange = output(); readonly toggleVisibility = output(); - readonly selectPie = output<{ id: string; name: string }>(); + readonly selectPie = output<{ + id: string; + name: string; + type: 'country' | 'region'; + }>(); - onSelectPie(id: string, name: string): void { - this.selectPie.emit({ id, name }); + onSelectPie(id: string, name: string, type: 'country' | 'region'): void { + this.selectPie.emit({ id, name, type }); } onSearchInput(event: Event): void { -- 2.56.1 From df56af976ccb501bcb7bba1f85b548203d3b1760 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 13:04:07 +0200 Subject: [PATCH 13/20] regenerated services --- webapp/src/app/api/.openapi-generator/FILES | 4 + webapp/src/app/api/api/auth.service.ts | 4 +- .../app/api/api/universityRankings.service.ts | 231 +++++++++++++++--- .../app/api/model/bodyRequestPasswordReset.ts | 2 +- webapp/src/app/api/model/matchedTopic.ts | 18 ++ webapp/src/app/api/model/models.ts | 4 + webapp/src/app/api/model/newsArticleDetail.ts | 3 +- webapp/src/app/api/model/topTopicItem.ts | 14 ++ webapp/src/app/api/model/topTopicsResponse.ts | 14 ++ webapp/src/app/api/model/trendSearchType.ts | 20 ++ webapp/src/app/api/model/trendSeries.ts | 1 + 11 files changed, 276 insertions(+), 39 deletions(-) create mode 100644 webapp/src/app/api/model/matchedTopic.ts create mode 100644 webapp/src/app/api/model/topTopicItem.ts create mode 100644 webapp/src/app/api/model/topTopicsResponse.ts create mode 100644 webapp/src/app/api/model/trendSearchType.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 9928d2c3..f32e14a8 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -142,6 +142,7 @@ model/loginResponse.ts model/longitude.ts model/matchedAuthor.ts model/matchedOfficer.ts +model/matchedTopic.ts model/mentionedPerson.ts model/meta.ts model/model2YrMeanCitedness.ts @@ -169,6 +170,8 @@ model/score.ts model/sortDirection.ts model/tokenType.ts model/topInstitutionItem.ts +model/topTopicItem.ts +model/topTopicsResponse.ts model/topic.ts model/topicCount.ts model/topicDomain.ts @@ -181,6 +184,7 @@ model/topicsByTime.ts model/topicsByYear.ts model/topicsListResponse.ts model/trendResponse.ts +model/trendSearchType.ts model/trendSeries.ts model/universityRanking.ts model/universityTopicData.ts diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index f3d264dc..e504fdc9 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -1514,6 +1514,7 @@ export class AuthService extends BaseService { const localVarTransferCache: boolean = options?.transferCache ?? true; + // to determine the Content-Type header const consumes: string[] = ['application/json']; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); @@ -1555,7 +1556,7 @@ export class AuthService extends BaseService { /** * Reset Password - * Reset the user's password using a one-time password reset token. + * Reset the user\'s password using a one-time password reset token. * @endpoint post /api/auth/v2/reset-password * @param bodyResetPassword * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. @@ -1624,6 +1625,7 @@ export class AuthService extends BaseService { const localVarTransferCache: boolean = options?.transferCache ?? true; + // to determine the Content-Type header const consumes: string[] = ['application/json']; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); diff --git a/webapp/src/app/api/api/universityRankings.service.ts b/webapp/src/app/api/api/universityRankings.service.ts index 0df23ac9..dffe09c7 100644 --- a/webapp/src/app/api/api/universityRankings.service.ts +++ b/webapp/src/app/api/api/universityRankings.service.ts @@ -31,7 +31,11 @@ import { RankingResponse } from '../model/rankingResponse'; // @ts-ignore import { TopInstitutionItem } from '../model/topInstitutionItem'; // @ts-ignore +import { TopTopicsResponse } from '../model/topTopicsResponse'; +// @ts-ignore import { TrendResponse } from '../model/trendResponse'; +// @ts-ignore +import { TrendSearchType } from '../model/trendSearchType'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -421,24 +425,183 @@ export class UniversityRankingsService extends BaseService { } /** - * Returns timeseries publication data for compared institutions, countries and regions. + * Returns top 10 research topics for a selected entity. + * @endpoint get /api/inse-service/university-rankings/top-topics + * @param entityId Entity ID + * @param entityType Entity type: institution, author, country, region + * @param startYear Start year + * @param endYear End year + * @param searchType Search strategy type + * @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 getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + entityId: string, + entityType: string, + startYear?: number, + endYear?: number, + searchType?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + entityId: string, + entityType: string, + startYear?: number, + endYear?: number, + searchType?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + entityId: string, + entityType: string, + startYear?: number, + endYear?: number, + searchType?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet( + entityId: string, + entityType: string, + startYear?: number, + endYear?: number, + searchType?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (entityId === null || entityId === undefined) { + throw new Error( + 'Required parameter entityId was null or undefined when calling getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet.', + ); + } + if (entityType === null || entityType === undefined) { + throw new Error( + 'Required parameter entityType was null or undefined when calling getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + entityId, + 'entity_id', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + entityType, + 'entity_type', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + startYear, + 'start_year', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + endYear, + 'end_year', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + searchType, + 'search_type', + ); + + 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/university-rankings/top-topics`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns timeseries publication data for compared institutions, countries, and regions. * @endpoint get /api/inse-service/university-rankings/trend * @param topics List of topics to analyze + * @param keywords List of raw keywords corresponding to topics + * @param softSearch True if using mapped topics, False if using raw keywords * @param institutions List of OpenAlex Institution IDs * @param countries List of country codes * @param regions List of region identifiers + * @param authors List of OpenAlex Author IDs + * @param searchType * @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 getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, + keywords?: Array, + softSearch?: boolean, institutions?: Array, countries?: Array, regions?: Array, - keywords?: Array, - softSearch?: boolean, - searchType?: string, authors?: Array, + searchType?: TrendSearchType, observe?: 'body', reportProgress?: boolean, options?: { @@ -449,13 +612,13 @@ export class UniversityRankingsService extends BaseService { ): Observable; public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, + keywords?: Array, + softSearch?: boolean, institutions?: Array, countries?: Array, regions?: Array, - keywords?: Array, - softSearch?: boolean, - searchType?: string, authors?: Array, + searchType?: TrendSearchType, observe?: 'response', reportProgress?: boolean, options?: { @@ -466,13 +629,13 @@ export class UniversityRankingsService extends BaseService { ): Observable>; public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, + keywords?: Array, + softSearch?: boolean, institutions?: Array, countries?: Array, regions?: Array, - keywords?: Array, - softSearch?: boolean, - searchType?: string, authors?: Array, + searchType?: TrendSearchType, observe?: 'events', reportProgress?: boolean, options?: { @@ -483,13 +646,13 @@ export class UniversityRankingsService extends BaseService { ): Observable>; public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, + keywords?: Array, + softSearch?: boolean, institutions?: Array, countries?: Array, regions?: Array, - keywords?: Array, - softSearch?: boolean, - searchType?: string, authors?: Array, + searchType?: TrendSearchType, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -514,6 +677,20 @@ export class UniversityRankingsService extends BaseService { ); }); } + if (keywords) { + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + softSearch, + 'soft_search', + ); if (institutions) { institutions.forEach((element) => { localVarQueryParameters = this.addToHttpParams( @@ -541,29 +718,6 @@ export class UniversityRankingsService extends BaseService { ); }); } - if (keywords) { - keywords.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'keywords', - ); - }); - } - if (softSearch !== undefined && softSearch !== null) { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - softSearch, - 'soft_search', - ); - } - if (searchType) { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'search_type', - ); - } if (authors) { authors.forEach((element) => { localVarQueryParameters = this.addToHttpParams( @@ -573,6 +727,11 @@ export class UniversityRankingsService extends BaseService { ); }); } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + searchType, + 'search_type', + ); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/model/bodyRequestPasswordReset.ts b/webapp/src/app/api/model/bodyRequestPasswordReset.ts index c3f6d5d4..ec3222b5 100644 --- a/webapp/src/app/api/model/bodyRequestPasswordReset.ts +++ b/webapp/src/app/api/model/bodyRequestPasswordReset.ts @@ -10,7 +10,7 @@ export interface BodyRequestPasswordReset { /** - * User's email address + * User\'s email address */ email: string; } diff --git a/webapp/src/app/api/model/matchedTopic.ts b/webapp/src/app/api/model/matchedTopic.ts new file mode 100644 index 00000000..52de9018 --- /dev/null +++ b/webapp/src/app/api/model/matchedTopic.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 MatchedTopic { + id?: string | null; + display_name?: string | null; + subfield_name?: string | null; + field_name?: string | null; + domain_name?: string | null; + source_keyword?: string | null; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index d932a058..fbe8649a 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -117,6 +117,7 @@ export * from './loginResponse'; export * from './longitude'; export * from './matchedAuthor'; export * from './matchedOfficer'; +export * from './matchedTopic'; export * from './mentionedPerson'; export * from './meta'; export * from './model2YrMeanCitedness'; @@ -143,6 +144,8 @@ export * from './score'; export * from './sortDirection'; export * from './tokenType'; export * from './topInstitutionItem'; +export * from './topTopicItem'; +export * from './topTopicsResponse'; export * from './topic'; export * from './topicCount'; export * from './topicDomain'; @@ -155,6 +158,7 @@ export * from './topicsByTime'; export * from './topicsByYear'; export * from './topicsListResponse'; export * from './trendResponse'; +export * from './trendSearchType'; export * from './trendSeries'; export * from './universityRanking'; export * from './universityTopicData'; diff --git a/webapp/src/app/api/model/newsArticleDetail.ts b/webapp/src/app/api/model/newsArticleDetail.ts index ac51097c..09962000 100644 --- a/webapp/src/app/api/model/newsArticleDetail.ts +++ b/webapp/src/app/api/model/newsArticleDetail.ts @@ -7,6 +7,7 @@ * https://openapi-generator.tech * Do not edit the class manually. */ +import { MatchedTopic } from './matchedTopic'; import { MentionedPerson } from './mentionedPerson'; export interface NewsArticleDetail { @@ -20,6 +21,6 @@ export interface NewsArticleDetail { related?: boolean | null; full_content?: string | null; authors?: Array; - topics?: Array; keywords?: Array; + topics?: Array; } diff --git a/webapp/src/app/api/model/topTopicItem.ts b/webapp/src/app/api/model/topTopicItem.ts new file mode 100644 index 00000000..e6a151d4 --- /dev/null +++ b/webapp/src/app/api/model/topTopicItem.ts @@ -0,0 +1,14 @@ +/** + * 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 TopTopicItem { + name: string; + count: number; +} diff --git a/webapp/src/app/api/model/topTopicsResponse.ts b/webapp/src/app/api/model/topTopicsResponse.ts new file mode 100644 index 00000000..4bac3de8 --- /dev/null +++ b/webapp/src/app/api/model/topTopicsResponse.ts @@ -0,0 +1,14 @@ +/** + * 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 { TopTopicItem } from './topTopicItem'; + +export interface TopTopicsResponse { + items: Array; +} diff --git a/webapp/src/app/api/model/trendSearchType.ts b/webapp/src/app/api/model/trendSearchType.ts new file mode 100644 index 00000000..bde11a52 --- /dev/null +++ b/webapp/src/app/api/model/trendSearchType.ts @@ -0,0 +1,20 @@ +/** + * 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 const TrendSearchType = { + Publications: 'publications', + Authors: 'authors', + Patents: 'patents', + Projects: 'projects', + News: 'news', + All: 'all', +} as const; +export type TrendSearchType = + (typeof TrendSearchType)[keyof typeof TrendSearchType]; diff --git a/webapp/src/app/api/model/trendSeries.ts b/webapp/src/app/api/model/trendSeries.ts index 1dc054be..b8ce939f 100644 --- a/webapp/src/app/api/model/trendSeries.ts +++ b/webapp/src/app/api/model/trendSeries.ts @@ -21,6 +21,7 @@ export namespace TrendSeries { Institution: 'institution', Country: 'country', Region: 'region', + Author: 'author', } as const; export type EntityTypeEnum = (typeof EntityTypeEnum)[keyof typeof EntityTypeEnum]; -- 2.56.1 From 605ffc1fffa3379800ace3e0703bb73adbf1e4df Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 15:59:58 +0200 Subject: [PATCH 14/20] removed Pi chart style from global style sheet to actual buttons --- .../author-selector.component.scss | 26 +++++++++++++++++++ .../institution-selector.component.scss | 26 +++++++++++++++++++ .../location-selector.component.scss | 26 +++++++++++++++++++ webapp/src/styles.scss | 26 ------------------- 4 files changed, 78 insertions(+), 26 deletions(-) diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.scss b/webapp/src/app/shared/ui/author-selector/author-selector.component.scss index 83d3db84..3b24a598 100644 --- a/webapp/src/app/shared/ui/author-selector/author-selector.component.scss +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.scss @@ -318,3 +318,29 @@ transform: rotate(360deg); } } + +.clickable-pie-target { + cursor: pointer; + display: inline-flex !important; + align-items: center; + gap: 6px; + transition: all 0.2s ease; + user-select: none; + border-radius: 4px; + padding: 2px 6px; + + &:hover { + background: rgba(0, 0, 0, 0.04); + opacity: 0.85; + } +} + +.pie-icon-indicator { + transition: transform 0.3s ease; +} + +.active-pie { + font-weight: 700 !important; + background: rgba(59, 130, 246, 0.08) !important; + border-radius: 4px; +} diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss index a9fe0b99..733745d7 100644 --- a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.scss @@ -338,3 +338,29 @@ transform: rotate(360deg); } } + +.clickable-pie-target { + cursor: pointer; + display: inline-flex !important; + align-items: center; + gap: 6px; + transition: all 0.2s ease; + user-select: none; + border-radius: 4px; + padding: 2px 6px; + + &:hover { + background: rgba(0, 0, 0, 0.04); + opacity: 0.85; + } +} + +.pie-icon-indicator { + transition: transform 0.3s ease; +} + +.active-pie { + font-weight: 700 !important; + background: rgba(59, 130, 246, 0.08) !important; + border-radius: 4px; +} diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss index acf0b1a7..08b79102 100644 --- a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss +++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss @@ -154,3 +154,29 @@ } } } + +.clickable-pie-target { + cursor: pointer; + display: inline-flex !important; + align-items: center; + gap: 6px; + transition: all 0.2s ease; + user-select: none; + border-radius: 4px; + padding: 2px 6px; + + &:hover { + background: rgba(0, 0, 0, 0.04); + opacity: 0.85; + } +} + +.pie-icon-indicator { + transition: transform 0.3s ease; +} + +.active-pie { + font-weight: 700 !important; + background: rgba(59, 130, 246, 0.08) !important; + border-radius: 4px; +} diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index 7625ab33..71643900 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -277,29 +277,3 @@ h3 { color: var(--sg-text-muted); font-size: 13px; } - -.clickable-pie-target { - cursor: pointer; - display: inline-flex !important; - align-items: center; - gap: 6px; - transition: all 0.2s ease; - user-select: none; - border-radius: 4px; - padding: 2px 6px; - - &:hover { - background: rgba(0, 0, 0, 0.04); - opacity: 0.85; - } -} - -.pie-icon-indicator { - transition: transform 0.3s ease; -} - -.active-pie { - font-weight: 700 !important; - background: rgba(59, 130, 246, 0.08) !important; - border-radius: 4px; -} -- 2.56.1 From 09150193155592c855087b0e49a0b4d006b8c413 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 16:01:57 +0200 Subject: [PATCH 15/20] changed search to find keywords in abstract, title, keywords. Refactored to remove the visualization button and implemented own route and tab inside Suche --- .../university_ranking/trend_strategies.py | 24 ++++++-- webapp/src/app/app.routes.ts | 2 + .../keywords-search.component.html | 18 ------ .../keywords-search.component.ts | 11 ---- .../search-results-state.service.ts | 59 +++++++++++++++++-- .../search-results.component.html | 7 ++- .../search-results.component.ts | 50 +--------------- .../uni-trend-parent.component.ts | 11 +++- 8 files changed, 90 insertions(+), 92 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 0ed2280b..720b275c 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -243,10 +243,16 @@ class PublicationsTrendStrategy(TrendStrategy): topic_filters = {} for idx, t in enumerate(topics): if not soft_search and keywords and idx < len(keywords): + kw_val = keywords[idx] clause = { - "nested": { - "path": "keywords", - "query": {"match_phrase": {"keywords.display_name": keywords[idx]}} + "bool": { + "should": [ + {"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw_val}}}}, + {"match_phrase": {"primary_topic.display_name": kw_val}}, + {"match_phrase": {"display_name": kw_val}}, + {"match_phrase": {"abstract": kw_val}} + ], + "minimum_should_match": 1 } } else: @@ -476,10 +482,16 @@ class AuthorsTrendStrategy(TrendStrategy): topic_filters = {} for idx, t in enumerate(topics): if not soft_search and keywords and idx < len(keywords): + kw_val = keywords[idx] clause = { - "nested": { - "path": "keywords", - "query": {"match_phrase": {"keywords.display_name": keywords[idx]}} + "bool": { + "should": [ + {"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw_val}}}}, + {"match_phrase": {"primary_topic.display_name": kw_val}}, + {"match_phrase": {"display_name": kw_val}}, + {"match_phrase": {"abstract": kw_val}} + ], + "minimum_should_match": 1 } } else: diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index e651d81e..e9fa000d 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -29,6 +29,7 @@ import { KeywordsToProjectsResultsComponent } from './modules/keywords-search/se import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/search-results/patents-results/patents-results.component'; import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component'; import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component'; +import { UniTrendParentComponent } from './modules/university-ranking/uni-trend-parent/uni-trend-parent.component'; export const routes: Routes = [ { path: '', @@ -120,6 +121,7 @@ export const routes: Routes = [ { path: 'patents', component: KeywordsToPatentsResultsComponent }, { path: 'works', component: KeywordsToWorksResultsComponent }, { path: 'news', component: KeywordsToNewsResultsComponent }, + { path: 'trends', component: UniTrendParentComponent }, ], }, { diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 496e4154..2b3fe606 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -385,23 +385,5 @@ search Suchen - - -
-} - - -@if (showVisualization() && selectedKeywords().length > 0) { -
-
} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 24286a8e..1559ef1d 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -22,7 +22,6 @@ import { TopicsService } from '../../api/api/topics.service'; import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest'; import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component'; -import { UniTrendParentComponent } from '../university-ranking/uni-trend-parent/uni-trend-parent.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component'; @@ -66,7 +65,6 @@ type KeywordView = 'llm' | 'topic'; MatExpansionModule, MatProgressBarModule, TopicAutocompleteComponent, - UniTrendParentComponent, TopicChipComponent, TopicLegendComponent, MatButtonToggleModule, @@ -124,7 +122,6 @@ export class KeywordsSearchComponent { readonly isExtracting = signal(false); readonly loadingNewKeyword = signal(false); readonly extractionSource = signal(null); - readonly showVisualization = signal(false); readonly topicMappingSearch = signal(false); readonly keywordsExist = computed( @@ -607,8 +604,6 @@ export class KeywordsSearchComponent { } search(): void { - this.showVisualization.set(false); - const payload: SearchResultsPayload = { extractedKeywords: this.getSelectedExtractedKeywordEntries(), manualKeywords: this.getSelectedManualKeywordEntries(), @@ -638,10 +633,6 @@ export class KeywordsSearchComponent { }); } - visualize(): void { - this.showVisualization.set(true); - } - // --- Helpers -------------------------------------------------------------- private applyExtractedKeywords(keywords: ExtractedKeywords): void { @@ -908,8 +899,6 @@ export class KeywordsSearchComponent { updateQueryParams(): void { if (this.isRestoringState) return; - this.showVisualization.set(false); - const queryParams = { mode: this.form.controls.selectedInputType.value, url: this.toNullableParam(this.form.controls.urlInput.value), diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index 3d917a48..b431ca43 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -38,15 +38,64 @@ export class SearchResultsStateService { () => this._payload()?.manualKeywords ?? [], ); + // Compute unified list of KeywordEntryWithTopic matching selected keywords + readonly selectedKeywordEntries = computed(() => { + const payload = this._payload(); + if (!payload) return []; + + const allEntries = [ + ...(payload.extractedKeywords ?? []), + ...(payload.manualKeywords ?? []), + ]; + + const entryByKeyword = new Map(); + for (const entry of allEntries) { + const kw = entry.llm_keyword?.keyword; + if (kw) { + entryByKeyword.set(kw.trim().toLowerCase(), entry); + } + } + + const result: KeywordEntryWithTopic[] = []; + const seen = new Set(); + + for (const keyword of payload.keywords) { + const normalized = keyword.trim().toLowerCase(); + const entry = entryByKeyword.get(normalized); + if (!entry || seen.has(normalized)) continue; + seen.add(normalized); + result.push(entry); + } + + return result; + }); + + // Keywords that did not resolve to a mapped topic entry + readonly missingKeywordLabels = computed(() => { + const payload = this._payload(); + if (!payload) return []; + + const entryKeywordSet = new Set( + this.selectedKeywordEntries() + .map((entry) => entry.llm_keyword?.keyword?.trim().toLowerCase()) + .filter(Boolean), + ); + + return payload.keywords.filter( + (keyword) => !entryKeywordSet.has(keyword.trim().toLowerCase()), + ); + }); + // Compute parallel keywords and topic names for trend dashboard strategies readonly keywordsList = computed(() => this.keywords()); readonly topicsList = computed(() => { - const ext = this.extractedKeywords(); - const man = this.manualKeywords(); - const all = [...ext, ...man]; return this.keywords().map((kw) => { - const match = all.find((e) => e.llm_keyword?.keyword === kw); - return match?.topic_mapping?.topic?.display_name ?? kw; + const entry = this.selectedKeywordEntries().find( + (e) => + e.llm_keyword?.keyword?.trim().toLowerCase() === + kw.trim().toLowerCase(), + ); + return entry?.topic_mapping?.topic?.display_name ?? kw; }); }); diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html index d1ce9543..e38cc36a 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html @@ -22,7 +22,10 @@
- @for (entry of selectedKeywordEntries(); track getEntryTrack(entry)) { + @for ( + entry of state.selectedKeywordEntries(); + track getEntryTrack(entry) + ) { } - @for (keyword of missingKeywordLabels(); track keyword) { + @for (keyword of state.missingKeywordLabels(); track keyword) { this.state.keywords().length); - readonly selectedKeywordEntries = computed(() => { - const payload = this.state.payload(); - if (!payload) return []; - - const allEntries = [ - ...(payload.extractedKeywords ?? []), - ...(payload.manualKeywords ?? []), - ]; - - const entryByKeyword = new Map(); - - for (const entry of allEntries) { - entryByKeyword.set( - this.normalizeKeyword(this.getKeywordLabel(entry)), - entry, - ); - } - - const result: KeywordEntryWithTopic[] = []; - const seen = new Set(); - - for (const keyword of payload.keywords) { - const normalized = this.normalizeKeyword(keyword); - const entry = entryByKeyword.get(normalized); - - if (!entry || seen.has(normalized)) continue; - - seen.add(normalized); - result.push(entry); - } - - return result; - }); - - readonly missingKeywordLabels = computed(() => { - const payload = this.state.payload(); - if (!payload) return []; - - const entryKeywordSet = new Set( - this.selectedKeywordEntries().map((entry) => - this.normalizeKeyword(this.getKeywordLabel(entry)), - ), - ); - - return payload.keywords.filter( - (keyword) => !entryKeywordSet.has(this.normalizeKeyword(keyword)), - ); - }); - constructor() { // Query params are authoritative (URL survives reload, deep links, // browser back/forward). sessionStorage is a best-effort cache for the diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index b23e7f8c..a5613317 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -138,7 +138,16 @@ export class UniTrendParentComponent implements OnInit { }); // Input containing extracted/selected keywords from parent - readonly keywords = input([]); + readonly keywordsInput = input([], { alias: 'keywords' }); + + // Read keywords dynamically from SearchResultsStateService if available, otherwise from input. + readonly keywords = computed(() => { + const fromState = this.state?.keywords(); + if (fromState && fromState.length > 0) { + return fromState; + } + return this.keywordsInput(); + }); // Trend settings signals readonly selectedSearchType = signal< -- 2.56.1 From 01a37e2ea795b4a930d7198ba0640c4fcdbf028a Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 16:25:48 +0200 Subject: [PATCH 16/20] added comment to indicate unfinished parts --- .../src/main/inse/university_ranking/trend_strategies.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 720b275c..96f511f4 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -603,7 +603,7 @@ class AuthorsTrendStrategy(TrendStrategy): return TrendResponse(series=series_list, years=years_range) - +### index was not ready yet, change! class PatentsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -656,7 +656,7 @@ class PatentsTrendStrategy(TrendStrategy): return TrendResponse(series=series_list, years=years_range) - +### index? Or query against existing scattered indicies? class ProjectsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -708,7 +708,7 @@ class ProjectsTrendStrategy(TrendStrategy): return TrendResponse(series=series_list, years=years_range) - +### requires proper index (currently only workaround) class NewsTrendStrategy(TrendStrategy): async def get_trend( self, -- 2.56.1 From b983a01174d71c9f034c1dfa59ea913e0e9550e6 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 17:06:10 +0200 Subject: [PATCH 17/20] adapted to use fuzzy everywhere --- .../main/inse/university_ranking/service.py | 4 +-- .../university_ranking/trend_strategies.py | 26 +++++++++---------- .../keywords-search.component.html | 8 ------ .../uni-trend-parent.component.ts | 4 +-- 4 files changed, 17 insertions(+), 25 deletions(-) diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py index 0bd2b823..112a2a6f 100644 --- a/service/src/main/inse/university_ranking/service.py +++ b/service/src/main/inse/university_ranking/service.py @@ -67,7 +67,7 @@ async def get_rankings( async def get_trend( topics: List[str] = Query(..., description="List of topics to analyze"), keywords: Optional[List[str]] = Query(None, description="List of raw keywords corresponding to topics"), - soft_search: bool = Query(True, description="True if using mapped topics, False if using raw keywords"), + fuzzy: bool = Query(True, description="True if using mapped topics, False if using raw keywords"), institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"), countries: Optional[List[str]] = Query(None, description="List of country codes"), regions: Optional[List[str]] = Query(None, description="List of region identifiers"), @@ -77,7 +77,7 @@ async def get_trend( return await strategy.get_trend( topics=topics, keywords=keywords, - soft_search=soft_search, + fuzzy=fuzzy, institutions=institutions, countries=countries, regions=regions, diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 96f511f4..fbab0724 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -26,7 +26,7 @@ class TrendStrategy(abc.ABC): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -83,7 +83,7 @@ class PublicationsTrendStrategy(TrendStrategy): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -242,7 +242,7 @@ class PublicationsTrendStrategy(TrendStrategy): topic_clauses = [] topic_filters = {} for idx, t in enumerate(topics): - if not soft_search and keywords and idx < len(keywords): + if not fuzzy and keywords and idx < len(keywords): kw_val = keywords[idx] clause = { "bool": { @@ -403,7 +403,7 @@ class AuthorsTrendStrategy(TrendStrategy): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -481,7 +481,7 @@ class AuthorsTrendStrategy(TrendStrategy): topic_clauses = [] topic_filters = {} for idx, t in enumerate(topics): - if not soft_search and keywords and idx < len(keywords): + if not fuzzy and keywords and idx < len(keywords): kw_val = keywords[idx] clause = { "bool": { @@ -609,7 +609,7 @@ class PatentsTrendStrategy(TrendStrategy): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -662,7 +662,7 @@ class ProjectsTrendStrategy(TrendStrategy): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -714,7 +714,7 @@ class NewsTrendStrategy(TrendStrategy): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -834,7 +834,7 @@ class AllTrendStrategy(TrendStrategy): self, topics: List[str], keywords: Optional[List[str]] = None, - soft_search: bool = True, + fuzzy: bool = True, institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None, @@ -848,10 +848,10 @@ class AllTrendStrategy(TrendStrategy): news_strat = NewsTrendStrategy() # Query UDE publications data only - pub_task = pub_strat.get_trend(topics, keywords, soft_search, institutions=[DEFAULT_INSTITUTION_ID]) - pat_task = pat_strat.get_trend(topics, keywords, soft_search) - proj_task = proj_strat.get_trend(topics, keywords, soft_search) - news_task = news_strat.get_trend(topics, keywords, soft_search) + pub_task = pub_strat.get_trend(topics, keywords, fuzzy, institutions=[DEFAULT_INSTITUTION_ID]) + pat_task = pat_strat.get_trend(topics, keywords, fuzzy) + proj_task = proj_strat.get_trend(topics, keywords, fuzzy) + news_task = news_strat.get_trend(topics, keywords, fuzzy) pub_res, pat_res, proj_res, news_res = await asyncio.gather(pub_task, pat_task, proj_task, news_task) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 3de176be..3c490f39 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -455,11 +455,3 @@ } } - - -@if (showVisualization() && selectedKeywords().length > 0) { -
- -
-} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index a5613317..4e0888f4 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -920,13 +920,13 @@ export class UniTrendParentComponent implements OnInit { this.fetchedAuthors.set([...this.comparisonAuthors()]); const kws = this.state?.keywordsList() ?? []; - const softSearch = this.state?.softSearch() ?? true; + const fuzzy = this.state?.fuzzySearch() ?? true; this.apiService .getTrendApiInseServiceUniversityRankingsTrendGet( topics, kws, - softSearch, + fuzzy, this.comparisonInstitutions().map((i: CompareItem) => i.id), this.comparisonCountries().map((c: CompareItem) => c.id), this.comparisonRegions().map((r: CompareItem) => r.id), -- 2.56.1 From 31253ff03b3f021fbf506a22b15cbcdbf0bfaf18 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 17:40:28 +0200 Subject: [PATCH 18/20] regenerated frontend --- .../app/api/api/universityRankings.service.ts | 399 ++++++++++-------- webapp/src/app/api/model/accessToken.ts | 3 + webapp/src/app/api/model/accountProfile.ts | 1 - .../src/app/api/model/createAccountRequest.ts | 1 - .../src/app/api/model/updateAccountRequest.ts | 1 - 5 files changed, 225 insertions(+), 180 deletions(-) diff --git a/webapp/src/app/api/api/universityRankings.service.ts b/webapp/src/app/api/api/universityRankings.service.ts index c086e15c..a7aba880 100644 --- a/webapp/src/app/api/api/universityRankings.service.ts +++ b/webapp/src/app/api/api/universityRankings.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,8 +11,13 @@ import { Inject, Injectable, Optional } from '@angular/core'; import { - HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; @@ -37,14 +42,15 @@ import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class UniversityRankingsService extends BaseService { - - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string | string[], @Optional() configuration?: Configuration) { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { super(basePath, configuration); } @@ -55,43 +61,167 @@ export class UniversityRankingsService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; - public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>>; - public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>>; - public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.'); + throw new Error( + 'Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.', + ); } let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); const localVarTransferCache: boolean = options?.transferCache ?? true; - let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } + let localVarPath = `/api/inse-service/university-rankings/autocomplete-locations`; + 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 data for the University Ranking Dashboard. + * @endpoint get /api/inse-service/university-rankings + * @param topic Research topic display name or OpenAlex ID (e.g., \'Artificial Intelligence\') + * @param metric Metric to rank by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, + metric?: 'publications' | 'citations', + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, + metric?: 'publications' | 'citations', + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, + metric?: 'publications' | 'citations', + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, + metric?: 'publications' | 'citations', + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (topic === null || topic === undefined) { + throw new Error( + 'Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.', + ); + } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); localVarQueryParameters = this.addToHttpParams( localVarQueryParameters, @@ -454,7 +584,7 @@ export class UniversityRankingsService extends BaseService { * @endpoint get /api/inse-service/university-rankings/trend * @param topics List of topics to analyze * @param keywords List of raw keywords corresponding to topics - * @param softSearch True if using mapped topics, False if using raw keywords + * @param fuzzy True if using mapped topics, False if using raw keywords * @param institutions List of OpenAlex Institution IDs * @param countries List of country codes * @param regions List of region identifiers @@ -466,7 +596,7 @@ export class UniversityRankingsService extends BaseService { public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, keywords?: Array, - softSearch?: boolean, + fuzzy?: boolean, institutions?: Array, countries?: Array, regions?: Array, @@ -483,7 +613,7 @@ export class UniversityRankingsService extends BaseService { public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, keywords?: Array, - softSearch?: boolean, + fuzzy?: boolean, institutions?: Array, countries?: Array, regions?: Array, @@ -500,7 +630,7 @@ export class UniversityRankingsService extends BaseService { public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, keywords?: Array, - softSearch?: boolean, + fuzzy?: boolean, institutions?: Array, countries?: Array, regions?: Array, @@ -517,7 +647,7 @@ export class UniversityRankingsService extends BaseService { public getTrendApiInseServiceUniversityRankingsTrendGet( topics: Array, keywords?: Array, - softSearch?: boolean, + fuzzy?: boolean, institutions?: Array, countries?: Array, regions?: Array, @@ -545,162 +675,88 @@ export class UniversityRankingsService extends BaseService { element, 'topics', ); - } + }); + } if (keywords) { - keywords.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'keywords', - ); - }); - } - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - softSearch, - 'soft_search', - ); - if (institutions) { - institutions.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'institutions', - ); - } - - /** - * Returns top institutions filtered by country/region and sorted by topic-level publications count. - * @endpoint get /api/inse-service/university-rankings/top-institutions - * @param topic Research topic - * @param region Region identifier (e.g. EU) - * @param country Country code (e.g. DE) - * @param limit Max suggestions to return - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region ?: string, country ?: string, limit ?: number, observe ?: 'body', reportProgress ?: boolean, options ?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; - public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>>; - public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>>; - public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { - if (topic === null || topic === undefined) { - throw new Error('Required parameter topic was null or undefined when calling getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet.'); + keywords.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'keywords', + ); + }); } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - topic, 'topic'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - region, 'region'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - country, 'country'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); - - 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/university-rankings/top-institutions`; - 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 - } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fuzzy, + 'fuzzy', ); - } - - /** - * Returns timeseries publication data for compared institutions, countries and regions. - * @endpoint get /api/inse-service/university-rankings/trend - * @param topics List of topics to analyze - * @param institutions List of OpenAlex Institution IDs - * @param countries List of country codes - * @param regions List of region identifiers - * @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 getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array, institutions?: Array, countries?: Array, regions?: Array, observe?: 'body', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable; - public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array, institutions?: Array, countries?: Array, regions?: Array, observe?: 'response', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; - public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array, institutions?: Array, countries?: Array, regions?: Array, observe?: 'events', reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable>; - public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array, institutions?: Array, countries?: Array, regions?: Array, observe: any = 'body', reportProgress: boolean = false, options?: { httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean }): Observable { - if (topics === null || topics === undefined) { - throw new Error('Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.'); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topics) { - topics.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'topics'); - }) - } if (institutions) { institutions.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'institutions'); - }) + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'institutions', + ); + }); } if (countries) { countries.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'countries'); - }) + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'countries', + ); + }); } if (regions) { regions.forEach((element) => { - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - element, 'regions'); - }) + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'regions', + ); + }); } + if (authors) { + authors.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'authors', + ); + }); + } + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + searchType, + 'search_type', + ); let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); const localVarTransferCache: boolean = options?.transferCache ?? true; - let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { responseType_ = 'json'; } else { responseType_ = 'blob'; @@ -709,7 +765,9 @@ export class UniversityRankingsService extends BaseService { let localVarPath = `/api/inse-service/university-rankings/trend`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -717,24 +775,11 @@ export class UniversityRankingsService extends BaseService { ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, ); } - if(authors) { - authors.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'authors', - ); - }); - } - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'search_type', - ); - } diff --git a/webapp/src/app/api/model/accessToken.ts b/webapp/src/app/api/model/accessToken.ts index c20b6743..9505d3c6 100644 --- a/webapp/src/app/api/model/accessToken.ts +++ b/webapp/src/app/api/model/accessToken.ts @@ -39,6 +39,9 @@ export interface AccessToken { * The specific role this access token grants within its organization. */ effective_role?: UserRole; + /** + * The roles this access token grants within its organization. + */ effective_roles?: Array; /** * The unique identifier of the organization associated with this access token. diff --git a/webapp/src/app/api/model/accountProfile.ts b/webapp/src/app/api/model/accountProfile.ts index 02ecd34a..a61b98ae 100644 --- a/webapp/src/app/api/model/accountProfile.ts +++ b/webapp/src/app/api/model/accountProfile.ts @@ -22,4 +22,3 @@ export interface AccountProfile { is_real_account?: boolean; is_impersonating?: boolean; } -export namespace AccountProfile {} diff --git a/webapp/src/app/api/model/createAccountRequest.ts b/webapp/src/app/api/model/createAccountRequest.ts index 2eaaa17d..c38fce15 100644 --- a/webapp/src/app/api/model/createAccountRequest.ts +++ b/webapp/src/app/api/model/createAccountRequest.ts @@ -17,4 +17,3 @@ export interface CreateAccountRequest { password: string; openalex_person_id?: string | null; } -export namespace CreateAccountRequest {} diff --git a/webapp/src/app/api/model/updateAccountRequest.ts b/webapp/src/app/api/model/updateAccountRequest.ts index 3e5ad04f..db502fd9 100644 --- a/webapp/src/app/api/model/updateAccountRequest.ts +++ b/webapp/src/app/api/model/updateAccountRequest.ts @@ -19,4 +19,3 @@ export interface UpdateAccountRequest { deleted?: boolean | null; activated?: boolean | null; } -export namespace UpdateAccountRequest {} -- 2.56.1 From 6627651ae03b674522bff39c1b90ac2b71147652 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 17:57:50 +0200 Subject: [PATCH 19/20] fixed initial word to Topic mapping and search --- .../university_ranking/trend_strategies.py | 40 ++------------- .../search-results.component.scss | 1 + .../uni-trend-parent.component.scss | 2 + .../uni-trend-parent.component.ts | 50 +++++++++++++++---- 4 files changed, 46 insertions(+), 47 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index fbab0724..904f76d8 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -258,25 +258,9 @@ class PublicationsTrendStrategy(TrendStrategy): else: tid = resolved_topic_ids.get(t) if tid: - clause = { - "bool": { - "should": [ - {"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}}, - {"term": {"primary_topic.id": tid}} - ], - "minimum_should_match": 1 - } - } + clause = {"term": {"primary_topic.id": tid}} else: - clause = { - "bool": { - "should": [ - {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}}, - {"match_phrase": {"primary_topic.display_name": t}} - ], - "minimum_should_match": 1 - } - } + clause = {"match_phrase": {"primary_topic.display_name": t}} topic_clauses.append(clause) topic_filters[t] = clause @@ -497,25 +481,9 @@ class AuthorsTrendStrategy(TrendStrategy): else: tid = resolved_topic_ids.get(t) if tid: - clause = { - "bool": { - "should": [ - {"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}}, - {"term": {"primary_topic.id": tid}} - ], - "minimum_should_match": 1 - } - } + clause = {"term": {"primary_topic.id": tid}} else: - clause = { - "bool": { - "should": [ - {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}}, - {"match_phrase": {"primary_topic.display_name": t}} - ], - "minimum_should_match": 1 - } - } + clause = {"match_phrase": {"primary_topic.display_name": t}} topic_clauses.append(clause) topic_filters[t] = clause diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/search-results.component.scss index b1d2a7ee..d3dcdd8a 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.scss @@ -93,6 +93,7 @@ $touch-target: 44px; .keyword-stack { display: flex; flex-wrap: wrap; + align-items: center; gap: 0.6rem; ::ng-deep app-topic-chip .topic-chip__count { diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 03d0fa32..7ee9af22 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -135,6 +135,8 @@ .chart-topic-tabs { display: flex; + flex-wrap: wrap; + align-items: center; gap: 0.4rem; padding: 0.6rem 1rem; background: #f9fafb; diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 4e0888f4..f820db7e 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -188,6 +188,7 @@ export class UniTrendParentComponent implements OnInit { readonly fetchedCountries = signal([]); readonly fetchedRegions = signal([]); readonly fetchedAuthors = signal([]); + readonly fetchedFuzzy = signal(null); // Results & Loading signals readonly rawTrendResponse = signal(null); @@ -199,12 +200,25 @@ export class UniTrendParentComponent implements OnInit { readonly isTopTopicsLoading = signal(false); readonly topTopicsError = signal(false); + getMappedTopic(topicOrKeyword: string): string { + const kws = this.keywords(); + const topics = this.state?.topicsList() ?? kws; + const idx = kws.findIndex( + (k) => k.toLowerCase() === topicOrKeyword.toLowerCase(), + ); + if (idx !== -1 && topics[idx]) { + return topics[idx]; + } + return topicOrKeyword; + } + getTopicColor(topic: string): string { + const mapped = this.getMappedTopic(topic); const ext = this.state?.extractedKeywords() ?? []; const man = this.state?.manualKeywords() ?? []; const all = [...ext, ...man]; const match = all.find( - (e) => e.topic_mapping?.topic?.display_name === topic, + (e) => e.topic_mapping?.topic?.display_name === mapped, ); if (match && match.topic_mapping?.topic) { return topicHierarchyColor({ @@ -216,7 +230,7 @@ export class UniTrendParentComponent implements OnInit { id: match.topic_mapping.topic.id, }); } - return topicHierarchyColor({ name: topic }); + return topicHierarchyColor({ name: mapped }); } readonly boundGetTopicColor = this.getTopicColor.bind(this); @@ -394,22 +408,24 @@ export class UniTrendParentComponent implements OnInit { this.availableYears.push(y); } - // Effect: automatically sync checkboxes list whenever input keywords change + // Effect: automatically sync checkboxes list whenever input keywords or fuzzy state changes effect(() => { const kws = this.keywords(); + const fuzzy = this.state?.fuzzySearch() ?? true; + const topics = fuzzy ? (this.state?.topicsList() ?? kws) : kws; const currentSelections = untracked(() => this.selectedTrendTopics()); const currentActive = untracked(() => this.activeChartTopic()); const searchType = this.selectedSearchType(); - if (kws.length > 0) { - // Find existing selections that are still in keywords, or default to all + if (topics.length > 0) { + // Find existing selections that are still in topics, or default to all const validSelections = currentSelections.filter((t: string) => - kws.includes(t), + topics.includes(t), ); if (validSelections.length > 0) { this.selectedTrendTopics.set(validSelections); } else { - this.selectedTrendTopics.set(kws); + this.selectedTrendTopics.set(topics); } // Initialize active chart topic to the first selected topic if empty or invalid @@ -455,14 +471,17 @@ export class UniTrendParentComponent implements OnInit { const regions = this.comparisonRegions(); const authors = this.comparisonAuthors(); const searchType = this.selectedSearchType(); + const fuzzy = this.state?.fuzzySearch() ?? true; if (topics.length === 0) return; const fetchedT = new Set(untracked(() => this.fetchedTopics())); const fetchedType = untracked(() => this.fetchedSearchType()); + const fetchedF = untracked(() => this.fetchedFuzzy()); const allTopicsFetched = topics.every((t) => fetchedT.has(t)); const sameType = searchType === fetchedType; + const sameFuzzy = fuzzy === fetchedF; let allEntitiesFetched = false; if (sameType) { @@ -502,7 +521,13 @@ export class UniTrendParentComponent implements OnInit { } const hasResponse = !!untracked(() => this.rawTrendResponse()); - if (allTopicsFetched && sameType && allEntitiesFetched && hasResponse) { + if ( + allTopicsFetched && + sameType && + sameFuzzy && + allEntitiesFetched && + hasResponse + ) { // All requested data is already present in rawTrendResponse, so skip backend call! return; } @@ -835,13 +860,14 @@ export class UniTrendParentComponent implements OnInit { this.isSuggestionsLoading.set(true); const kws = this.keywords(); const topics = this.state?.topicsList() ?? kws; - const topic = + const rawTopic = this.activeChartTopic() || (this.selectedTrendTopics().length > 0 ? this.selectedTrendTopics()[0] : topics.length > 0 ? topics[0] : 'Artificial Intelligence'); + const topic = this.getMappedTopic(rawTopic); const countryFilter = this.comparisonCountries().length > 0 @@ -875,13 +901,14 @@ export class UniTrendParentComponent implements OnInit { this.isSuggestionsLoading.set(true); const kws = this.keywords(); const topics = this.state?.topicsList() ?? kws; - const topic = + const rawTopic = this.activeChartTopic() || (this.selectedTrendTopics().length > 0 ? this.selectedTrendTopics()[0] : topics.length > 0 ? topics[0] : 'Artificial Intelligence'); + const topic = this.getMappedTopic(rawTopic); this.personsApiService .searchPersonsList( @@ -918,9 +945,10 @@ export class UniTrendParentComponent implements OnInit { this.fetchedCountries.set([...this.comparisonCountries()]); this.fetchedRegions.set([...this.comparisonRegions()]); this.fetchedAuthors.set([...this.comparisonAuthors()]); + const fuzzy = this.state?.fuzzySearch() ?? true; + this.fetchedFuzzy.set(fuzzy); const kws = this.state?.keywordsList() ?? []; - const fuzzy = this.state?.fuzzySearch() ?? true; this.apiService .getTrendApiInseServiceUniversityRankingsTrendGet( -- 2.56.1 From e9d268ff9fb392c0493eb359e00c9bd09060200b Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 13 Jul 2026 18:18:32 +0200 Subject: [PATCH 20/20] added alternative names to searches --- .../inse/university_ranking/trend_logic.py | 119 +++++++++++++++--- .../uni-trend-chart.component.ts | 12 +- .../uni-trend-parent.component.html | 3 +- .../uni-trend-parent.component.ts | 29 ++++- 4 files changed, 142 insertions(+), 21 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 0c3f7ebc..c5abd8ac 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -30,25 +30,67 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: import asyncio - # Query countries index (Idea: Instead of wildcard: use alternative names?) + # Query countries index with alternatives and prefix boosts country_query = { "bool": { "should": [ { - "wildcard": { - "display_name.keyword": { - "value": f"*{stripped}*", - "case_insensitive": True + "match": { + "country_code": { + "query": stripped.upper(), + "boost": 20 + } + } + }, + { + "match_phrase_prefix": { + "display_name": { + "query": stripped, + "boost": 10 + } + } + }, + { + "match_phrase_prefix": { + "display_name_alternatives": { + "query": stripped, + "boost": 8 } } }, { "match": { - "country_code": { - "query": stripped.upper(), + "display_name": { + "query": stripped, "boost": 5 } } + }, + { + "match": { + "display_name_alternatives": { + "query": stripped, + "boost": 4 + } + } + }, + { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True, + "boost": 1 + } + } + }, + { + "wildcard": { + "display_name_alternatives.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True, + "boost": 1 + } + } } ], "minimum_should_match": 1 @@ -57,11 +99,60 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: # Query continents index continent_query = { - "wildcard": { - "display_name.keyword": { - "value": f"*{stripped}*", - "case_insensitive": True - } + "bool": { + "should": [ + { + "match_phrase_prefix": { + "display_name": { + "query": stripped, + "boost": 10 + } + } + }, + { + "match_phrase_prefix": { + "display_name_alternatives": { + "query": stripped, + "boost": 8 + } + } + }, + { + "match": { + "display_name": { + "query": stripped, + "boost": 5 + } + } + }, + { + "match": { + "display_name_alternatives": { + "query": stripped, + "boost": 4 + } + } + }, + { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True, + "boost": 1 + } + } + }, + { + "wildcard": { + "display_name_alternatives.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True, + "boost": 1 + } + } + } + ], + "minimum_should_match": 1 } } @@ -181,11 +272,11 @@ async def get_top_institutions_by_region( query = {"bool": {"filter": must_clauses}} - # Fetch top 50 by overall works count to cover a good pool of institutions + # Fetch top 500 by overall works count to cover a good pool of institutions res = await elasticsearch.search( index=str(ESIndex.OPENALEX_INSTITUTIONS), query=query, - size=50, + size=500, source=["id", "display_name", "country_code", "works_count", "topics"], sort=[{"works_count": "desc"}], cluster="nes" diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 41664237..cfa68ac1 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -23,6 +23,7 @@ export class UniTrendChartComponent { readonly activeTopic = input(null); readonly startYear = input(2010); readonly endYear = input(2025); + readonly getEntityColor = input<(id: string) => string>(); // Computed signal to automatically rebuild ECharts options when data or mode changes readonly chartOptions = computed(() => { @@ -70,12 +71,13 @@ export class UniTrendChartComponent { '#eab308', // Amber/Yellow Dark '#f43f5e', // Rose ]; - const getEntityColor = (idx: number) => - entityColors[idx % entityColors.length]; + const getFn = this.getEntityColor(); // Build series: Line in top grid, growth volume bars and S-Curve in bottom grid trendData.series.forEach((entity, entityIdx) => { - const color = getEntityColor(entityIdx); + const color = getFn + ? getFn(entity.entity_id) + : entityColors[entityIdx % entityColors.length]; if ((entity as any).visible === false) { return; } @@ -196,7 +198,9 @@ export class UniTrendChartComponent { res += `
`; trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { - const color = getEntityColor(entityIdx); + const color = getFn + ? getFn(entity.entity_id) + : entityColors[entityIdx % entityColors.length]; if ((entity as any).visible === false) { return; } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 00bc05d1..eaf0b4a9 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -129,7 +129,8 @@ [mode]="chartMode()" [activeTopic]="activeChartTopic()" [startYear]="startYear()" - [endYear]="endYear()"> + [endYear]="endYear()" + [getEntityColor]="boundGetEntityColor">
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index f820db7e..160ed637 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -923,8 +923,33 @@ export class UniTrendParentComponent implements OnInit { ) .subscribe({ next: (res) => { - this.recommendedAuthors.set(res.results || []); - this.isSuggestionsLoading.set(false); + if (res.results && res.results.length > 0) { + this.recommendedAuthors.set(res.results); + this.isSuggestionsLoading.set(false); + } else { + // Fallback: search globally across all institutions + this.personsApiService + .searchPersonsList( + undefined, + undefined, // global! + undefined, + undefined, + [topic], + 1, + 6, + undefined, + ) + .subscribe({ + next: (globalRes) => { + this.recommendedAuthors.set(globalRes.results || []); + this.isSuggestionsLoading.set(false); + }, + error: () => { + this.recommendedAuthors.set([]); + this.isSuggestionsLoading.set(false); + }, + }); + } }, error: () => { this.isSuggestionsLoading.set(false); -- 2.56.1