From 34c02351123bf1defbe41ddfd7f494a649b0bce6 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 14:22:57 +0100 Subject: [PATCH 01/36] updated keywords-wordcloud component. Adde more optional fields for reusability --- .../keyword-wordcloud.component.html | 66 +++++-- .../keyword-wordcloud.component.scss | 93 ++++++++++ .../keyword-wordcloud.component.ts | 163 ++++++++++++++---- 3 files changed, 275 insertions(+), 47 deletions(-) diff --git a/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.html b/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.html index bb200604..cc6e9a8a 100644 --- a/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.html +++ b/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.html @@ -1,5 +1,10 @@ -
- @if (title) { +
+ @if (title && variant !== 'bare') {

{{ title }}

@@ -7,30 +12,63 @@

{{ subtitle }}

}
- @if (showCount && displayWords.length) { + @if (showCount && !loading && !loadFailed && displayWords.length) { {{ displayWords.length }} Begriffe }
} - @if (displayWords.length) { -
+ @if (loading) { +
+ {{ loadingMessage }} +
+ } @else if (loadFailed) { +
+ {{ loadFailedMessage }} +
+ } @else if (displayWords.length) { +
@for (word of displayWords; track word.id) { - - {{ word.name }} - + @if (wordTooltip; as tooltip) { + + } @else { + + } }
} @else {
{{ emptyTitle }} - {{ emptyMessage }} + @if (emptyMessage) { + {{ emptyMessage }} + }
}
diff --git a/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.scss b/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.scss index 6b6c950f..68eb626e 100644 --- a/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.scss +++ b/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.scss @@ -1,3 +1,7 @@ +:host { + display: block; +} + .word-cloud-panel { overflow: hidden; border: 1px solid var(--sg-border, #e2e5ea); @@ -53,21 +57,44 @@ } .word-cloud-word { + appearance: none; + margin: 0; padding: 3px 5px; border: 1px solid transparent; border-radius: 6px; + background: none; + color: inherit; line-height: 1.1; text-align: center; font-family: inherit; user-select: none; + cursor: default; transition: transform 150ms ease, background-color 150ms ease; + &:not(:disabled) { + cursor: pointer; + } + &:hover { background: var(--sg-surface-soft, #f2f4f7); transform: translateY(-2px); } + + &:focus-visible { + outline: 2px solid var(--sg-primary, #5b8ff9); + outline-offset: 2px; + } + + &:disabled { + opacity: 1; + } +} + +.word-cloud-word-active { + background: color-mix(in srgb, currentColor 14%, transparent); + box-shadow: inset 0 0 0 1.5px currentColor; } .word-cloud-state { @@ -102,6 +129,72 @@ font-size: 22px; } +/* --------------------------------- bare ---------------------------------- */ + +.word-cloud-panel--bare { + overflow: visible; + border: none; + border-radius: 0; + background: transparent; + box-shadow: none; + + .word-cloud-chart { + min-height: 420px; + gap: 0.35em 1em; + padding: 1.5rem 1rem; + background: transparent; + } + + .word-cloud-word { + padding: 0.1em 0.3em; + border: none; + border-radius: 6px; + background: none; + font-family: 'Open Sans', Arial, sans-serif; + transition: + transform 0.15s ease, + background-color 0.15s ease, + box-shadow 0.15s ease; + + &:hover:not(:disabled), + &:focus-visible { + background: none; + transform: scale(1.08); + outline: none; + } + + &:disabled { + cursor: default; + } + } + + .word-cloud-word-active { + background: color-mix(in srgb, currentColor 14%, transparent); + box-shadow: inset 0 0 0 1.5px currentColor; + + &:hover:not(:disabled) { + background: color-mix(in srgb, currentColor 14%, transparent); + } + } + + .word-cloud-state { + min-height: 420px; + padding: 0; + font-size: 14px; + + .state-icon { + display: none; + } + + strong { + margin: 0; + color: var(--sg-text-muted, #6b7280); + font-size: 14px; + font-weight: 400; + } + } +} + @media (max-width: 700px) { .word-cloud-chart { min-height: 240px; diff --git a/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.ts b/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.ts index 0208e97d..a4934c0d 100644 --- a/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.ts +++ b/webapp/src/app/shared/ui/keyword-wordcloud/keyword-wordcloud.component.ts @@ -1,16 +1,52 @@ +import { ComponentType } from '@angular/cdk/portal'; import { CommonModule } from '@angular/common'; -import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; +import { + Component, + EventEmitter, + Input, + OnChanges, + Output, + SimpleChanges, +} from '@angular/core'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; + +/** A word with optional presentation overrides and arbitrary caller metadata. */ +export interface WordCloudWordData { + name: string; + count?: number; + id?: string; + color?: string; + fontSize?: number; + fontWeight?: number; + active?: boolean; + disabled?: boolean; +} /** A word can be a plain string or an object with an optional weight/count. */ -export type WordCloudWord = string | { name: string; count?: number }; +export type WordCloudWord = string | WordCloudWordData; + +/** + * Optional per-word tooltip. The shared component owns the trigger element, + * the caller supplies the component and its inputs. + */ +export interface WordCloudTooltipConfig { + component: ComponentType; + inputs?: (word: WordCloudWordData) => Record | null; + disabled?: (word: WordCloudWordData) => boolean; + maxWidth?: string | number | null; +} + +export type WordCloudVariant = 'panel' | 'bare'; interface DisplayWord { id: string; name: string; - count: number; color: string; fontSize: number; fontWeight: number; + active: boolean; + disabled: boolean; + source: WordCloudWordData; } const DEFAULT_COLORS = [ @@ -29,13 +65,13 @@ const DEFAULT_COLORS = [ @Component({ selector: 'app-keyword-wordcloud', standalone: true, - imports: [CommonModule], + imports: [CommonModule, ComponentTooltipDirective], templateUrl: './keyword-wordcloud.component.html', styleUrl: './keyword-wordcloud.component.scss', }) export class KeywordWordcloudComponent implements OnChanges { /** The keywords to display. Accepts plain strings or { name, count? } objects. */ - @Input() words: WordCloudWord[] = []; + @Input() words: readonly WordCloudWord[] = []; /** Panel header title. Set to '' / null to hide the header entirely. */ @Input() title: string | null = 'Keywords'; @@ -43,9 +79,18 @@ export class KeywordWordcloudComponent implements OnChanges { /** Optional descriptive subtitle under the title. */ @Input() subtitle?: string; + /** `panel` renders the card chrome, `bare` embeds the words without it. */ + @Input() variant: WordCloudVariant = 'panel'; + /** Show the "N Begriffe" count badge in the header. */ @Input() showCount = true; + @Input() loading = false; + @Input() loadingMessage = 'Keywords werden geladen …'; + + @Input() loadFailed = false; + @Input() loadFailedMessage = 'Keywords konnten nicht geladen werden.'; + @Input() emptyTitle = 'Keine Keywords gefunden'; @Input() emptyMessage = 'Für dieses Element sind keine Keywords vorhanden.'; @@ -53,7 +98,22 @@ export class KeywordWordcloudComponent implements OnChanges { @Input() maxFontSize = 34; /** Override the color palette used to cycle through words. */ - @Input() colors: string[] = DEFAULT_COLORS; + @Input() colors: readonly string[] = DEFAULT_COLORS; + + /** Words become focusable buttons that emit `wordClick`; otherwise they are static. */ + @Input() interactive = false; + + @Input() chartAriaLabel = 'Wordcloud der Keywords'; + + /** Optional predicate to mark a word as active (e.g. a legend selection). */ + @Input() isWordActive?: (word: WordCloudWordData) => boolean; + + /** Optional per-word accessible label. Falls back to the word itself. */ + @Input() wordAriaLabel?: (word: WordCloudWordData) => string | null; + + @Input() wordTooltip?: WordCloudTooltipConfig | null; + + @Output() wordClick = new EventEmitter(); displayWords: DisplayWord[] = []; @@ -68,51 +128,88 @@ export class KeywordWordcloudComponent implements OnChanges { } } - private buildWords(input: WordCloudWord[]): DisplayWord[] { + selectWord(word: DisplayWord): void { + if (!this.interactive || word.disabled) return; + this.wordClick.emit(word.source); + } + + isActive(word: DisplayWord): boolean { + return word.active || (this.isWordActive?.(word.source) ?? false); + } + + ariaLabelFor(word: DisplayWord): string { + return this.wordAriaLabel?.(word.source) ?? word.name; + } + + tooltipInputsFor(word: DisplayWord): Record | null { + return this.wordTooltip?.inputs?.(word.source) ?? null; + } + + tooltipDisabledFor(word: DisplayWord): boolean { + return this.wordTooltip?.disabled?.(word.source) ?? false; + } + + private buildWords(input: readonly WordCloudWord[]): DisplayWord[] { if (!input.length) return []; const normalized = this.normalize(input); - const counts = normalized.map((w) => w.count); + const counts = normalized.map((word) => word.count); const minimum = Math.min(...counts); const maximum = Math.max(...counts); const scaled = normalized.map((word, index) => { const intensity = maximum === minimum ? 1 : (word.count - minimum) / (maximum - minimum); + const source = word.source; + return { - id: `${word.name}-${index}`, - name: word.name, - count: word.count, - color: this.colors[index % this.colors.length], - fontSize: Math.round( - this.minFontSize + intensity * (this.maxFontSize - this.minFontSize), - ), - fontWeight: intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400, + id: source.id ?? `${source.name}-${index}`, + name: source.name, + color: source.color ?? this.colors[index % this.colors.length], + fontSize: + source.fontSize ?? + Math.round( + this.minFontSize + + intensity * (this.maxFontSize - this.minFontSize), + ), + fontWeight: + source.fontWeight ?? + (intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400), + active: source.active ?? false, + disabled: source.disabled ?? false, + source, }; }); - // Alternating push/unshift → bigger/earlier words gravitate toward the middle + return this.centre(scaled); + } + + /** Resolves each word to a { name, count } pair, falling back to rank-based sizing. */ + private normalize( + input: readonly WordCloudWord[], + ): { name: string; count: number; source: WordCloudWordData }[] { + const objects: WordCloudWordData[] = input.map((word) => + typeof word === 'string' ? { name: word } : word, + ); + const hasAllCounts = objects.every( + (word) => typeof word.count === 'number', + ); + + return objects.map((word, index) => ({ + name: word.name, + count: hasAllCounts ? (word.count as number) : objects.length - index, + source: word, + })); + } + + /** Alternating push/unshift → bigger/earlier words gravitate toward the middle. */ + private centre(words: DisplayWord[]): DisplayWord[] { const centred: DisplayWord[] = []; - scaled.forEach((word, index) => { + words.forEach((word, index) => { if (index % 2 === 0) centred.push(word); else centred.unshift(word); }); return centred; } - - /** Resolves each word to a { name, count } pair, falling back to rank-based sizing. */ - private normalize(input: WordCloudWord[]): { name: string; count: number }[] { - const hasAllCounts = input.every( - (w) => typeof w !== 'string' && typeof w.count === 'number', - ); - - return input.map((w, index) => { - const name = typeof w === 'string' ? w : w.name; - const count = hasAllCounts - ? (w as { name: string; count: number }).count - : input.length - index; // rank-based decay: first = biggest - return { name, count }; - }); - } } From e63f2e99d863568d36e429932b96adeee8bace4e Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 14:24:26 +0100 Subject: [PATCH 02/36] created utils for research wordcloud to enable compatibility to the shared keywords-wordcloud component --- .../research-wordcloud.utils.ts | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 webapp/src/app/modules/person-overview/research-wordcloud.utils.ts diff --git a/webapp/src/app/modules/person-overview/research-wordcloud.utils.ts b/webapp/src/app/modules/person-overview/research-wordcloud.utils.ts new file mode 100644 index 00000000..cbeced4d --- /dev/null +++ b/webapp/src/app/modules/person-overview/research-wordcloud.utils.ts @@ -0,0 +1,166 @@ +import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { + getTopicLegendFieldId, + getTopicLegendSubfieldId, + TopicLegendTopic, +} from '../../resolvers/utils/topic-legend'; +import type { WordCloudWordData } from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component'; +import type { + TopicTimelineElement, + TopicTimelineTopic, +} from './components/research-timeline/research-timeline.component'; + +export interface WordCloudWord extends WordCloudWordData { + topicId: string; + rawTopicId: string; + fieldLegendId: string; + subfieldLegendId: string; + color: string; + fontSize: number; + fontWeight: number; +} + +export interface ResearchWordcloud { + words: WordCloudWord[]; + legendTopics: TopicLegendTopic[]; +} + +const displayedWordLimit = 30; +const minimumFontSize = 12; +const maximumFontSize = 32; + +interface AggregatedTopic { + name: string; + count: number; + legendTopic: TopicLegendTopic; +} + +export function buildResearchWordcloud( + elements: readonly TopicTimelineElement[], + startYear: number | undefined, + endYear: number | undefined, +): ResearchWordcloud { + const yearsInRange = elements.filter((element) => + isWithinYearRange(element.year, startYear, endYear), + ); + + const aggregated = aggregateTopics(yearsInRange); + + if (aggregated.size === 0) { + return { words: [], legendTopics: [] }; + } + + const displayed = Array.from(aggregated.values()) + .sort( + (left, right) => + right.count - left.count || left.name.localeCompare(right.name), + ) + .slice(0, displayedWordLimit); + + const intensity = buildIntensityScale(displayed); + + const words = displayed.map((topic): WordCloudWord => { + const legendTopic = topic.legendTopic; + const scale = intensity(topic.count); + + return { + name: topic.name, + topicId: legendTopic.id ?? '', + rawTopicId: stripOpenAlexId(legendTopic.id), + fieldLegendId: getTopicLegendFieldId(legendTopic), + subfieldLegendId: getTopicLegendSubfieldId(legendTopic), + color: topicHierarchyColor(legendTopic), + fontSize: Math.round( + minimumFontSize + scale * (maximumFontSize - minimumFontSize), + ), + fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400, + }; + }); + + return { + words, + legendTopics: displayed.map((topic) => topic.legendTopic), + }; +} + +function aggregateTopics( + elements: readonly TopicTimelineElement[], +): Map { + const aggregated = new Map(); + + for (const element of elements) { + for (const topic of element.primary_topics ?? []) { + if (!topic.name) { + continue; + } + + const key = topic.id ?? topic.name; + const existing = aggregated.get(key); + + if (existing) { + existing.count += topic.count; + continue; + } + + aggregated.set(key, { + name: topic.name, + count: topic.count, + legendTopic: toLegendTopic(topic), + }); + } + } + + return aggregated; +} + +function buildIntensityScale( + topics: readonly AggregatedTopic[], +): (count: number) => number { + const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0))); + const minimumWeight = Math.min(...weights); + const maximumWeight = Math.max(...weights); + + if (maximumWeight === minimumWeight) { + return () => 0.5; + } + + return (count) => + (Math.sqrt(Math.max(count, 0)) - minimumWeight) / + (maximumWeight - minimumWeight); +} + +function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic { + return { + id: topic.id, + name: topic.name, + field_id: topic.field_id, + field_name: topic.field_name, + field_description: topic.field_description, + domain_id: topic.domain_id, + domain_name: topic.domain_name, + domain_description: topic.domain_description, + subfield_id: topic.subfield_id, + subfield_name: topic.subfield_name, + subfield_description: topic.subfield_description, + }; +} + +function isWithinYearRange( + year: number | undefined, + startYear: number | undefined, + endYear: number | undefined, +): boolean { + if (startYear !== undefined && (year === undefined || year < startYear)) { + return false; + } + + if (endYear !== undefined && (year === undefined || year > endYear)) { + return false; + } + + return true; +} + +function stripOpenAlexId(id: string | null | undefined): string { + return (id ?? '').replace('https://openalex.org/', ''); +} From 90c6fa56c8addca2588d53061f04858e9c09fe76 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 14:26:13 +0100 Subject: [PATCH 03/36] research-wordcloud component replaced by the shared keywords-component --- .../research-wordcloud.component.html | 30 -- .../research-wordcloud.component.scss | 59 ---- .../research-wordcloud.component.ts | 305 ------------------ .../person-overview.component.html | 20 +- .../person-overview.component.ts | 80 ++++- 5 files changed, 87 insertions(+), 407 deletions(-) delete mode 100644 webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html delete mode 100644 webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss delete mode 100644 webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html deleted file mode 100644 index 80fdda5d..00000000 --- a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.html +++ /dev/null @@ -1,30 +0,0 @@ -@if (loading) { -
Forschungsthemen werden geladen ...
-} @else if (loadFailed) { -
- Forschungsthemen konnten nicht geladen werden. -
-} @else if (words.length) { -
- @for (word of words; track word.name) { - - } -
-} @else { -

Keine Forschungsthemen gefunden.

-} diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss deleted file mode 100644 index 3d944b96..00000000 --- a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.scss +++ /dev/null @@ -1,59 +0,0 @@ -:host { - display: block; - min-height: 420px; -} - -.word-cloud-chart { - width: 100%; - min-height: 420px; - display: flex; - flex-wrap: wrap; - align-content: center; - align-items: baseline; - justify-content: center; - gap: 0.35em 1em; - padding: 1.5rem 1rem; - box-sizing: border-box; -} - -.word-cloud-word { - appearance: none; - border: none; - background: none; - padding: 0.1em 0.3em; - margin: 0; - border-radius: 6px; - font-family: 'Open Sans', Arial, sans-serif; - line-height: 1.1; - cursor: pointer; - transition: - transform 0.15s ease, - background-color 0.15s ease, - box-shadow 0.15s ease; - - &:hover:not(:disabled), - &:focus-visible { - transform: scale(1.08); - outline: none; - } - - &:disabled { - cursor: default; - } -} - -.word-cloud-word-active { - background: color-mix(in srgb, currentColor 14%, transparent); - box-shadow: inset 0 0 0 1.5px currentColor; -} - -.word-cloud-state { - margin: 0; - min-height: 420px; - display: flex; - align-items: center; - justify-content: center; - color: var(--sg-text-muted); - font-size: 14px; - text-align: center; -} diff --git a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts b/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts deleted file mode 100644 index 70d0e77d..00000000 --- a/webapp/src/app/modules/person-overview/components/research-wordcloud/research-wordcloud.component.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { Component, EventEmitter, Input, Output } from '@angular/core'; - -import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive'; -import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component'; -import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors'; -import { - getTopicLegendFieldId, - getTopicLegendSubfieldId, - TopicLegendTopic, -} from '../../../../resolvers/utils/topic-legend'; -import type { - TopicTimelineElement, - TopicTimelineTopic, -} from '../research-timeline/research-timeline.component'; -import { - formatYearRange, - normalizeSelectedYears, -} from '../../../../resolvers/utils/year-range'; -import { workQueryParamKeys } from '../../../../resolvers/work-page.resolver'; - -interface WordTooltipInputs { - topicId: string; - secondaryActionLabel: string | null; - secondaryActionLink: unknown[] | null; - secondaryActionQueryParams: Record; -} - -export interface WordCloudWord { - name: string; - topicId: string; - rawTopicId: string; - fieldLegendId: string; - subfieldLegendId: string; - color: string; - fontSize: number; - fontWeight: number; -} - -export interface ResearchWordcloud { - words: WordCloudWord[]; - legendTopics: TopicLegendTopic[]; -} - -const displayedWordLimit = 30; -const minimumFontSize = 12; -const maximumFontSize = 32; - -interface AggregatedTopic { - name: string; - count: number; - legendTopic: TopicLegendTopic; -} - -export function buildResearchWordcloud( - elements: readonly TopicTimelineElement[], - startYear: number | undefined, - endYear: number | undefined, -): ResearchWordcloud { - const yearsInRange = elements.filter((element) => - isWithinYearRange(element.year, startYear, endYear), - ); - - const aggregated = aggregateTopics(yearsInRange); - - if (aggregated.size === 0) { - return { words: [], legendTopics: [] }; - } - - const displayed = Array.from(aggregated.values()) - .sort( - (left, right) => - right.count - left.count || left.name.localeCompare(right.name), - ) - .slice(0, displayedWordLimit); - - const intensity = buildIntensityScale(displayed); - - const words = displayed.map((topic): WordCloudWord => { - const legendTopic = topic.legendTopic; - const scale = intensity(topic.count); - - return { - name: topic.name, - topicId: legendTopic.id ?? '', - rawTopicId: stripOpenAlexId(legendTopic.id), - fieldLegendId: getTopicLegendFieldId(legendTopic), - subfieldLegendId: getTopicLegendSubfieldId(legendTopic), - color: topicHierarchyColor(legendTopic), - fontSize: Math.round( - minimumFontSize + scale * (maximumFontSize - minimumFontSize), - ), - fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400, - }; - }); - - return { - words: centreWords(words), - legendTopics: displayed.map((topic) => topic.legendTopic), - }; -} - -function aggregateTopics( - elements: readonly TopicTimelineElement[], -): Map { - const aggregated = new Map(); - - for (const element of elements) { - for (const topic of element.primary_topics ?? []) { - if (!topic.name) { - continue; - } - - const key = topic.id ?? topic.name; - const existing = aggregated.get(key); - - if (existing) { - existing.count += topic.count; - continue; - } - - aggregated.set(key, { - name: topic.name, - count: topic.count, - legendTopic: toLegendTopic(topic), - }); - } - } - - return aggregated; -} - -function buildIntensityScale( - topics: readonly AggregatedTopic[], -): (count: number) => number { - const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0))); - const minimumWeight = Math.min(...weights); - const maximumWeight = Math.max(...weights); - - if (maximumWeight === minimumWeight) { - return () => 0.5; - } - - return (count) => - (Math.sqrt(Math.max(count, 0)) - minimumWeight) / - (maximumWeight - minimumWeight); -} - -function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic { - return { - id: topic.id, - name: topic.name, - field_id: topic.field_id, - field_name: topic.field_name, - field_description: topic.field_description, - domain_id: topic.domain_id, - domain_name: topic.domain_name, - domain_description: topic.domain_description, - subfield_id: topic.subfield_id, - subfield_name: topic.subfield_name, - subfield_description: topic.subfield_description, - }; -} - -function isWithinYearRange( - year: number | undefined, - startYear: number | undefined, - endYear: number | undefined, -): boolean { - if (startYear !== undefined && (year === undefined || year < startYear)) { - return false; - } - - if (endYear !== undefined && (year === undefined || year > endYear)) { - return false; - } - - return true; -} - -function centreWords(words: WordCloudWord[]): WordCloudWord[] { - const centred: WordCloudWord[] = []; - - words.forEach((word, index) => { - if (index % 2 === 0) { - centred.push(word); - return; - } - - centred.unshift(word); - }); - - return centred; -} - -function stripOpenAlexId(id: string | null | undefined): string { - return (id ?? '').replace('https://openalex.org/', ''); -} - -@Component({ - selector: 'app-research-wordcloud', - standalone: true, - imports: [ComponentTooltipDirective], - templateUrl: './research-wordcloud.component.html', - styleUrl: './research-wordcloud.component.scss', -}) -export class ResearchWordcloudComponent { - readonly AppTopicTooltipComponent = AppTopicTooltipComponent; - - @Input() set words(value: WordCloudWord[]) { - this._words = value; - this.rebuildTooltipInputs(); - } - get words(): WordCloudWord[] { - return this._words; - } - - @Input() set personPublicationsLink(value: unknown[] | null) { - this._personPublicationsLink = value; - this.rebuildTooltipInputs(); - } - - @Input() set personName(value: string) { - this._personName = value; - this.rebuildTooltipInputs(); - } - - @Input() set selectedYears(value: number[]) { - this._selectedYears = normalizeSelectedYears(value); - this.rebuildTooltipInputs(); - } - - @Input() loading = false; - @Input() loadFailed = false; - @Input() activeFieldIds: ReadonlySet = new Set(); - @Input() activeSubfieldIds: ReadonlySet = new Set(); - - @Output() wordSelect = new EventEmitter(); - - private _words: WordCloudWord[] = []; - private _personPublicationsLink: unknown[] | null = null; - private _personName = ''; - private _selectedYears: number[] = []; - private tooltipInputsByTopic = new Map(); - - selectWord(word: WordCloudWord): void { - if (!word.topicId) { - return; - } - - this.wordSelect.emit(word); - } - - isWordActiveByLegend(word: WordCloudWord): boolean { - return ( - this.activeFieldIds.has(word.fieldLegendId) || - (word.subfieldLegendId.length > 0 && - this.activeSubfieldIds.has(word.subfieldLegendId)) - ); - } - - tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null { - return this.tooltipInputsByTopic.get(word.topicId) ?? null; - } - - wordAriaLabel(word: WordCloudWord): string { - return `${this.publicationsLabel()} zum Thema ${word.name}${this.yearRangeSuffix()}`; - } - - private publicationsLabel(): string { - return this._personName - ? `Publikationen von ${this._personName}` - : 'Publikationen dieser Person'; - } - - private yearRangeSuffix(): string { - return this._selectedYears.length > 0 - ? ` ${formatYearRange(this._selectedYears)}` - : ''; - } - - private rebuildTooltipInputs(): void { - const label = `${this.publicationsLabel()}${this.yearRangeSuffix()}`; - const link = this._personPublicationsLink; - - this.tooltipInputsByTopic = new Map( - this._words - .filter((word) => word.topicId) - .map((word) => [ - word.topicId, - { - topicId: word.rawTopicId, - secondaryActionLabel: link ? label : null, - secondaryActionLink: link, - secondaryActionQueryParams: { - [workQueryParamKeys.page]: 0, - ...(this._selectedYears.length > 0 - ? { [workQueryParamKeys.years]: this._selectedYears } - : {}), - [workQueryParamKeys.topicId]: word.topicId, - }, - }, - ]), - ); - } -} diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index e1a23acf..f44532d0 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -22,16 +22,22 @@ (yearSelect)="onTimelineYearSelect($event)" (loadEarlierYears)="onTimelineLoadEarlierYears()" (legendSelectionChange)="onLegendSelectionChange($event)"> - + loadingMessage="Forschungsthemen werden geladen ..." + loadFailedMessage="Forschungsthemen konnten nicht geladen werden." + emptyTitle="Keine Forschungsthemen gefunden." + emptyMessage="" + [interactive]="true" + chartAriaLabel="Wordcloud der Forschungsthemen" + [isWordActive]="isWordActiveByLegend" + [wordAriaLabel]="wordCloudAriaLabel" + [wordTooltip]="wordCloudTooltip" + (wordClick)="onWordClick($event)" /> diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index c049f600..d90eaf8a 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -14,20 +14,33 @@ import { } from './components/research-timeline/research-timeline.component'; import { buildResearchWordcloud, - ResearchWordcloudComponent, WordCloudWord, -} from './components/research-wordcloud/research-wordcloud.component'; +} from './research-wordcloud.utils'; import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { TopicLegendSelectionState, TopicLegendTopic, } from '../../resolvers/utils/topic-legend'; import { PersonDataResolved } from '../../resolvers/person.resolver'; +import { formatYearRange } from '../../resolvers/utils/year-range'; +import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component'; +import { + KeywordWordcloudComponent, + WordCloudTooltipConfig, + WordCloudWordData, +} from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component'; + +type WordTooltipInputs = { + topicId: string; + secondaryActionLabel: string | null; + secondaryActionLink: unknown[] | null; + secondaryActionQueryParams: Record; +}; @Component({ selector: 'app-person-overview', standalone: true, - imports: [ResearchTimelineComponent, ResearchWordcloudComponent], + imports: [ResearchTimelineComponent, KeywordWordcloudComponent], templateUrl: './person-overview.component.html', styleUrl: './person-overview.component.scss', }) @@ -73,6 +86,27 @@ export class PersonOverviewComponent implements OnInit { personName = ''; personPublicationsLink: unknown[] | null = null; + readonly wordCloudTooltip: WordCloudTooltipConfig = { + component: AppTopicTooltipComponent, + inputs: (word) => this.tooltipInputsFor(word as WordCloudWord), + disabled: (word) => !(word as WordCloudWord).rawTopicId, + maxWidth: '500px', + }; + + readonly isWordActiveByLegend = (word: WordCloudWordData): boolean => { + const topicWord = word as WordCloudWord; + return ( + this.activeLegendFieldIds.has(topicWord.fieldLegendId) || + (topicWord.subfieldLegendId.length > 0 && + this.activeLegendSubfieldIds.has(topicWord.subfieldLegendId)) + ); + }; + + readonly wordCloudAriaLabel = (word: WordCloudWordData): string => { + const topicWord = word as WordCloudWord; + return `${this.publicationsLabel()} zum Thema ${topicWord.name}${this.yearRangeSuffix()}`; + }; + ngOnInit(): void { combineLatest(this.route.pathFromRoot.map((route) => route.paramMap)) .pipe( @@ -222,8 +256,9 @@ export class PersonOverviewComponent implements OnInit { this.loadCompleteTopicTimeline(this.currentAuthorId); } - onWordClick(word: WordCloudWord): void { - if (!word.topicId) return; + onWordClick(word: WordCloudWordData): void { + const topicWord = word as WordCloudWord; + if (!topicWord.topicId) return; void this.router.navigate(['../publications'], { relativeTo: this.route, queryParams: { @@ -231,7 +266,7 @@ export class PersonOverviewComponent implements OnInit { ...(this.wordCloudYears.length > 0 ? { [workQueryParamKeys.years]: this.wordCloudYears } : {}), - [workQueryParamKeys.topicId]: word.topicId, + [workQueryParamKeys.topicId]: topicWord.topicId, }, }); } @@ -241,6 +276,39 @@ export class PersonOverviewComponent implements OnInit { this.activeLegendSubfieldIds = selection.subfieldIds; } + private tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null { + if (!word.topicId) return null; + + const link = this.personPublicationsLink; + + return { + topicId: word.rawTopicId, + secondaryActionLabel: link + ? `${this.publicationsLabel()}${this.yearRangeSuffix()}` + : null, + secondaryActionLink: link, + secondaryActionQueryParams: { + [workQueryParamKeys.page]: 0, + ...(this.wordCloudYears.length > 0 + ? { [workQueryParamKeys.years]: this.wordCloudYears } + : {}), + [workQueryParamKeys.topicId]: word.topicId, + }, + }; + } + + private publicationsLabel(): string { + return this.personName + ? `Publikationen von ${this.personName}` + : 'Publikationen dieser Person'; + } + + private yearRangeSuffix(): string { + return this.wordCloudYears.length > 0 + ? ` ${formatYearRange(this.wordCloudYears)}` + : ''; + } + private findAuthorId(paramMaps: readonly ParamMap[]): string { return ( paramMaps From 5153e5876dc96ad70b8815fe1f3db869a031a434 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 21:02:39 +0100 Subject: [PATCH 04/36] adjusted tooltips for better explanability --- webapp/src/app/modules/accounts/accounts.component.html | 2 +- .../modules/person-network/person-network.component.html | 2 +- .../research-timeline/research-timeline.component.html | 5 ++++- .../src/app/shared/ui/file-upload/file-upload.component.ts | 2 +- .../ui/query-param-input/query-param-input.component.html | 7 ++++++- .../ui/searchable-select/searchable-select.component.html | 2 +- webapp/src/index.html | 4 ++-- 7 files changed, 16 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 62bd3956..3173120d 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -69,7 +69,7 @@ @@ -44,6 +45,7 @@ @@ -51,6 +53,7 @@ diff --git a/webapp/src/app/shared/ui/file-upload/file-upload.component.ts b/webapp/src/app/shared/ui/file-upload/file-upload.component.ts index e9e5041e..d045c7fa 100644 --- a/webapp/src/app/shared/ui/file-upload/file-upload.component.ts +++ b/webapp/src/app/shared/ui/file-upload/file-upload.component.ts @@ -214,7 +214,7 @@ export class FileUploadComponent implements OnInit, OnDestroy { if (file) { this.files = this.files.filter((f) => f.id !== id); this.emitFilesChange(); - this.showError('Upload cancelled'); + this.showError('Upload abgebrochen'); } } diff --git a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html index 6ffb5b7d..66e7a2cf 100644 --- a/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html +++ b/webapp/src/app/shared/ui/query-param-input/query-param-input.component.html @@ -7,7 +7,12 @@ (debouncedValueChange)="this._handleValueChange($event)" [ngModel]="this._urlValue()" /> {{ SEARCH_ICON }} - diff --git a/webapp/src/app/shared/ui/searchable-select/searchable-select.component.html b/webapp/src/app/shared/ui/searchable-select/searchable-select.component.html index 5cfefc04..230537bc 100644 --- a/webapp/src/app/shared/ui/searchable-select/searchable-select.component.html +++ b/webapp/src/app/shared/ui/searchable-select/searchable-select.component.html @@ -22,7 +22,7 @@ diff --git a/webapp/src/index.html b/webapp/src/index.html index cbbce822..8d67ed62 100644 --- a/webapp/src/index.html +++ b/webapp/src/index.html @@ -1,8 +1,8 @@ - + - INSE App + AIIS – Innovation Scouting From 0775f3efc76374c7afea6bb9cb55c1921b957469 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 21:17:36 +0100 Subject: [PATCH 05/36] fixed hierarchy chart render warning --- .../hierarchy-chart.component.html | 14 +-- .../hierarchy-chart.component.scss | 10 +- .../hierarchy-chart.component.ts | 109 ++++++++++++++++-- .../hierarchy/hierarchy.component.html | 7 +- 4 files changed, 120 insertions(+), 20 deletions(-) diff --git a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.html b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.html index cebd0d75..6489776a 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.html +++ b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.html @@ -88,13 +88,13 @@ -
+ @if (expanded()) { +
+ }
} diff --git a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss index 5545b2b0..9d201698 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss +++ b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss @@ -66,11 +66,14 @@ .uh-row { display: flex; - flex-grow: 1; + flex-grow: 0; + flex-shrink: 0; + flex-basis: auto; flex-direction: row; flex-wrap: nowrap; align-items: stretch; gap: var(--uh-gap); + height: var(--uh-row-height); overflow-x: auto; overflow-y: hidden; padding-bottom: 2px; @@ -132,6 +135,7 @@ flex: 1 1 100%; display: flex; flex-direction: column; + min-height: 0; overflow: hidden; } @@ -167,13 +171,13 @@ } .uh-chart-viewport { + flex: 1 1 auto; + min-height: 0; overflow-x: hidden; overflow-y: auto; - height: 100%; padding: 0 !important; } .uh-chart { - height: 100% !important; width: 100%; } diff --git a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts index 5357b175..01ae7615 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts +++ b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts @@ -1,6 +1,7 @@ import { Component, DestroyRef, + ElementRef, OnInit, signal, inject, @@ -10,10 +11,10 @@ import { EventEmitter, effect, untracked, + viewChild, } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { Router, ActivatedRoute } from '@angular/router'; -import { NgxEchartsDirective } from 'ngx-echarts'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatCardModule } from '@angular/material/card'; @@ -21,7 +22,8 @@ import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatChipsModule } from '@angular/material/chips'; import { MatTooltipModule } from '@angular/material/tooltip'; -import type { EChartsOption } from 'echarts'; +import type { ECharts, EChartsOption } from 'echarts'; +import { PassiveWheelDirective } from '../../../directives/passive-wheel.directive'; import { CredentialService } from '../../../shared/services/credential.service'; import { ChartThemeService } from '../../../shared/services/chart-theme.service'; import { HierarchyEditDialogComponent } from './hierarchy-edit-dialog/hierarchy-edit-dialog.component'; @@ -64,7 +66,7 @@ const MIN_TREE_HEIGHT = 200; selector: 'app-hierarchy-chart', standalone: true, imports: [ - NgxEchartsDirective, + PassiveWheelDirective, MatProgressSpinnerModule, MatToolbarModule, MatCardModule, @@ -92,10 +94,19 @@ export class HierarchyChartComponent implements OnInit { private readonly credentialService = inject(CredentialService); private readonly orgminerService = inject(OrgminerService); private readonly chartTheme = inject(ChartThemeService); + /** Reference of the theme colors used for the current chart options. */ + private lastChartTheme = this.chartTheme.colors(); readonly loading = signal(true); readonly lang = signal<'de' | 'en'>('de'); readonly levels = signal([]); + private readonly chartHost = + viewChild>('chartHost'); + private chart: ECharts | null = null; + private chartHostElement: HTMLDivElement | null = null; + private chartResizeObserver: ResizeObserver | null = null; + private chartInitToken = 0; + private readonly snackBar = inject(MatSnackBar); private readonly idMap = new Map(); universityRoot: RawNode | null = null; @@ -109,6 +120,8 @@ export class HierarchyChartComponent implements OnInit { private isOwnNavigation = false; hierarchyData = input.required(); + /** False while the parent expansion panel is collapsed. */ + readonly expanded = input(true); pendingSuggestion = input(null); can_edit = computed(() => this.hierarchyData().can_edit ?? false); can_suggest = computed(() => this.hierarchyData().can_suggest ?? false); @@ -133,7 +146,10 @@ export class HierarchyChartComponent implements OnInit { }); }); effect(() => { - this.chartTheme.colors(); + const colors = this.chartTheme.colors(); + if (colors === this.lastChartTheme) return; + this.lastChartTheme = colors; + untracked(() => { if (!this.universityRoot) return; this.levels.update((levels) => @@ -148,6 +164,15 @@ export class HierarchyChartComponent implements OnInit { const suggestion = this.pendingSuggestion(); untracked(() => this.loadPendingSuggestionIntoEditor(suggestion)); }); + effect(() => { + const levels = this.levels(); + const expanded = this.expanded(); + const host = this.chartHost()?.nativeElement ?? null; + const level = expanded ? (levels[levels.length - 1] ?? null) : null; + untracked(() => this.syncChart(host, level)); + }); + + this.destroyRef.onDestroy(() => this.disposeChart()); } ngOnInit(): void { @@ -539,6 +564,70 @@ export class HierarchyChartComponent implements OnInit { }; } + /* ------------------------------ chart instance ---------------------------- */ + + /** + * Owns the ECharts instance directly instead of delegating to ngx-echarts. + * This avoids two async `init()` calls racing when the options change while + * the chart is still being created (the "already initialized" warning). + */ + private syncChart( + host: HTMLDivElement | null, + level: TreeLevel | null, + ): void { + if (!host || !level) { + this.disposeChart(); + return; + } + + if (this.chart && this.chartHostElement === host) { + this.chart.setOption(level.options, true); + return; + } + + this.disposeChart(); + this.chartHostElement = host; + const token = ++this.chartInitToken; + + requestAnimationFrame(() => { + if (token !== this.chartInitToken || this.chartHostElement !== host) { + return; + } + + void import('echarts').then(({ init }) => { + if (token !== this.chartInitToken || this.chartHostElement !== host) { + return; + } + + const chart = init(host); + this.chart = chart; + chart.setOption(level.options, true); + chart.on('click', (params) => this.onChartNodeClick(params)); + this.observeChartSize(host); + }); + }); + } + + private onChartNodeClick(params: unknown): void { + const levelIndex = Math.max(0, this.levels().length - 1); + this.onNodeClick(params, levelIndex); + } + + private observeChartSize(host: HTMLDivElement): void { + this.chartResizeObserver?.disconnect(); + this.chartResizeObserver = new ResizeObserver(() => this.chart?.resize()); + this.chartResizeObserver.observe(host); + } + + private disposeChart(): void { + this.chartInitToken++; + this.chartResizeObserver?.disconnect(); + this.chartResizeObserver = null; + this.chart?.dispose(); + this.chart = null; + this.chartHostElement = null; + } + /* --------------------------------- saving -------------------------------- */ /** @@ -551,7 +640,7 @@ export class HierarchyChartComponent implements OnInit { this.orgminerService.saveHierarchy(children as any).subscribe({ next: (response) => { - this.snackBar.open('Hierarchy saved successfully', 'Close', { + this.snackBar.open('Hierarchie gespeichert.', 'OK', { duration: 3000, }); @@ -573,9 +662,13 @@ export class HierarchyChartComponent implements OnInit { } }, error: (error) => { - this.snackBar.open('Error saving hierarchy', 'Close', { - duration: 3000, - }); + this.snackBar.open( + 'Hierarchie konnte nicht gespeichert werden.', + 'OK', + { + duration: 4000, + }, + ); console.error('[HierarchyChart] error saving hierarchy:', error); this.hierarchySaved.set(false); }, diff --git a/webapp/src/app/modules/hierarchy/hierarchy.component.html b/webapp/src/app/modules/hierarchy/hierarchy.component.html index d184d1e0..39bc717c 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy.component.html +++ b/webapp/src/app/modules/hierarchy/hierarchy.component.html @@ -25,9 +25,12 @@ suggestion.status === 'new' + ) ?? null + " (analyzeOrgEvent)="analyzeOrg($event)" (suggestionSaved)="reloadSuggestions()" /> From 8c45c29fc63ba7dfd119397a6bab503fe61a0fab Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 21:55:44 +0100 Subject: [PATCH 06/36] standartized resolving state of components --- .../institutions/institutions.component.html | 1 + .../institutions/institutions.component.ts | 8 ++- .../modules/projects/projects.component.html | 1 + .../modules/projects/projects.component.ts | 8 ++- .../publications/publications.component.html | 1 + .../publications/publications.component.ts | 6 ++ .../app/modules/topics/topics.component.html | 1 + .../app/modules/topics/topics.component.ts | 14 +++-- .../ui/app-layout/app-layout.component.html | 16 +++-- .../ui/app-layout/app-layout.component.ts | 59 +++++++++++++++++-- 10 files changed, 98 insertions(+), 17 deletions(-) diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index 3f9c1230..31f42562 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -4,6 +4,7 @@ subtitle="Suche nach Hochschulen, Forschungszentren und weiteren Einrichtungen."> (); + private readonly resolverState = inject(ResolverStateService); + readonly loading = computed(() => + this.resolverState.isResolvingInside('/institutions'), + ); + observers: FilterObserver[] = [ { id: 'name', diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 8e1f2bcc..5b1ebd87 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -4,6 +4,7 @@ subtitle="Durchsuche geförderte Projekte aus DFG-, EU- und Bundesdatenquellen."> (); + private readonly resolverState = inject(ResolverStateService); + readonly loading = computed(() => + this.resolverState.isResolvingInside('/projects'), + ); + page = computed(() => ({ page: this.fundingProjectPage().page || 0, size: this.fundingProjectPage().size || 10, diff --git a/webapp/src/app/modules/publications/publications.component.html b/webapp/src/app/modules/publications/publications.component.html index b84d5d21..1484323e 100644 --- a/webapp/src/app/modules/publications/publications.component.html +++ b/webapp/src/app/modules/publications/publications.component.html @@ -4,6 +4,7 @@ subtitle="Durchsuche wissenschaftliche Publikationen nach Titel, Autor:innen, Themen oder Institutionen."> + this.resolverState.isResolvingInside('/publications'), + ); workPage = input.required(); selectedAuthorsPage = input.required(); diff --git a/webapp/src/app/modules/topics/topics.component.html b/webapp/src/app/modules/topics/topics.component.html index c22a5496..61581c4b 100644 --- a/webapp/src/app/modules/topics/topics.component.html +++ b/webapp/src/app/modules/topics/topics.component.html @@ -4,6 +4,7 @@ subtitle="Entdecke Forschungsfelder nach Namen, Publikationen und Zitierungen."> (); + private readonly resolverState = inject(ResolverStateService); + readonly loading = computed(() => + this.resolverState.isResolvingInside('/topics'), + ); + observers: FilterObserver[] = [ { id: 'query', diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 01566c95..b41ef3df 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -38,10 +38,16 @@ {{ MENU_ICON }} } - + @if (showBack()) { + + }
@@ -50,7 +56,7 @@ } -
+
@if (resolverState.isResolvingFromOutside('/persons')) { void; + private readonly destroyRef = inject(DestroyRef); + private readonly backNavigation = inject(BackNavigationService); + private readonly scrollService = inject(RouteScrollService); + // Instantiated for its router subscription; keeps document.title in sync. + private readonly pageTitle = inject(PageTitleService); + private readonly contentScroller = + viewChild>('contentScroller'); + private readonly currentPath = signal('/'); + + readonly showBack = computed( + () => !this.backNavigation.isRoot(this.currentPath()), + ); + private readonly sidebarCollapsedStorageKey = 'inse.sidebar.collapsed'; sideNavOpen = false; sideNavCollapsed = this.readSidebarCollapsedState(); @@ -79,11 +103,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy { constructor( public credentialService: CredentialService, public router: Router, - private readonly location: Location, public changeDetector: ChangeDetectorRef, media: MediaMatcher, ) { this.mediaQuery = media.matchMedia('(max-width: 600px)'); + this.currentPath.set(this.pathOf(this.router.url)); this.mediaQueryListener = () => { this.sideNavOpen = !this.mediaQuery.matches; @@ -93,6 +117,29 @@ export class AppLayoutComponent implements OnInit, OnDestroy { changeDetector.detectChanges(); }; + + this.router.events + .pipe( + filter( + (event): event is NavigationEnd => event instanceof NavigationEnd, + ), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((event) => { + this.currentPath.set(this.pathOf(event.urlAfterRedirects)); + + // On phones the drawer is an overlay; keep it from covering the + // freshly opened page. + if (this.mediaQuery.matches && this.sideNavOpen) { + this.sideNavOpen = false; + this.drawer?.close(); + } + }); + + afterNextRender(() => { + const scroller = this.contentScroller()?.nativeElement; + if (scroller) this.scrollService.attach(scroller); + }); } toggle() { @@ -147,6 +194,10 @@ export class AppLayoutComponent implements OnInit, OnDestroy { } navigateBack() { - this.location.back(); + this.backNavigation.back(); + } + + private pathOf(url: string): string { + return url.split('?')[0].split('#')[0] || '/'; } } From e984372259cf53ecd2d33ad3e195bdf40567440c Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 21:58:55 +0100 Subject: [PATCH 07/36] =?UTF-8?q?made=20the=20"Zur=C3=BCck"=20button=20vis?= =?UTF-8?q?ible=20only=20within=20components?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app-searchbar.component.html | 25 +++-- .../app-searchbar/app-searchbar.component.ts | 97 ++++++++++++------- 2 files changed, 79 insertions(+), 43 deletions(-) diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html index 3f294de6..c5fd300c 100644 --- a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html @@ -3,24 +3,31 @@ - + @for (person of filteredPersons.results; track person.id) { - + {{ PERSON_ICON }} {{ person.display_name }} } + + @if (suggestionsLoading()) { + Suche läuft … + } @else if ( + searchControl.value && + searchControl.value.length >= 2 && + !filteredPersons.results?.length + ) { + Keine Personen gefunden + } diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts index bdd14b37..c3b7f791 100644 --- a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts @@ -1,4 +1,10 @@ -import { Component, inject, ViewChild, DestroyRef } from '@angular/core'; +import { + Component, + inject, + ViewChild, + DestroyRef, + signal, +} from '@angular/core'; import { MatIcon } from '@angular/material/icon'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; @@ -11,9 +17,11 @@ import { MatInputModule } from '@angular/material/input'; import { MatFormFieldModule } from '@angular/material/form-field'; import { switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { of } from 'rxjs'; +import { finalize, of } from 'rxjs'; import { PersonsService, AuthorsListResponse } from '../../../api'; import { PERSON_ICON, SEARCH_ICON } from '../icons'; +import { CredentialService } from '../../services/credential.service'; +import { activeInstitutionPersonListQueryParams } from '../../person-list-query-params'; @Component({ selector: 'app-searchbar', @@ -48,12 +56,13 @@ export class AppSearchbarComponent { private readonly router = inject(Router); private readonly route = inject(ActivatedRoute); private readonly personService = inject(PersonsService); - constructor() { - const route = inject(ActivatedRoute); - const router = inject(Router); + private readonly credentialService = inject(CredentialService); + readonly suggestionsLoading = signal(false); + + constructor() { // Sync searchControl from query param on every URL change - route.queryParams + this.route.queryParams .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((params) => { const query = params['query'] ?? ''; @@ -67,13 +76,17 @@ export class AppSearchbarComponent { .pipe( debounceTime(300), distinctUntilChanged(), - switchMap((v) => { - const value = v ?? ''; - if (value.length < 2) return of(this.emptyPersons()); - return this.personService.searchPersonsAutocomplete( - value, - 'display_name', - ); + switchMap((value) => { + const term = (value ?? '').trim(); + if (term.length < 2) { + this.suggestionsLoading.set(false); + return of(this.emptyPersons()); + } + + this.suggestionsLoading.set(true); + return this.personService + .searchPersonsAutocomplete(term, 'display_name') + .pipe(finalize(() => this.suggestionsLoading.set(false))); }), takeUntilDestroyed(this.destroyRef), ) @@ -83,22 +96,23 @@ export class AppSearchbarComponent { } selectPerson(personName: string | undefined | null): void { - if (personName) { - this.searchControl.setValue(personName); - this.startSearch(); - } + if (!personName) return; + + this.searchControl.setValue(personName, { emitEvent: false }); + this.startSearch(); } - onKeydownTab(event: KeyboardEvent): void { + onEnter(event: Event): void { + if (event.defaultPrevented) return; + + // Let Material select the highlighted option; its optionSelected handler + // performs the navigation. Only free-text Enter starts a search here. + if (this.autocomplete?.isOpen && this.autocompleteTrigger?.activeOption) { + return; + } + event.preventDefault(); - const first = this.filteredPersons?.results?.[0]; - if (first?.display_name) { - this.searchControl.setValue(first.display_name); - } - } - - onEnter(): void { - this.autocompleteTrigger.closePanel(); + this.autocompleteTrigger?.closePanel(); this.startSearch(); } @@ -107,16 +121,31 @@ export class AppSearchbarComponent { } startSearch(): void { - const search = this.searchControl.value ?? ''; + const search = (this.searchControl.value ?? '').trim(); + const currentPath = this.router.url.split('?')[0]; + const onPersonList = currentPath.startsWith('/persons'); - this.router.navigate( - this.router.url.startsWith('/persons') ? [] : ['/persons'], - { - relativeTo: this.route, - queryParams: { query: search || null, page: 1 }, - queryParamsHandling: 'merge', + // On the person list, keep the active filters. Anywhere else, start from + // the account's institution defaults and never leak unrelated params + // (sort keys, titles, topics from other sections). + const baseParams: Record = onPersonList + ? { ...this.router.parseUrl(this.router.url).queryParams } + : activeInstitutionPersonListQueryParams( + this.credentialService.effectiveInstitutionId(), + this.credentialService.organizationName(), + ); + + delete baseParams['query']; + delete baseParams['page']; + + void this.router.navigate(['/persons'], { + queryParams: { + ...baseParams, + query: search || null, + page: 1, + pageSize: baseParams['pageSize'] ?? 10, }, - ); + }); } private emptyPersons(): AuthorsListResponse { From 8b374681c2d9f661d29b8ec7f2fd774fc08aa276 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 22:25:42 +0100 Subject: [PATCH 08/36] added page title service for displaying page title --- .../app/shared/services/page-title.service.ts | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 webapp/src/app/shared/services/page-title.service.ts diff --git a/webapp/src/app/shared/services/page-title.service.ts b/webapp/src/app/shared/services/page-title.service.ts new file mode 100644 index 00000000..6e678034 --- /dev/null +++ b/webapp/src/app/shared/services/page-title.service.ts @@ -0,0 +1,71 @@ +import { Injectable, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { NavigationEnd, Router } from '@angular/router'; +import { filter } from 'rxjs'; + +const APP_NAME = 'AIIS'; + +const TITLES: ReadonlyArray<{ prefix: string; title: string }> = [ + { prefix: '/person/', title: 'Person' }, + { prefix: '/persons', title: 'Personen' }, + { prefix: '/publication/', title: 'Publikation' }, + { prefix: '/publications', title: 'Publikationen' }, + { prefix: '/patent/', title: 'Patent' }, + { prefix: '/patents', title: 'Patente' }, + { prefix: '/institution/', title: 'Institution' }, + { prefix: '/institutions', title: 'Institutionen' }, + { prefix: '/topic/', title: 'Thema' }, + { prefix: '/topics', title: 'Themen' }, + { prefix: '/news/', title: 'Nachricht' }, + { prefix: '/news', title: 'Nachrichten' }, + { prefix: '/projects/', title: 'Projekt' }, + { prefix: '/projects', title: 'Projekte' }, + { prefix: '/founders/', title: 'Multiplikator' }, + { prefix: '/founders', title: 'Gründungspotenzial' }, + { prefix: '/multipliers', title: 'Multiplikatoren' }, + { prefix: '/compare', title: 'Autorenvergleich' }, + { prefix: '/bookmarks', title: 'Bookmarks' }, + { prefix: '/keywords/', title: 'Keywords' }, + { prefix: '/keywords', title: 'Keywords' }, + { prefix: '/hierarchy', title: 'Hierarchie' }, + { prefix: '/account', title: 'Mein Konto' }, + { prefix: '/accounts', title: 'Accounts' }, + { prefix: '/organizations', title: 'Organisationen' }, + { prefix: '/jobs', title: 'Jobs' }, + { prefix: '/dashboard', title: 'Dashboard' }, + { prefix: '/login', title: 'Anmelden' }, + { prefix: '/forgot-password', title: 'Passwort vergessen' }, + { prefix: '/reset-password', title: 'Passwort zurücksetzen' }, + { prefix: '/error', title: 'Fehler' }, + { prefix: '/icons', title: 'Icons' }, +]; + +@Injectable({ providedIn: 'root' }) +export class PageTitleService { + private readonly router = inject(Router); + + constructor() { + this.router.events + .pipe( + filter( + (event): event is NavigationEnd => event instanceof NavigationEnd, + ), + takeUntilDestroyed(), + ) + .subscribe((event) => this.update(event.urlAfterRedirects)); + + this.update(this.router.url); + } + + private update(url: string): void { + document.title = `${this.titleFor(url)} · ${APP_NAME}`; + } + + private titleFor(url: string): string { + const path = url.split('?')[0].split('#')[0] || '/'; + if (path === '/' || path === '') return 'Start'; + + const match = TITLES.find(({ prefix }) => path.startsWith(prefix)); + return match?.title ?? 'Übersicht'; + } +} From 30eea4aa2276ac6eb20cf9c63884e296c3980460 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 22:35:38 +0100 Subject: [PATCH 09/36] prevented hierarchy to reresolbe on node click --- webapp/src/app/app.routes.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 56f2575e..2c8ec491 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -284,7 +284,26 @@ export const routes: Routes = [ hierarchyData: hierarchyResolver, suggestions: suggestionResolver, }, - runGuardsAndResolvers: 'always', + // Chart navigation only changes `path`/`lang`; do not refetch the whole + // hierarchy on every node click. An explicit same-URL reload (used by + // `reloadSuggestions`) still re-runs the resolvers. + runGuardsAndResolvers: (from, to) => { + if (from.routeConfig !== to.routeConfig) return true; + + const keys = new Set([ + ...from.queryParamMap.keys, + ...to.queryParamMap.keys, + ]); + const changedKeys = [...keys].filter( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + + // No query change at all -> explicit same-URL reload. + if (changedKeys.length === 0) return true; + + // Only the chart's own state changed -> keep the loaded hierarchy. + return changedKeys.some((key) => key !== 'path' && key !== 'lang'); + }, loadComponent: () => import('./modules/hierarchy/hierarchy.component').then( (mod) => mod.HierarchyComponent, From 83e0bc3e01f6f56fc4b66a856d4a3570a594d8a1 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 22:43:23 +0100 Subject: [PATCH 10/36] minor ui fixes --- .../ui/card-search/card-search.component.html | 23 +++++++++++-------- .../shared/ui/loading/loading.component.scss | 6 +++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/webapp/src/app/shared/ui/card-search/card-search.component.html b/webapp/src/app/shared/ui/card-search/card-search.component.html index d55fc7ab..72c99f8b 100644 --- a/webapp/src/app/shared/ui/card-search/card-search.component.html +++ b/webapp/src/app/shared/ui/card-search/card-search.component.html @@ -30,9 +30,12 @@ @let pageValue = page(); -
+
@if (loading()) { -
+
} @@ -45,7 +48,7 @@ }
- } @else { + } @else if (!loading()) { @if (this.noResultsTmp()) { } @else { @@ -55,12 +58,14 @@ } }
- @if (pageValue.elements && pageValue.elements.length > 0) { + @if (!loading() && pageValue.elements && pageValue.elements.length > 0) { } - + @if (!loading() && page().total > 0) { + + }
diff --git a/webapp/src/app/shared/ui/loading/loading.component.scss b/webapp/src/app/shared/ui/loading/loading.component.scss index 5a95614a..db9f90dd 100644 --- a/webapp/src/app/shared/ui/loading/loading.component.scss +++ b/webapp/src/app/shared/ui/loading/loading.component.scss @@ -38,3 +38,9 @@ opacity: 0.7; } } + +@media (prefers-reduced-motion: reduce) { + .spinner-icon { + animation: none; + } +} From faa22e0a8f0dd418744ee2ad352ffb17a844190f Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 22:53:07 +0100 Subject: [PATCH 11/36] added skeleton loading to person-card's university display --- webapp/src/app/modules/person-card/person-card.component.html | 1 + 1 file changed, 1 insertion(+) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 59970d53..cf8478f8 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -53,6 +53,7 @@
Date: Thu, 12 Nov 2026 23:01:38 +0100 Subject: [PATCH 12/36] standartized "goBack" button --- .../researcher-network.component.html | 8 +- .../researcher-network.component.scss | 20 --- .../news-detail/news-detail.component.html | 9 -- .../news-detail/news-detail.component.scss | 23 ---- .../news-detail/news-detail.component.ts | 6 - .../patent-detail.component.html | 9 -- .../patent-detail.component.scss | 21 ---- .../patent-detail/patent-detail.component.ts | 8 -- .../modules/patents/patents.component.html | 11 -- .../app/modules/patents/patents.component.ts | 13 ++ .../bund-details/bund-details.component.ts | 3 - .../dfg-details/dfg-details.component.ts | 4 - .../publication-detail.component.html | 9 -- .../publication-detail.component.scss | 21 ---- .../publication-detail.component.ts | 16 +-- .../services/back-navigation.service.ts | 114 ++++++++++++++++++ .../ui/app-layout/app-layout.component.ts | 4 +- 17 files changed, 141 insertions(+), 158 deletions(-) create mode 100644 webapp/src/app/shared/services/back-navigation.service.ts diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html index 8e02a0c3..1743f8ab 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html @@ -4,10 +4,6 @@ [subtitle]="unavailable()?.body ?? null" [titleTooltip]="unavailable() ? null : pageTooltip">
- - {{ ARROW_BACK_ICON }} - Zurück zur Multiplikatoren-Übersicht - @if (!unavailable()) {
@if (careerBucket()) { @@ -147,8 +143,8 @@

- Rang 0–100 im Vergleich zu Personen derselben Karrierestufe. - Ab 85 % wird ein Rollen-Badge vergeben. + Rang 0–100 im Vergleich zu Personen derselben Karrierestufe. Ab + 85 % wird ein Rollen-Badge vergeben.

@for (group of metricGroups(); track group.key) {
diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss index 000a86d3..4fb68456 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss @@ -3,26 +3,6 @@ min-width: 0; } -.back-link { - display: inline-flex; - align-items: center; - gap: 4px; - margin-bottom: 6px; - color: var(--sg-text-muted); - font-size: 13px; - text-decoration: none; - - mat-icon { - font-size: 18px; - width: 18px; - height: 18px; - } - - &:hover { - color: var(--sg-blue-highlight); - } -} - .meta-block { margin-top: 8px; } diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 43274825..b7607dea 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -1,14 +1,5 @@
- - @if (loading) {
- - @if (loading) { - @if (showDetail && selectedPatent) { - - } - @if (error) {

Fehler beim Laden der Patente.

} @else if (showDetail && selectedPatent) { diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index 758f23ca..a60446e1 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -24,6 +24,7 @@ import { import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component'; import { HELP_ICON, PATENT_ICON } from '../../shared/ui/icons'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; +import { BackNavigationService } from '../../shared/services/back-navigation.service'; type PatentSource = 'EPO' | 'USPTO'; @@ -69,6 +70,8 @@ export class PatentsComponent { private route = inject(ActivatedRoute); private patentsApi = inject(PatentsService); private destroyRef = inject(DestroyRef); + private backNavigation = inject(BackNavigationService); + private unregisterLocalBack: (() => void) | null = null; patents: PatentEntry[] = []; total = 0; @@ -92,6 +95,8 @@ export class PatentsComponent { readonly expandedClassificationKeys = new Set(); constructor() { + this.destroyRef.onDestroy(() => this.unregisterLocalBack?.()); + this.route.queryParams .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((qp) => { @@ -181,12 +186,20 @@ export class PatentsComponent { } selectPatent(patent: PatentEntry): void { + this.unregisterLocalBack?.(); + this.unregisterLocalBack = this.backNavigation.registerLocalBack(() => + this.closeDetail(), + ); + this.selectedPatent = patent; this.showDetail = true; this.expandedClassificationKeys.clear(); } closeDetail(): void { + this.unregisterLocalBack?.(); + this.unregisterLocalBack = null; + this.showDetail = false; this.selectedPatent = null; this.expandedClassificationKeys.clear(); diff --git a/webapp/src/app/modules/projects/bund-details/bund-details.component.ts b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts index ed0573df..f0e362dd 100644 --- a/webapp/src/app/modules/projects/bund-details/bund-details.component.ts +++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts @@ -172,7 +172,4 @@ export class BundDetailsComponent implements OnInit { return 'var(--sg-text-muted)'; } } - goBack(): void { - window.history.back(); - } } diff --git a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts index 7e66404c..3f1c6271 100644 --- a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts +++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts @@ -279,8 +279,4 @@ export class DfgDetailsComponent implements OnInit { queryParams: { search: institutionName }, }); } - - goBack(): void { - window.history.back(); - } } diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.html b/webapp/src/app/modules/publication-detail/publication-detail.component.html index 5daa523b..0303ab56 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.html +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.html @@ -1,14 +1,5 @@
- - @if (loading) { (); @@ -130,20 +130,22 @@ export class PublicationDetailComponent implements OnInit { readonly institutionsPageSize = 5; returnUrl: string | null = null; - returnLabel = 'Alle Publikationen'; - returnAriaLabel = 'Zurück zu den Publikationen'; ngOnInit(): void { this.loading = true; const navigationState = this.location.getState() as { returnUrl?: string; - returnLabel?: string; } | null; if (navigationState?.returnUrl) { this.returnUrl = navigationState.returnUrl; - this.returnLabel = navigationState.returnLabel ?? 'Zurück'; - this.returnAriaLabel = `Zurück zu ${this.returnLabel}`; + + // The topbar back button should return to the page the user came from, + // not to an unrelated history entry. + const unregister = this.backNavigation.registerLocalBack(() => + this.navigateBack(), + ); + this.destroyRef.onDestroy(unregister); } this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ diff --git a/webapp/src/app/shared/services/back-navigation.service.ts b/webapp/src/app/shared/services/back-navigation.service.ts new file mode 100644 index 00000000..5b3162d9 --- /dev/null +++ b/webapp/src/app/shared/services/back-navigation.service.ts @@ -0,0 +1,114 @@ +import { Location } from '@angular/common'; +import { Injectable, computed, inject, signal } from '@angular/core'; +import { Router } from '@angular/router'; + +type BackHandler = () => void; + +const ROOT_PATHS = new Set([ + '/dashboard', + '/compare', + '/multipliers', + '/founders', + '/bookmarks', + '/persons', + '/keywords', + '/hierarchy', + '/news', + '/account', + '/accounts', + '/organizations', + '/jobs', + '/publications', + '/topics', + '/projects', + '/patents', + '/institutions', + '/login', + '/forgot-password', + '/reset-password', + '/icons', + '/error', +]); + +const FALLBACKS: ReadonlyArray<{ prefix: string; target: string }> = [ + { prefix: '/person/', target: '/persons' }, + { prefix: '/publication/', target: '/publications' }, + { prefix: '/patent/', target: '/patents' }, + { prefix: '/news/', target: '/news' }, + { prefix: '/institution/', target: '/institutions' }, + { prefix: '/topic/', target: '/topics' }, + { prefix: '/projects/', target: '/projects' }, + { prefix: '/founders/', target: '/multipliers' }, + { prefix: '/keywords/', target: '/keywords' }, + { prefix: '/error', target: '/dashboard' }, +]; + +@Injectable({ providedIn: 'root' }) +export class BackNavigationService { + private readonly router = inject(Router); + private readonly location = inject(Location); + + // In-page detail views (e.g. the inline patent detail) own the back action + // while they are open. The topbar button executes the newest handler. + private readonly localHandlers = signal([]); + + readonly hasLocalHandler = computed(() => this.localHandlers().length > 0); + + /** + * Registers a back action for an in-page detail view. Returns an unregister + * function that the component calls when the view closes or is destroyed. + */ + registerLocalBack(handler: BackHandler): () => void { + this.localHandlers.update((handlers) => [...handlers, handler]); + + return () => { + this.localHandlers.update((handlers) => + handlers.filter((candidate) => candidate !== handler), + ); + }; + } + + /** True when this tab has at least one earlier in-app navigation. */ + canGoBack(): boolean { + const state = history.state as { navigationId?: number } | null; + return (state?.navigationId ?? 0) > 1; + } + + /** + * Goes back in history when that is safe, otherwise navigates to the + * section that owns the current detail page. + */ + back(fallback?: string): void { + const handlers = this.localHandlers(); + const localHandler = handlers[handlers.length - 1]; + + if (localHandler) { + localHandler(); + return; + } + + if (this.canGoBack()) { + this.location.back(); + return; + } + + void this.router.navigateByUrl( + fallback ?? this.fallbackFor(this.router.url), + ); + } + + /** Whether the current URL is a top-level section. */ + isRoot(url: string): boolean { + return ROOT_PATHS.has(this.pathOf(url)); + } + + fallbackFor(url: string): string { + const path = this.pathOf(url); + const match = FALLBACKS.find(({ prefix }) => path.startsWith(prefix)); + return match?.target ?? '/dashboard'; + } + + private pathOf(url: string): string { + return url.split('?')[0].split('#')[0] || '/'; + } +} diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 00cfea1d..7f47cb21 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -93,7 +93,9 @@ export class AppLayoutComponent implements OnInit, OnDestroy { private readonly currentPath = signal('/'); readonly showBack = computed( - () => !this.backNavigation.isRoot(this.currentPath()), + () => + this.backNavigation.hasLocalHandler() || + !this.backNavigation.isRoot(this.currentPath()), ); private readonly sidebarCollapsedStorageKey = 'inse.sidebar.collapsed'; From e6e8d192cc5a582cd8eb10c44172ed68829eb1b3 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 12 Nov 2026 23:07:52 +0100 Subject: [PATCH 13/36] fixed bug where the page title was shown as tooltip on mouse hover --- .../ui/page-container/page-container.component.ts | 12 +++++++++++- .../shared/ui/page-header/page-header.component.ts | 11 ++++++++++- .../ui/weights-sliders/weights-sliders.component.ts | 7 +++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/shared/ui/page-container/page-container.component.ts b/webapp/src/app/shared/ui/page-container/page-container.component.ts index 4ff83a16..9110d913 100644 --- a/webapp/src/app/shared/ui/page-container/page-container.component.ts +++ b/webapp/src/app/shared/ui/page-container/page-container.component.ts @@ -1,4 +1,4 @@ -import { Component, input } from '@angular/core'; +import { Component, ElementRef, inject, input } from '@angular/core'; import { PageHeaderComponent } from '../page-header/page-header.component'; /** Shared full-width page frame with a consistent page heading. */ @@ -14,4 +14,14 @@ export class PageContainerComponent { readonly subtitle = input(null); readonly eyebrow = input(null); readonly titleTooltip = input(null); + + constructor() { + // `title` is an input, but a static `title="..."` attribute would also be + // written to the host element. Browsers then show it as a native tooltip + // when hovering anywhere inside the page. Remove the attribute; the input + // value itself is unaffected. + inject>(ElementRef).nativeElement.removeAttribute( + 'title', + ); + } } diff --git a/webapp/src/app/shared/ui/page-header/page-header.component.ts b/webapp/src/app/shared/ui/page-header/page-header.component.ts index 5a700292..73e2afe4 100644 --- a/webapp/src/app/shared/ui/page-header/page-header.component.ts +++ b/webapp/src/app/shared/ui/page-header/page-header.component.ts @@ -1,4 +1,4 @@ -import { Component, input } from '@angular/core'; +import { Component, ElementRef, inject, input } from '@angular/core'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; @@ -20,4 +20,13 @@ export class PageHeaderComponent { readonly eyebrow = input(null); readonly titleTooltip = input(null); readonly level = input<1 | 2 | 3>(1); + + constructor() { + // See PageContainerComponent: a static `title="..."` would stay on the + // host element and trigger the browser's native tooltip for the whole + // section. The input still receives the value. + inject>(ElementRef).nativeElement.removeAttribute( + 'title', + ); + } } diff --git a/webapp/src/app/shared/ui/weights-sliders/weights-sliders.component.ts b/webapp/src/app/shared/ui/weights-sliders/weights-sliders.component.ts index daedb304..6ebbe31b 100644 --- a/webapp/src/app/shared/ui/weights-sliders/weights-sliders.component.ts +++ b/webapp/src/app/shared/ui/weights-sliders/weights-sliders.component.ts @@ -1,6 +1,7 @@ import { Component, DestroyRef, + ElementRef, EventEmitter, Input, OnChanges, @@ -159,6 +160,12 @@ export class WeightsSlidersComponent implements OnInit, OnChanges { private isOwnNavigation = false; constructor() { + // `title` is an input. A static `title="..."` would stay on the host and + // show up as a native tooltip over the whole widget. + inject>(ElementRef).nativeElement.removeAttribute( + 'title', + ); + this.form.valueChanges .pipe(debounceTime(250), takeUntilDestroyed(this.destroyRef)) .subscribe(() => { From 4c39933b8d27ef92d674f88a0a95c93cfc5bb6ea Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 13 Nov 2026 12:02:35 +0100 Subject: [PATCH 14/36] minor layout fixes --- .../founder-dashboard.component.html | 37 +++++++++---------- .../hierarchy-chart.component.scss | 1 + .../hierarchy-chart.component.ts | 4 +- .../ui/page-header/page-header.component.scss | 2 +- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html index 4e938e1e..32184847 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html @@ -23,7 +23,7 @@ [ariaLabel]="'Vom Modell bewertet: ' + fmtInt(kpis().scoreable)" [tooltip]="scoreableTooltip" [detail]="scoreableDetail()" /> - +
-

Shortlist: Top-Kandidat:innen

+

Top-Kandidat:innen

+ aria-label="Mindestwert für die Liste der Top-Kandidat:innen" /> {{ thresholdDraft() }} {{ row.candidate.career_bucket ?? '–' }} @@ -157,8 +159,9 @@

- Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten. - 90 heißt: stärker als 90 % der Vergleichsgruppe. + Alle Werte sind Ränge von 0 bis 100 – keine + Wahrscheinlichkeiten. 90 heißt: stärker als 90 % der + Vergleichsgruppe.

@@ -213,9 +216,7 @@ matTooltip="Zahl der Patente mit Bezug zur Einrichtung." matTooltipClass="sg-tooltip-wide"> Patente - {{ - fmtInt(row.candidate.founder_features?.patents) - }} + {{ fmtInt(row.candidate.founder_features?.patents) }} Förderprojekte - {{ - fmtInt(row.candidate.founder_features?.grants) - }} + {{ fmtInt(row.candidate.founder_features?.grants) }} {{ FOUNDER_ICON }}

Noch keine Gründungspotenzial-Scores

- Für die {{ universityName() }} liegen Forschungsdaten - vor, aber die Gründungspotenzial-Auswertung wurde noch nicht - berechnet. Sobald sie vorliegt, erscheinen hier die Kandidat:innen und - ihre Werte. + Für die {{ universityName() }} liegen + Forschungsdaten vor, aber die Gründungspotenzial-Auswertung wurde + noch nicht berechnet. Sobald sie vorliegt, erscheinen hier die + Kandidat:innen und ihre Werte.

diff --git a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss index 9d201698..6daad1c2 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss +++ b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.scss @@ -180,4 +180,5 @@ .uh-chart { width: 100%; + height: 100% !important; } diff --git a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts index 01ae7615..01ce9d25 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts +++ b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts @@ -497,7 +497,7 @@ export class HierarchyChartComponent implements OnInit { const colors = this.chartTheme.colors(); return { - backgroundColor: this.chartTheme.colors().backgroundColor, + backgroundColor: '#ffffff', tooltip: { trigger: 'item', triggerOn: 'mousemove', @@ -524,7 +524,7 @@ export class HierarchyChartComponent implements OnInit { verticalAlign: 'middle', align: 'right', fontSize: 11, - color: colors.text, + color: 'black', formatter: (params: any) => { if (params.data.hasChildren) { return '{bold|' + params.name + '}'; diff --git a/webapp/src/app/shared/ui/page-header/page-header.component.scss b/webapp/src/app/shared/ui/page-header/page-header.component.scss index 5ae368a2..e39ac081 100644 --- a/webapp/src/app/shared/ui/page-header/page-header.component.scss +++ b/webapp/src/app/shared/ui/page-header/page-header.component.scss @@ -67,7 +67,7 @@ h3.page-header__title { } .page-header__subtitle { - max-width: 90ch; + max-width: 120ch; margin: 6px 0 0; color: var(--sg-text-muted); font-size: 14px; From 739669021bf43d2c58f49955e33b7406b464dcc3 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 15 Nov 2026 00:03:22 +0100 Subject: [PATCH 15/36] added explain panel to founder-dashobard component --- .../founder-dashboard.component.html | 9 + .../founder-dashboard.component.ts | 21 ++ .../founder-explainer-panel.component.html | 116 +++++++++ .../founder-explainer-panel.component.scss | 161 ++++++++++++ .../founder-explainer-panel.component.ts | 242 ++++++++++++++++++ webapp/src/styles.scss | 38 +++ 6 files changed, 587 insertions(+) create mode 100644 webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.html create mode 100644 webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.scss create mode 100644 webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.ts diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html index 32184847..aacbb981 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html @@ -3,6 +3,15 @@ title="Wer hat Gründungspotenzial?" subtitle="Kandidat:innen für Gründungsgespräche und -angebote." [titleTooltip]="pageTooltip"> +
@if (hasData() && hasScores()) {
diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts index 8f6567f3..569e576d 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts @@ -13,6 +13,7 @@ import { ActivatedRoute, Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop'; import { MatCardModule } from '@angular/material/card'; import { MatButtonModule } from '@angular/material/button'; +import { MatDialog } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatSliderModule } from '@angular/material/slider'; @@ -42,11 +43,14 @@ import { FOUNDER_ICON, HELP_OUTLINE_ICON, INFO_OUTLINE_ICON, + INSIGHTS_ICON, PERSONS_ICON, STAR_ICON, VERIFIED_ICON, } from '../../../shared/ui/icons'; import { CredentialService } from '../../../shared/services/credential.service'; +import { FounderExplainerPanelComponent } from './founder-explainer-panel/founder-explainer-panel.component'; + const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen'; @@ -88,6 +92,7 @@ export class FounderDashboardComponent { readonly FOUNDER_ICON = FOUNDER_ICON; readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON; readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON; + readonly INSIGHTS_ICON = INSIGHTS_ICON; readonly PERSONS_ICON = PERSONS_ICON; readonly STAR_ICON = STAR_ICON; readonly VERIFIED_ICON = VERIFIED_ICON; @@ -97,6 +102,7 @@ export class FounderDashboardComponent { private readonly router = inject(Router); private readonly route = inject(ActivatedRoute); + private readonly dialog = inject(MatDialog); private readonly credentials = inject(CredentialService, { optional: true }); /** The university whose cohort is shown; comes from the account profile. */ @@ -315,6 +321,21 @@ export class FounderDashboardComponent { this.onSliderCommit(next); } + /** Opens the global model explanation; independent of the selection. */ + openExplainer(): void { + this.dialog.open(FounderExplainerPanelComponent, { + panelClass: 'sg-side-panel', + position: { right: '0', top: '0' }, + height: '100dvh', + width: 'min(520px, 100vw)', + maxWidth: '100vw', + maxHeight: '100dvh', + ariaLabel: 'Modell-Erklärung zum Gründungspotenzial', + autoFocus: 'first-tabbable', + restoreFocus: true, + }); + } + // -- Formatting helpers for the template -------------------------------- readonly fmtInt = fmtInt; diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.html b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.html new file mode 100644 index 00000000..fe3d8993 --- /dev/null +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.html @@ -0,0 +1,116 @@ +
+
+
+

Modell-Erklärung

+

Woher kommt das Gründungspotenzial?

+
+ +
+ +
+ @if (loading()) { +
+ +

Modellinformationen werden geladen …

+
+ } @else if (error()) { +
+ {{ ERROR_OUTLINE_ICON }} +

Die Modellinformationen konnten nicht geladen werden.

+ +
+ } @else { +

+ Das Modell schätzt aus Publikationen, Patenten, Förderungen und + Industriekontakten, wie wahrscheinlich eine Person gründet. Die Balken + zeigen, auf welche Merkmale sich das Modell insgesamt am stärksten + stützt. +

+ +
+ + ROC-AUC {{ fmtAuc(modelInfo()?.oof_roc_auc) }} + + + PR-AUC {{ fmtAuc(modelInfo()?.oof_pr_auc) }} + + @if (modelInfo()?.reference_cohort_size) { + + Referenz + {{ fmtInt(modelInfo()?.reference_cohort_size) }} + Profile + + } + @if (modelInfo()?.reference_founders) { + + {{ fmtInt(modelInfo()?.reference_founders) }} + Gründer:innen + + } +
+ + @if (entries().length) { + + +
+

Woher kommen die Zahlen?

+

+ Für jedes Merkmal – zum Beispiel Publikationen pro Jahr, Patente + oder Industriekontakte – macht das Modell denselben Test: +

+
    +
  1. + Ein Merkmal wird zufällig vertauscht, alle anderen bleiben gleich. +
  2. +
  3. Das Modell bewertet dieselben Personen erneut.
  4. +
  5. + Je stärker die Trefferqualität danach sinkt, desto größer ist der + Balken. +
  6. +
+

+ Ein großer Balken heißt also: Das Modell verlässt sich stark auf + dieses Merkmal. Die Prozentwerte sind der Anteil an der + Gesamtbedeutung der angezeigten Merkmale. Sie sind keine Punkte, + keine Wahrscheinlichkeit und kein Beitrag einer einzelnen Person. + Die Werte gelten für das Modell insgesamt und sind für alle Personen + gleich. +

+
+ +

+ Ausgeblendet: Das wichtigste Trainingsmerkmal (Patent-Fachgebiet) ist + im aktuellen Datenbestand für alle gleich und trennt daher niemanden. + Institutionsmerkmale sind im Produktionsmodell nicht enthalten. +

+ } @else { +

+ Für dieses Modell sind keine darstellbaren Merkmale verfügbar. +

+ } + +

+ Die Werte beschreiben das trainierte Modell, nicht die einzelne Person. + Sie belegen keinen Ursache-Wirkungs-Zusammenhang. +

+ } +
+
diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.scss b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.scss new file mode 100644 index 00000000..4b8b8e67 --- /dev/null +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.scss @@ -0,0 +1,161 @@ +:host { + display: block; + height: 100%; +} + +.explainer { + display: flex; + flex-direction: column; + height: 100%; + background: var(--sg-card-bg); + color: var(--sg-text); +} + +.explainer__head { + display: flex; + flex: none; + align-items: flex-start; + gap: 12px; + padding: 20px 18px 14px 24px; + border-bottom: 1px solid var(--sg-border); +} + +.explainer__heading { + flex: 1; + min-width: 0; +} + +.explainer__eyebrow { + margin: 0 0 4px; + color: var(--sg-text-soft); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.explainer__title { + margin: 0; + color: var(--sg-text); + font-size: 19px; + font-weight: 700; + line-height: 1.3; +} + +.explainer__close { + flex: none; + margin: -4px -4px 0 0; + color: var(--sg-text-muted); +} + +.explainer__body { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 18px 24px 24px; +} + +.explainer__lead { + margin: 0 0 14px; + color: var(--sg-text-muted); + font-size: 13px; + line-height: 1.55; +} + +.explainer__metrics { + display: flex; + flex-wrap: wrap; + gap: 6px 14px; + margin-bottom: 18px; + padding: 10px 12px; + border: 1px solid var(--sg-border); + border-radius: 10px; + background: var(--sg-surface-muted); + color: var(--sg-text-muted); + font-size: 12px; + line-height: 1.4; + + strong { + color: var(--sg-text); + font-variant-numeric: tabular-nums; + } +} + +.explainer__chart { + width: 100%; +} + +.explainer__origin { + margin-top: 18px; + padding: 14px 16px 16px; + border: 1px solid var(--sg-border); + border-radius: 12px; + background: var(--sg-surface-muted); + + h3 { + margin: 0 0 8px; + color: var(--sg-text); + font-size: 13px; + font-weight: 700; + } + + p { + margin: 0; + color: var(--sg-text-muted); + font-size: 12px; + line-height: 1.5; + } +} + +.explainer__steps { + margin: 10px 0; + padding-left: 18px; + color: var(--sg-text-muted); + font-size: 12px; + line-height: 1.5; + + li + li { + margin-top: 4px; + } + + li::marker { + color: var(--sg-primary); + font-weight: 700; + } +} + +.explainer__note, +.explainer__caveat { + margin: 10px 0 0; + color: var(--sg-text-soft); + font-size: 11.5px; + line-height: 1.5; +} + +.explainer__caveat { + margin-top: 16px; + padding-top: 12px; + border-top: 1px solid var(--sg-border); +} + +.explainer__state { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + padding: 48px 12px; + color: var(--sg-text-muted); + font-size: 13px; + text-align: center; + + p { + margin: 0; + } + + &--error mat-icon { + width: 30px; + height: 30px; + color: var(--sg-error); + font-size: 30px; + } +} diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.ts b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.ts new file mode 100644 index 00000000..ec50a828 --- /dev/null +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-explainer-panel/founder-explainer-panel.component.ts @@ -0,0 +1,242 @@ +import { + ChangeDetectionStrategy, + Component, + computed, + inject, + signal, +} from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialogRef } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +import { FounderModelInfo, MultiplicatorsService } from '../../../../api'; +import { ChartThemeService } from '../../../../shared/services/chart-theme.service'; +import { CLOSE_ICON, ERROR_OUTLINE_ICON } from '../../../../shared/ui/icons'; +import { fmtInt } from '../../founder-potential.utils'; + +/** + * German labels for the features the founder classifier exposes. Features + * missing here fall back to a readable version of their technical name. + */ +const FEATURE_LABELS: Record = { + pub_rate: 'Publikationen pro Jahr', + first_publication_year: 'Jahr der ersten Publikation', + industry_collab_at_index: 'Publikationen mit Industriebeteiligung', + career_age_at_index: 'Karrierealter', + patents_at_index: 'Patente', + patent_rate: 'Patente pro Jahr', + patent_research_area_46: 'Patent-Fachgebiet: Informatik', + publication_research_area_32: 'Fachgebiet: Biomedizin & Klinik', + years_since_first_grant: 'Jahre seit erster Förderung', + grant_research_area_51: 'Förder-Fachgebiet: Physik', +}; + +/** One bar in the chart, with the share of the displayed total. */ +interface ImportanceEntry { + label: string; + share: number; + importance: number; + std: number | null; +} + +function isVisibleFeature(feature: string): boolean { + // Constant in this deployment (no IPC-to-FOR mapping) and dropped from the + // production bundle, respectively. Showing them would mislead locally. + return ( + feature !== 'patent_research_area_n.' && + !feature.startsWith('institution_') + ); +} + +function featureLabel(feature: string): string { + return ( + FEATURE_LABELS[feature] ?? + feature + .replace(/_/g, ' ') + .replace(/\b\w/g, (letter) => letter.toUpperCase()) + ); +} + +function fmtShare(value: number): string { + return value.toLocaleString('de-DE', { + minimumFractionDigits: 1, + maximumFractionDigits: 1, + }); +} + +function fmtImportance(value: number): string { + return value.toLocaleString('de-DE', { + minimumFractionDigits: 3, + maximumFractionDigits: 3, + }); +} + +function fmtAuc(value: number | null | undefined): string { + if (value === null || value === undefined) return '—'; + return value.toLocaleString('de-DE', { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }); +} + +/** + * Right-hand overlay that explains where the founder score comes from. + * + * It shows the model's global permutation importances, not per-person + * contributions: the API exposes only raw feature values per candidate. + */ +@Component({ + selector: 'app-founder-explainer-panel', + standalone: true, + imports: [ + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + NgxEchartsDirective, + ], + templateUrl: './founder-explainer-panel.component.html', + styleUrl: './founder-explainer-panel.component.scss', + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class FounderExplainerPanelComponent { + readonly CLOSE_ICON = CLOSE_ICON; + readonly ERROR_OUTLINE_ICON = ERROR_OUTLINE_ICON; + + private readonly service = inject(MultiplicatorsService); + private readonly dialogRef = inject( + MatDialogRef, + ); + private readonly chartTheme = inject(ChartThemeService); + + readonly modelInfo = signal(null); + readonly loading = signal(false); + readonly error = signal(false); + + readonly fmtInt = fmtInt; + readonly fmtAuc = fmtAuc; + + readonly entries = computed(() => { + const importances = (this.modelInfo()?.importances ?? []).filter((item) => + isVisibleFeature(item.feature), + ); + const total = importances.reduce( + (sum, item) => sum + item.importance_mean, + 0, + ); + if (total <= 0) return []; + + return [...importances] + .sort((a, b) => b.importance_mean - a.importance_mean) + .map((item) => ({ + label: featureLabel(item.feature), + share: (item.importance_mean / total) * 100, + importance: item.importance_mean, + std: item.importance_std ?? null, + })); + }); + + /** Enough vertical room for every bar; the panel body scrolls if needed. */ + readonly chartHeight = computed(() => + Math.max(240, this.entries().length * 44 + 24), + ); + + readonly chartOptions = computed(() => { + const colors = this.chartTheme.colors(); + const entries = this.entries(); + + return { + animationDuration: 350, + grid: { left: 4, right: 50, top: 8, bottom: 4, containLabel: true }, + tooltip: { + trigger: 'item', + confine: true, + backgroundColor: colors.tooltipBg, + borderColor: colors.tooltipBorder, + textStyle: { color: colors.tooltipTextColor, fontSize: 12 }, + formatter: (params: any) => { + const entry = entries[params.dataIndex]; + if (!entry) return ''; + const std = + entry.std !== null + ? ` ± ${fmtImportance(entry.std)}` + : ''; + return [ + `${entry.label}`, + `Anteil an der Gesamtbedeutung: ${fmtShare(entry.share)} %`, + `Beitrag zur Trefferqualität: ${fmtImportance(entry.importance)}${std}`, + ].join('
'); + }, + }, + xAxis: { + type: 'value', + axisLabel: { + color: colors.mutedTextColor, + fontSize: 11, + formatter: (value: any) => + `${value.toLocaleString('de-DE', { maximumFractionDigits: 0 })} %`, + }, + axisLine: { show: false }, + axisTick: { show: false }, + splitLine: { lineStyle: { color: colors.splitLine } }, + }, + yAxis: { + type: 'category', + inverse: true, + data: entries.map((entry) => entry.label), + axisLabel: { + color: colors.text, + fontSize: 12, + width: 170, + overflow: 'break', + lineHeight: 15, + }, + axisLine: { show: false }, + axisTick: { show: false }, + }, + series: [ + { + type: 'bar', + data: entries.map((entry) => entry.share), + barMaxWidth: 20, + itemStyle: { + color: colors.primary, + borderRadius: [0, 4, 4, 0], + }, + label: { + show: true, + position: 'right', + color: colors.text, + fontSize: 11, + formatter: (params: any) => `${fmtShare(params.value)} %`, + }, + }, + ], + }; + }); + + constructor() { + this.load(); + } + + load(): void { + this.loading.set(true); + this.error.set(false); + this.service.getFounderModelInfo().subscribe({ + next: (info) => { + this.modelInfo.set(info); + this.loading.set(false); + }, + error: () => { + this.error.set(true); + this.loading.set(false); + }, + }); + } + + close(): void { + this.dialogRef.close(); + } +} diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index 4236f572..c5f9c45c 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -657,6 +657,44 @@ html.dark-theme { white-space: normal; } +// Right-hand overlay used for contextual explanations, e.g. the founder model. +.cdk-overlay-pane.sg-side-panel { + animation: sg-side-panel-in 180ms ease-out; + + .mat-mdc-dialog-container { + padding: 0; + } + + .mat-mdc-dialog-surface { + overflow: hidden; + border-radius: 18px 0 0 18px; + background: var(--sg-card-bg); + } +} + +@media (max-width: 600px) { + .cdk-overlay-pane.sg-side-panel .mat-mdc-dialog-surface { + border-radius: 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .cdk-overlay-pane.sg-side-panel { + animation: none; + } +} + +@keyframes sg-side-panel-in { + from { + opacity: 0; + transform: translateX(28px); + } + to { + opacity: 1; + transform: translateX(0); + } +} + .cdk-overlay-pane .mat-mdc-option small { display: block; color: var(--sg-text-muted); From 23b112beb9ed6b7f930b82a8d9c9b26b9fd4cc57 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 15 Nov 2026 00:03:52 +0100 Subject: [PATCH 16/36] optimized charts rendering --- .../app/directives/passive-wheel.directive.ts | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 webapp/src/app/directives/passive-wheel.directive.ts diff --git a/webapp/src/app/directives/passive-wheel.directive.ts b/webapp/src/app/directives/passive-wheel.directive.ts new file mode 100644 index 00000000..2a5543cd --- /dev/null +++ b/webapp/src/app/directives/passive-wheel.directive.ts @@ -0,0 +1,58 @@ +import { Directive, ElementRef, inject } from '@angular/core'; + +const PASSIVE_WHEEL_SELECTOR = '[data-passive-wheel]'; +let wheelPatchInstalled = false; + +/** + * Chrome flags non-passive `wheel`/`mousewheel` listeners as scroll-blocking. + * zrender (ECharts) mounts them on the chart's inner viewport without listener + * options. The hierarchy tree only uses `roam: 'move'` and never calls + * `preventDefault()` on wheel events, so marking them passive is safe. + * + * The patch is global but only affects wheel listeners inside an element that + * carries this directive. + */ +function installPassiveWheelPatch(): void { + if (wheelPatchInstalled) return; + wheelPatchInstalled = true; + + const nativeAddEventListener = EventTarget.prototype.addEventListener; + + EventTarget.prototype.addEventListener = function ( + this: EventTarget, + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void { + const isWheelEvent = type === 'wheel' || type === 'mousewheel'; + const hasOptions = options !== undefined && typeof options !== 'boolean'; + + if ( + isWheelEvent && + !hasOptions && + this instanceof Element && + this.closest(PASSIVE_WHEEL_SELECTOR) + ) { + nativeAddEventListener.call(this, type, listener, { + capture: options === true, + passive: true, + }); + return; + } + + nativeAddEventListener.call(this, type, listener, options); + }; +} + +@Directive({ + selector: '[appPassiveWheel]', + standalone: true, +}) +export class PassiveWheelDirective { + private readonly host = inject>(ElementRef); + + constructor() { + this.host.nativeElement.setAttribute('data-passive-wheel', ''); + installPassiveWheelPatch(); + } +} From a9e7a0f3abbea4ef8407b0ae586e3edea93446bb Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 15 Nov 2026 00:03:59 +0100 Subject: [PATCH 17/36] optimized route-scroll behaviour --- .../shared/services/route-scroll.service.ts | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 webapp/src/app/shared/services/route-scroll.service.ts diff --git a/webapp/src/app/shared/services/route-scroll.service.ts b/webapp/src/app/shared/services/route-scroll.service.ts new file mode 100644 index 00000000..697beea1 --- /dev/null +++ b/webapp/src/app/shared/services/route-scroll.service.ts @@ -0,0 +1,181 @@ +import { Injectable, inject } from '@angular/core'; +import { NavigationEnd, NavigationStart, Router } from '@angular/router'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +const STORAGE_PREFIX = 'inse.scroll.'; +const STATE_KEY = 'sgScrollId'; + +/** + * Restores the scroll position of the app's inner scroll container. + * + * Rules: + * - a path change starts at the top, + * - back/forward restores the position of that history entry, + * - a query-only change on the same page keeps the current position, so + * selection, filter and pagination updates do not make the page jump. + * + * The app scrolls inside `main.content` (not the window), so Angular's + * built-in `withInMemoryScrolling` cannot handle it. + */ +@Injectable({ providedIn: 'root' }) +export class RouteScrollService { + private readonly router = inject(Router); + + private scroller: HTMLElement | null = null; + private currentScrollId: string | null = null; + private scrollFrame: number | null = null; + private nextNavigationIsPopstate = false; + private currentPath = ''; + + constructor() { + if ('scrollRestoration' in history) { + history.scrollRestoration = 'manual'; + } + + this.currentPath = this.pathOf(this.router.url); + + this.router.events.pipe(takeUntilDestroyed()).subscribe((event) => { + if (event instanceof NavigationStart) { + this.persistCurrent(); + this.nextNavigationIsPopstate = event.navigationTrigger === 'popstate'; + return; + } + + if (event instanceof NavigationEnd) { + this.handleNavigationEnd(event, this.nextNavigationIsPopstate); + } + }); + } + + /** Connects the persistent scroll container of the app shell. */ + attach(scroller: HTMLElement): void { + if (this.scroller === scroller) return; + + this.scroller?.removeEventListener('scroll', this.onScroll); + this.scroller = scroller; + this.scroller.addEventListener('scroll', this.onScroll, { passive: true }); + + const storedId = this.readStateId(); + this.currentScrollId = storedId ?? this.writeStateId(this.createScrollId()); + + this.restore(this.currentScrollId); + } + + /** Connects the scroll container after the first render. */ + attachWhenReady(getScroller: () => HTMLElement | null | undefined): void { + requestAnimationFrame(() => { + const scroller = getScroller(); + if (scroller) this.attach(scroller); + }); + } + + private handleNavigationEnd( + event: NavigationEnd, + isBackForward: boolean, + ): void { + const nextPath = this.pathOf(event.urlAfterRedirects); + + if (isBackForward) { + const id = this.readStateId() ?? this.writeStateId(this.createScrollId()); + this.currentScrollId = id; + this.scheduleRestore(id); + this.currentPath = nextPath; + return; + } + + const isNewPage = nextPath !== this.currentPath; + const previousPosition = this.scroller?.scrollTop ?? 0; + + const id = this.writeStateId(this.createScrollId()); + this.currentScrollId = id; + + if (isNewPage) { + this.scheduleScrollTop(); + } else { + // Query-only update on the same page: keep the user's position. + this.writePosition(id, previousPosition); + } + + this.currentPath = nextPath; + } + + private scheduleRestore(scrollId: string): void { + this.scheduleFrame(() => this.restore(scrollId)); + } + + private scheduleScrollTop(): void { + this.scheduleFrame(() => this.setScrollTop(0)); + } + + private scheduleFrame(callback: () => void): void { + // Two frames: one for the new component tree, one for its layout. + requestAnimationFrame(() => { + requestAnimationFrame(callback); + }); + } + + private restore(scrollId: string | null): void { + if (!this.scroller || !scrollId) return; + + const stored = this.readPosition(scrollId); + this.setScrollTop(stored); + } + + private setScrollTop(value: number): void { + if (!this.scroller) return; + this.scroller.scrollTop = Math.max(0, value); + } + + private persistCurrent(): void { + if (!this.scroller || !this.currentScrollId) return; + this.writePosition(this.currentScrollId, this.scroller.scrollTop); + } + + private readonly onScroll = (): void => { + if (this.scrollFrame !== null) return; + + this.scrollFrame = requestAnimationFrame(() => { + this.scrollFrame = null; + this.persistCurrent(); + }); + }; + + private createScrollId(): string { + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; + } + + private readStateId(): string | null { + const state = history.state as Record | null; + const id = state?.[STATE_KEY]; + return typeof id === 'string' && id.length > 0 ? id : null; + } + + private writeStateId(id: string): string { + const state = (history.state ?? {}) as Record; + history.replaceState({ ...state, [STATE_KEY]: id }, ''); + return id; + } + + private readPosition(scrollId: string): number { + try { + const raw = sessionStorage.getItem(STORAGE_PREFIX + scrollId); + const value = raw === null ? 0 : Number(raw); + return Number.isFinite(value) ? value : 0; + } catch { + return 0; + } + } + + private writePosition(scrollId: string, position: number): void { + try { + sessionStorage.setItem(STORAGE_PREFIX + scrollId, String(position)); + } catch { + // Storage can be unavailable (private mode/quota). Position restoration + // is an enhancement, never a hard requirement. + } + } + + private pathOf(url: string): string { + return url.split('?')[0].split('#')[0] || '/'; + } +} From ef6df95b544998e456e07c40f716619073e294be Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 16 Nov 2026 14:34:24 +0100 Subject: [PATCH 18/36] fixed verification helper for stop creating Edge/CollaborationGraph objects, added new helper function --- service/src/main/inse/orgminer/logic.py | 241 ++++++++++++++----- service/src/main/inse/orgminer/test_logic.py | 162 +++++++++++++ 2 files changed, 347 insertions(+), 56 deletions(-) diff --git a/service/src/main/inse/orgminer/logic.py b/service/src/main/inse/orgminer/logic.py index 503d9675..a2bc045e 100644 --- a/service/src/main/inse/orgminer/logic.py +++ b/service/src/main/inse/orgminer/logic.py @@ -2,11 +2,14 @@ from collections import defaultdict import asyncio -from typing import Any, Callable, Optional +from typing import Any, Awaitable, Callable, Optional from inse.integrations.elasticsearch import search from inse.utils import normalize_name from inse.model import ESCluster, ESIndex -from inse.authors.v2.service import _build_collaboration_graph +from inse.authors.v2.service import ( + _build_collaboration_graph, + _build_collaboration_graph_query, +) from inse.auth.model import Account, Organization from inse import config from .model import ( @@ -134,6 +137,180 @@ async def get_person_collaborator_weights( return weights +async def get_collaborator_weights_for_targets( + author_id: str, + institution_id: str, + target_ids: set[str] | frozenset[str] | list[str], +) -> dict[str, float]: + """Return ``{collaborator_id: shared_work_weight}`` only for ``target_ids``. + + The collaboration-graph builder expands every pair of authors on every work, + which explodes for works with hundreds or thousands of authors. Verification + only needs the weights towards the other staff candidates in the same + organization, so this asks Elasticsearch for those counts directly. + """ + targets = sorted(set(target_ids) - {author_id}) + if not targets: + return {} + + query = _build_collaboration_graph_query( + raw_oa_author_id=author_id, + institution_ids=[institution_id], + ) + body = { + "size": 0, + "query": query, + "aggs": { + "collaborators": { + "nested": {"path": "authorships"}, + "aggs": { + "targets": { + "terms": { + "field": "authorships.author.id", + "include": targets, + "size": len(targets), + } + } + }, + } + }, + } + + results = await search( + body=body, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, + ) + buckets = ( + results.get("aggregations", {}) + .get("collaborators", {}) + .get("targets", {}) + .get("buckets", []) + ) + return { + bucket["key"]: float(bucket["doc_count"]) + for bucket in buckets + if bucket.get("key") + } + + +async def get_verified_staff_with_collab_graph( + staff_list: list[dict[str, Any]], + institution_id: str = DEFAULT_INSTITUTION_ID, + max_concurrent_queries: int | None = None, +) -> list[dict[str, Any]]: + """Return verified staff entries with the OpenAlex IDs and edges proving verification. + + A staff entry is verified when at least one of its OpenAlex author candidates + has a collaboration edge to a candidate belonging to a different staff entry + in the same organization. + + Only collaborator weights towards the organization's other staff candidates + are fetched, so verification memory does not grow with the size of an + author's full co-author network. + + ``max_concurrent_queries`` bounds the OpenAlex candidate and graph searches. + It is useful for batch jobs processing organizations with large staff lists. + """ + if max_concurrent_queries is not None and max_concurrent_queries < 1: + raise ValueError("max_concurrent_queries must be at least 1.") + + query_semaphore = ( + asyncio.Semaphore(max_concurrent_queries) + if max_concurrent_queries is not None + else None + ) + + async def _run_query(operation: Callable[[], Awaitable[Any]]) -> Any: + if query_semaphore is None: + return await operation() + async with query_semaphore: + return await operation() + + async def _resolve_staff(staff: dict[str, Any]) -> set[str]: + name = staff.get("name") + if not name: + return set() + + candidate_ids = await _run_query( + lambda: resolve_author_candidates( + normalize_name(name), + institution_id, + ) + ) + return set(candidate_ids) + + async def _get_neighbor_weights( + author_id: str, target_ids: set[str] + ) -> dict[str, float]: + return await _run_query( + lambda: get_collaborator_weights_for_targets( + author_id, + institution_id, + target_ids, + ) + ) + + candidate_sets = await asyncio.gather( + *(_resolve_staff(staff) for staff in staff_list) + ) + + async def _verify_staff( + staff_index: int, own_ids: set[str] + ) -> dict[str, Any] | None: + if not own_ids: + return None + + other_ids = ( + set().union( + *( + candidate_ids + for index, candidate_ids in enumerate(candidate_sets) + if index != staff_index + ) + ) + - own_ids + ) + if not other_ids: + return None + + # ``other_ids`` only contains OpenAlex candidates of the other staff + # entries in this organization, and every candidate set was resolved + # against ``institution_id``. Collaborator weights are therefore + # restricted to same-university colleagues; no external co-author can + # contribute evidence. + author_ids = sorted(own_ids) + neighbor_weights = await asyncio.gather( + *(_get_neighbor_weights(author_id, other_ids) for author_id in author_ids) + ) + evidence = [ + { + "openalex_id": author_id, + "collaborator_openalex_id": collaborator_id, + "shared_work_weight": weights[collaborator_id], + } + for author_id, weights in zip(author_ids, neighbor_weights) + for collaborator_id in sorted(weights.keys() & other_ids) + ] + if not evidence: + return None + + return { + "staff_index": staff_index, + "staff": staff_list[staff_index], + "openalex_ids": sorted({item["openalex_id"] for item in evidence}), + "collaboration_evidence": evidence, + } + + checked_entries = await asyncio.gather( + *( + _verify_staff(staff_index, candidate_ids) + for staff_index, candidate_ids in enumerate(candidate_sets) + ) + ) + return [entry for entry in checked_entries if entry is not None] + + async def find_org_for_person( name: str, institution_id: str = None, @@ -567,62 +744,14 @@ async def get_orgminer_content_verified_by_collab_graph( orgminer_content = hits[0]["_source"] staff_list = orgminer_content.get("staff") or [] - async def _resolve_staff(staff: dict) -> set[str]: - name = staff.get("name") - if not name: - return set() - - candidate_ids = await resolve_author_candidates( - normalize_name(name), - institution_id, - ) - return set(candidate_ids) - - async def _get_neighbor_ids(author_id: str) -> set[str]: - collaborator_weights = await get_person_collaborator_weights( - author_id, - institution_id, - ) - return set(collaborator_weights.keys()) - - candidate_sets = await asyncio.gather( - *(_resolve_staff(staff) for staff in staff_list) - ) - - async def _is_verified(staff_index: int) -> bool: - own_ids = candidate_sets[staff_index] - if not own_ids: - return False - - # Candidates belonging to other staff members only. - other_ids = ( - set().union( - *( - candidate_ids - for index, candidate_ids in enumerate(candidate_sets) - if index != staff_index - ) - ) - - own_ids - ) - - if not other_ids: - return False - - neighbor_sets = await asyncio.gather( - *(_get_neighbor_ids(author_id) for author_id in own_ids) - ) - - return any(neighbor_ids & other_ids for neighbor_ids in neighbor_sets) - - verified_flags = await asyncio.gather( - *(_is_verified(index) for index in range(len(staff_list))) + verified_entries = await get_verified_staff_with_collab_graph( + staff_list, + institution_id, ) orgminer_content["verified_staff"] = [ - staff - for staff, is_verified in zip(staff_list, verified_flags) - if is_verified + entry["staff"] + for entry in verified_entries ] return OrgminerContent.from_elastic_hit(orgminer_content) @@ -704,4 +833,4 @@ async def get_classified_pages(org_url: str,institution_id: str = DEFAULT_INSTIT return ClassifiedPageResponse( total=response["hits"]["total"]["value"], pages=classified_pages - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/orgminer/test_logic.py b/service/src/main/inse/orgminer/test_logic.py index 644ecbec..15470475 100644 --- a/service/src/main/inse/orgminer/test_logic.py +++ b/service/src/main/inse/orgminer/test_logic.py @@ -1,8 +1,170 @@ +import asyncio import json from inse.orgminer import logic +def test_get_verified_staff_with_collab_graph_returns_matching_ids_and_edges( + monkeypatch, +): + staff = [ + {"name": "Person One", "email": "one@example.org"}, + {"name": "Person Two"}, + ] + resolved = { + "person one": ["https://openalex.org/A1", "https://openalex.org/A2"], + "person two": ["https://openalex.org/B1"], + } + neighbors = { + "https://openalex.org/A1": {"https://openalex.org/B1": 2.5}, + "https://openalex.org/A2": {}, + "https://openalex.org/B1": {}, + } + + async def resolve_author_candidates(name, institution_id): + return resolved[name] + + async def get_collaborator_weights_for_targets( + author_id, institution_id, target_ids + ): + return { + collaborator_id: weight + for collaborator_id, weight in neighbors[author_id].items() + if collaborator_id in target_ids + } + + monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates) + monkeypatch.setattr( + logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets + ) + + result = asyncio.run( + logic.get_verified_staff_with_collab_graph(staff, "I123") + ) + + assert result == [ + { + "staff_index": 0, + "staff": staff[0], + "openalex_ids": ["https://openalex.org/A1"], + "collaboration_evidence": [ + { + "openalex_id": "https://openalex.org/A1", + "collaborator_openalex_id": "https://openalex.org/B1", + "shared_work_weight": 2.5, + } + ], + } + ] + + +def test_get_verified_staff_with_collab_graph_respects_query_concurrency( + monkeypatch, +): + staff = [{"name": "Person One"}, {"name": "Person Two"}] + active_queries = 0 + peak_queries = 0 + + async def tracked(result): + nonlocal active_queries, peak_queries + active_queries += 1 + peak_queries = max(peak_queries, active_queries) + try: + await asyncio.sleep(0.001) + return result + finally: + active_queries -= 1 + + async def resolve_author_candidates(name, institution_id): + author_id = "https://openalex.org/A1" if name == "person one" else "https://openalex.org/A2" + return await tracked([author_id]) + + async def get_collaborator_weights_for_targets( + author_id, institution_id, target_ids + ): + neighbor_id = ( + "https://openalex.org/A2" + if author_id == "https://openalex.org/A1" + else "https://openalex.org/A1" + ) + return await tracked( + {neighbor_id: 1.0} if neighbor_id in target_ids else {} + ) + + monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates) + monkeypatch.setattr( + logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets + ) + + result = asyncio.run( + logic.get_verified_staff_with_collab_graph( + staff, + "I123", + max_concurrent_queries=1, + ) + ) + + assert len(result) == 2 + assert peak_queries == 1 + + +def test_get_collaborator_weights_for_targets_uses_bounded_aggregation( + monkeypatch, +): + captured = {} + + async def fake_search(**kwargs): + captured.update(kwargs) + return { + "aggregations": { + "collaborators": { + "targets": { + "buckets": [ + {"key": "https://openalex.org/B1", "doc_count": 7}, + ] + } + } + } + } + + monkeypatch.setattr(logic, "search", fake_search) + + result = asyncio.run( + logic.get_collaborator_weights_for_targets( + "https://openalex.org/A1", + "I123", + {"https://openalex.org/B1", "https://openalex.org/A1"}, + ) + ) + + assert result == {"https://openalex.org/B1": 7.0} + body = captured["body"] + assert body["size"] == 0 + nested = body["aggs"]["collaborators"] + assert nested["nested"] == {"path": "authorships"} + assert nested["aggs"]["targets"]["terms"]["include"] == [ + "https://openalex.org/B1" + ] + assert "query" in body + + +def test_get_collaborator_weights_for_targets_without_targets_skips_request( + monkeypatch, +): + async def fail_search(**kwargs): + raise AssertionError("search must not be called") + + monkeypatch.setattr(logic, "search", fail_search) + + result = asyncio.run( + logic.get_collaborator_weights_for_targets( + "https://openalex.org/A1", "I123", set() + ) + ) + + assert result == {} + + def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch): monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path) From cb4e7465b16a5f77ff84ad7f24f93583f947a12b Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 16 Nov 2026 14:42:45 +0100 Subject: [PATCH 19/36] added helper function to transfer NES credentials to the container/ added persistent directory for verified persons script --- .../src/main/inse/background_jobs/runner.py | 47 ++++++++++++++++-- .../test_runner_environment.py | 49 +++++++++++++++++++ .../main/inse/background_jobs/test_stop.py | 30 +++++++++++- 3 files changed, 121 insertions(+), 5 deletions(-) create mode 100644 service/src/main/inse/background_jobs/test_runner_environment.py diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 90adcf0e..8afed1c8 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -28,6 +28,9 @@ settings = config.get_settings() RUN_STATE_LOCK = RLock() ORGMINER_DEFAULT_PERSISTENT_DIR = "/app/orgminer_pipeline/runs" +ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY = ( + "inse/jobs/orgminer-verified-persons-ude" +) _client: docker.DockerClient | None = None @@ -131,6 +134,22 @@ def is_registry_image(image: str | None) -> bool: return bool(image) and image.split("/", 1)[0] == registry_host() +def uses_nes_credentials(image: str | None) -> bool: + """Only the OrgMiner verified-person job needs direct NES access.""" + if not image or not is_registry_image(image): + return False + + registry, _, image_path = image.partition("/") + image_path = image_path.split("@", 1)[0] + path_parts = image_path.rsplit("/", 1) + repository_name = path_parts[-1].split(":", 1)[0] + repository = "/".join([*path_parts[:-1], repository_name]) + return ( + registry == registry_host() + and repository == ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY + ) + + def container_name(definition: JobDefinition, run: JobRun) -> str: slug = definition.name.lower() slug = ( @@ -198,7 +217,20 @@ def is_orgminer(definition: JobDefinition) -> bool: def resolve_environment(definition: JobDefinition) -> dict[str, str]: - base = job_environment() if is_registry_image(resolve_image(definition)) else {} + image = resolve_image(definition) + base = job_environment() if is_registry_image(image) else {} + if uses_nes_credentials(image): + nes_environment = { + "ELASTICSEARCH_URL": settings.elasticsearch_url, + "ELASTICSEARCH_API_KEY": settings.elasticsearch_api_key, + } + base.update( + { + key: value + for key, value in nes_environment.items() + if value + } + ) return {**base, **(definition.env or {})} @@ -399,7 +431,16 @@ def _reconcile_runs(session: Session) -> None: container.reload() if container.status in ("exited", "dead"): - exit_code = container.attrs["State"]["ExitCode"] + state = container.attrs.get("State", {}) + exit_code = state["ExitCode"] + logs = container.logs().decode("utf-8", errors="replace") + if state.get("OOMKilled"): + logs = append_system_log( + logs, + "The container ran out of memory and was killed by the kernel " + f"(exit {exit_code}). No Python traceback is written for this; " + "the log above simply stops.", + ) new_status = ( JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED ) @@ -408,7 +449,7 @@ def _reconcile_runs(session: Session) -> None: run, new_status=new_status, exit_code=exit_code, - logs=container.logs().decode("utf-8", errors="replace"), + logs=logs, ) if applied: session.commit() diff --git a/service/src/main/inse/background_jobs/test_runner_environment.py b/service/src/main/inse/background_jobs/test_runner_environment.py new file mode 100644 index 00000000..ef4d304b --- /dev/null +++ b/service/src/main/inse/background_jobs/test_runner_environment.py @@ -0,0 +1,49 @@ +from types import SimpleNamespace + +from . import runner +from .model import JobDefinition + + +def _settings(): + return SimpleNamespace( + background_jobs_image="docker.nes.uni-due.de/inse/background-jobs:latest", + elasticsearch_url="https://nes.example/elastic", + elasticsearch_api_key="nes-api-key", + elasticsearch_inse_url="https://inse.example/elastic", + elasticsearch_inse_api_key="inse-api-key", + llm_api_url="https://llm.example", + llm_api_key="llm-api-key", + llm_model="test-model", + sentence_transformers_model_name="test-embedding-model", + ) + + +def _job(image: str) -> JobDefinition: + return JobDefinition(name="test", image=image) + + +def test_nes_credentials_are_injected_only_for_verified_person_image(monkeypatch): + monkeypatch.setattr(runner, "settings", _settings()) + verified_image = ( + "docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:v1" + ) + regular_image = "docker.nes.uni-due.de/inse/jobs/news-topics:latest" + + verified_environment = runner.resolve_environment(_job(verified_image)) + regular_environment = runner.resolve_environment(_job(regular_image)) + + assert verified_environment["ELASTICSEARCH_URL"] == "https://nes.example/elastic" + assert verified_environment["ELASTICSEARCH_API_KEY"] == "nes-api-key" + assert regular_environment["ELASTICSEARCH_INSE_API_KEY"] == "inse-api-key" + assert "ELASTICSEARCH_URL" not in regular_environment + assert "ELASTICSEARCH_API_KEY" not in regular_environment + + +def test_nes_credentials_are_not_injected_for_non_registry_copy(monkeypatch): + monkeypatch.setattr(runner, "settings", _settings()) + local_image = "localhost/inse/jobs/orgminer-verified-persons-ude:dev" + + environment = runner.resolve_environment(_job(local_image)) + + assert "ELASTICSEARCH_URL" not in environment + assert "ELASTICSEARCH_API_KEY" not in environment diff --git a/service/src/main/inse/background_jobs/test_stop.py b/service/src/main/inse/background_jobs/test_stop.py index edea90f8..7b47415e 100644 --- a/service/src/main/inse/background_jobs/test_stop.py +++ b/service/src/main/inse/background_jobs/test_stop.py @@ -12,10 +12,16 @@ from .model import JobRun, JobRunStatus, JobTriggeredBy class FakeContainer: def __init__( - self, *, status: str, exit_code: int, logs: str, stop_error=None + self, + *, + status: str, + exit_code: int, + logs: str, + stop_error=None, + oom_killed: bool = False, ): self.status = status - self.attrs = {"State": {"ExitCode": exit_code}} + self.attrs = {"State": {"ExitCode": exit_code, "OOMKilled": oom_killed}} self._logs = logs self.stop_calls = 0 self.removed = False @@ -126,6 +132,26 @@ def test_reconciler_keeps_running_container_after_backend_restart( assert container.removed is False +def test_reconciler_annotates_container_killed_by_oom(session, monkeypatch): + run = _run(session) + container = FakeContainer( + status="exited", + exit_code=137, + logs="last org: https://www.uni-due.de/zmb", + oom_killed=True, + ) + _use_container(monkeypatch, container) + + runner.reconcile_runs(session) + session.refresh(run) + + assert run.status == JobRunStatus.FAILED + assert run.exit_code == 137 + assert "last org: https://www.uni-due.de/zmb" in run.logs + assert "ran out of memory" in run.logs + assert container.removed is True + + def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch): run = _run(session) container = FakeContainer( From 492987100cfe2611035d48cbd8e133311a1e0e1b Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 16 Nov 2026 14:43:12 +0100 Subject: [PATCH 20/36] added verified persons job --- .dockerignore | 6 + .gitignore | 3 + service/scripts/jobs-image/README.md | 29 + .../orgminer-verified-persons-ude/Dockerfile | 27 + .../requirements.txt | 5 + .../README.md | 56 ++ .../upload_orgminer_verified_persons_ude.py | 917 ++++++++++++++++++ 7 files changed, 1043 insertions(+) create mode 100644 service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile create mode 100644 service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt create mode 100644 service/scripts/upload_orgminer_verified_persons_ude/README.md create mode 100644 service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py diff --git a/.dockerignore b/.dockerignore index 957438e1..7d14381e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,3 +1,4 @@ +# Root-context job images only need service code, never the webapp or repo data. * !background-jobs !service @@ -7,6 +8,11 @@ service/* # Keyword extraction contract, shared with background-jobs/app/llm/client.py. !service/src/main/inse/news/keyword_extraction.py +# UDE verified-persons job image imports the full service package and one +# institution hierarchy, so these are the only extra paths it needs. +!service/src/main/inse +!service/src/data/hierarchies/I62318514/hierarchy.json + # Data-only folders that do not belong in the job image. service/scripts/multipliers diff --git a/.gitignore b/.gitignore index fe6b79ff..77260b1e 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,6 @@ service/sentence_transformer/models/ llm_evaluations/bio_generation/.venv .devcontainer +# Runtime checkpoint for the UDE OrgMiner verified-person uploader. +service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json +service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json.tmp diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md index dfe8da7e..d0c7a4e0 100644 --- a/service/scripts/jobs-image/README.md +++ b/service/scripts/jobs-image/README.md @@ -82,6 +82,7 @@ differ only by their `command`. | Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | | News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend | | News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | +| UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint | | Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows | Each image is its own repository under the `jobs/` path namespace, prefixed @@ -106,6 +107,30 @@ docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest Each image's Dockerfile header lists its own build command. +### UDE OrgMiner verified persons + +```bash +docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \ + -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest . +docker push docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest +``` + +Create a manual-only job in the Jobs UI with this image and set **Persistent +directory** to `/state`. The image's entrypoint writes its JSON checkpoint to +`/state/orgminer_verified_persons_ude_progress.json`; the runner mounts a task-specific Docker volume there so +separate runs resume. Keep the job definition if you need to keep its checkpoint +(deleting the definition also removes its volume). Leave **Command** empty for a +full resumable run, or set it to `--limit 5` for a small first run. Set **Command** +to `--fresh` if every invocation should delete the checkpoint and start at the +first organization. Organizations are processed sequentially; no concurrency +flags exist. The target index is `orgminer_verified_persons_ude`. + +If the run stops without a `Finished:` line and reports exit `137`, the +container was killed (usually by the host's out-of-memory killer) and no Python +traceback exists. The run log then gets a `[system] ... ran out of memory ...` +note from the runner. A job without a **Persistent directory** always starts +from the first organization, which makes such a restart look identical. + ## Running locally without pushing Before each run the backend pulls the job's image from the registry when it is a @@ -127,6 +152,10 @@ is enough for local runs. Because every tag lives under the `docker.nes.uni-due.de` registry host, the backend treats these as registry images and injects the INSE Elasticsearch / LLM credentials automatically (plus any per-job `env`). +The `orgminer-verified-persons-ude` image also receives `ELASTICSEARCH_URL` and +`ELASTICSEARCH_API_KEY` from backend settings, and only that exact repository +gets those NES credentials. Other job images continue to receive INSE/LLM +credentials only. Most images write to the test index by default: the crawlers upload into the index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to diff --git a/service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile b/service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile new file mode 100644 index 00000000..a02f3cd0 --- /dev/null +++ b/service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile @@ -0,0 +1,27 @@ +# UDE OrgMiner staff verification using the collaboration graph. +# Build from the repository root: +# docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \ +# -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest . +# +# The runner injects INSE credentials for registry images and NES credentials +# only for this image. The persistent /state volume holds the JSON checkpoint. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app/service/src/main + +COPY service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/src/main/inse/ ./service/src/main/inse/ +COPY service/src/data/hierarchies/I62318514/hierarchy.json \ + ./service/src/data/hierarchies/I62318514/hierarchy.json +COPY service/scripts/upload_orgminer_verified_persons_ude/ \ + ./service/scripts/upload_orgminer_verified_persons_ude/ + +# Fail the image build if the service verification code is missing a dependency. +RUN python -c "import inse.orgminer.logic" + +ENTRYPOINT ["python", "/app/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py", \ + "--progress-file", "/state/orgminer_verified_persons_ude_progress.json"] diff --git a/service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt b/service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt new file mode 100644 index 00000000..8311e70a --- /dev/null +++ b/service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt @@ -0,0 +1,5 @@ +fastapi~=0.115.0 +httpx~=0.27.0 +pydantic-settings~=2.2.1 +python-dotenv~=1.0 +sqlmodel~=0.0.33 diff --git a/service/scripts/upload_orgminer_verified_persons_ude/README.md b/service/scripts/upload_orgminer_verified_persons_ude/README.md new file mode 100644 index 00000000..f94dd8ef --- /dev/null +++ b/service/scripts/upload_orgminer_verified_persons_ude/README.md @@ -0,0 +1,56 @@ +# Upload verified UDE OrgMiner persons + +Run from the repository root: + +```bash +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py +``` + +The script reads `ude_organization_content_august_2025_draft`, applies the +OrgMiner collaboration-graph verification rule, and upserts one document per +verified OpenAlex person and organization into `orgminer_verified_persons_ude` +on the INSE Elasticsearch cluster. + +For the background-job image and persistent checkpoint setup, see +[`../jobs-image/README.md`](../jobs-image/README.md#ude-orgminer-verified-persons). + +INSE credentials must be available as `ELASTICSEARCH_INSE_URL` and +`ELASTICSEARCH_INSE_API_KEY` for reading/writing OrgMiner data. NES credentials +must also be available as `ELASTICSEARCH_URL` and `ELASTICSEARCH_API_KEY` for +OpenAlex author resolution during verification. They can be set in the +environment or the service `.env` file. + +The default checkpoint is `orgminer_verified_persons_ude_progress.json` next to +the script. It records completed source organization document IDs and the last +completed organization URI. On restart the scan resumes from that URI, skips +completed organizations, and safely retries upserts if an interrupted request did +not get checkpointed. Use `--progress-file PATH` to keep the checkpoint elsewhere. + +The script processes one organization at a time, so a run needs no concurrency +flags. + +Useful options: + +```bash +# Run verification without writing to Elasticsearch or changing the checkpoint +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --dry-run + +# Smoke-test a limited number of pending organizations +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --limit 5 + +# Delete the checkpoint and scan from the first organization again +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh +``` + +Verification requests only the collaboration weights towards the organization's +other staff candidates. It does not materialize every co-author pair, which is +unbounded for works with hundreds or thousands of authors. The progress log ends +each line with the process's peak `rss` so memory growth is visible. + +`--fresh` removes the selected checkpoint and its temporary atomic-write file, +but does not clear the output index. Existing person/organization IDs are +upserted; output documents that are no longer produced are left in the index. +When configured on a background-job task, `--fresh` applies on every run, so the +task always restarts from the first source organization. If the checkpoint +directory is not a mounted volume, a warning is logged because progress cannot +survive the container. diff --git a/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py b/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py new file mode 100644 index 00000000..6e8e2a38 --- /dev/null +++ b/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py @@ -0,0 +1,917 @@ +"""Upload UDE OrgMiner staff that were verified by the collaboration graph. + +What this script does +--------------------- +For every organization in the UDE organization-content index (one at a time): + + 1. READ the organization and its staff list from Elasticsearch (INSE) + 2. VERIFY each staff member against the collaboration graph (OpenAlex) + 3. BUILD one document per (organization, OpenAlex person) + 4. UPLOAD the documents to ``orgminer_verified_persons_ude`` (bulk upsert) + 5. CHECKPOINT the organization as done in a small JSON progress file + +Everything runs sequentially: one organization at a time, one graph query at a +time. + +Resumability +------------ +Document IDs are deterministic, so re-running is always safe (documents are +overwritten, never duplicated). The progress file stores only: + +* ``processed_org_doc_ids``: organizations that were fully uploaded. +* ``last_source_uri``: a cursor; every organization sorted before it is done. + +The cursor stops advancing at the first failed organization, so failures are +retried on the next run. + +Usage (from any directory): + python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py + +Requires the INSE and NES Elasticsearch credentials in the service's ``.env`` +file or the environment. ``--dry-run`` verifies and counts without creating the +index, uploading, or touching the progress file. +""" +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import json +import logging +import os +import sys +import time +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable +from contextlib import aclosing +from dataclasses import dataclass, field +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, TypeVar + +import httpx + +SERVICE_DIR = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SERVICE_DIR / "src" / "main")) + +from inse import config # noqa: E402 +from inse.model import ESIndex # noqa: E402 +from inse.orgminer import logic # noqa: E402 +from inse.orgminer.institutions_helper import DEFAULT_INSTITUTION_ID # noqa: E402 + +T = TypeVar("T") +Hit = dict[str, Any] # one Elasticsearch search hit +HierarchyLookup = dict[str, tuple[str, list[str]]] # uri -> (name, path from root) + + +# ============================================================================= +# Configuration +# ============================================================================= + +SOURCE_INDEX = ESIndex.UDE_ORGANIZATION_CONTENT.value +OUTPUT_INDEX = "orgminer_verified_persons_ude" +INSTITUTION_URL = f"https://openalex.org/{DEFAULT_INSTITUTION_ID}" +DEFAULT_PROGRESS_FILE = ( + Path(__file__).resolve().parent / "orgminer_verified_persons_ude_progress.json" +) +PROGRESS_VERSION = 2 + +# Scanning the source index (point-in-time search, paged). +SCAN_PAGE_SIZE = 100 +PIT_KEEP_ALIVE = "10m" +MAX_PIT_RESTARTS = 5 + +# Bulk uploads. +BULK_MAX_DOCS = 250 +BULK_MAX_BYTES = 5 * 1024 * 1024 +MAX_ATTEMPTS = 4 +RETRYABLE_STATUS = {429, 502, 503, 504} + +# Collab-graph queries per organization. Kept at 1: fully sequential. +GRAPH_QUERIES_AT_A_TIME = 1 + +PROGRESS_SAVE_INTERVAL_S = 5.0 +PROGRESS_LOG_INTERVAL_S = 30.0 + +INDEX_MAPPING = { + "dynamic": "strict", + "properties": { + "name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "org_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "org_uri": {"type": "keyword"}, + "org_hierarchy_path": {"type": "keyword"}, + "openalex_id": {"type": "keyword"}, + # Kept verbatim in _source; staff dicts vary, so don't index them. + "staff": {"type": "object", "dynamic": False}, + "staff_entries": {"type": "object", "dynamic": False}, + "source_index": {"type": "keyword"}, + "source_org_doc_id": {"type": "keyword"}, + "verification_method": {"type": "keyword"}, + "verification_evidence": { + "type": "nested", + "properties": { + "openalex_id": {"type": "keyword"}, + "collaborator_openalex_id": {"type": "keyword"}, + "shared_work_weight": {"type": "float"}, + }, + }, + "verified_at": {"type": "date"}, + }, +} + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s %(message)s", +) +logger = logging.getLogger("upload_orgminer_verified_persons_ude") + + +# ============================================================================= +# Generic helpers +# ============================================================================= + + +def backoff_delay(attempt: int) -> float: + return min(2.0**attempt, 30.0) + + +async def retry_async( + operation: Callable[[], Awaitable[T]], + *, + description: str, + attempts: int = MAX_ATTEMPTS, +) -> T: + """Run ``operation``; on any exception wait (exponential backoff) and retry.""" + for attempt in range(1, attempts + 1): + try: + return await operation() + except Exception as exc: + if attempt == attempts: + raise + logger.warning( + "%s failed (attempt %d/%d): %s. Retrying.", + description, + attempt, + attempts, + exc, + ) + await asyncio.sleep(backoff_delay(attempt)) + raise AssertionError("unreachable") + + +def require_es_credentials() -> tuple[str, str]: + """Check both clusters are configured; return the INSE (url, api_key).""" + if ( + not config.settings.elasticsearch_url + or not config.settings.elasticsearch_api_key + ): + raise SystemExit( + "NES Elasticsearch credentials are missing. Collab-graph verification " + "needs ELASTICSEARCH_URL and ELASTICSEARCH_API_KEY." + ) + url = config.settings.elasticsearch_inse_url + api_key = config.settings.elasticsearch_inse_api_key + if not url or not api_key: + raise SystemExit( + "INSE Elasticsearch credentials are missing. Set " + "ELASTICSEARCH_INSE_URL and ELASTICSEARCH_INSE_API_KEY in the " + "environment or service/src/main/inse/.env." + ) + return url.rstrip("/"), api_key + + +def make_headers(api_key: str, content_type: str = "application/json") -> dict[str, str]: + return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type} + + +def checkpoint_dir_is_mounted(path: Path) -> bool | None: + """Whether the checkpoint directory is a mount point (relevant in containers). + + Returns ``None`` when the platform doesn't expose mount info (e.g. macOS). + """ + mountinfo = Path("/proc/self/mountinfo") + if not mountinfo.exists(): + return None + try: + directory = str(path.parent.resolve()) + lines = mountinfo.read_text(encoding="utf-8").splitlines() + except OSError: + return None + return any( + len(fields) > 4 and fields[4] == directory + for fields in (line.split() for line in lines) + ) + + +# ============================================================================= +# Run statistics and progress checkpoint +# ============================================================================= + + +@dataclass +class Stats: + scanned: int = 0 + orgs_done: int = 0 + orgs_failed: int = 0 + person_docs: int = 0 + uploaded: int = 0 + doc_errors: int = 0 + started: float = field(default_factory=time.monotonic) + + @property + def has_errors(self) -> bool: + return bool(self.orgs_failed or self.doc_errors) + + def summary(self) -> str: + return ( + f"scanned={self.scanned} orgs_done={self.orgs_done} " + f"orgs_failed={self.orgs_failed} person_docs={self.person_docs} " + f"uploaded={self.uploaded} doc_errors={self.doc_errors} " + f"elapsed={time.monotonic() - self.started:.0f}s" + ) + + +@dataclass +class Progress: + """Checkpoint saved to a JSON file (at most every few seconds, and on exit).""" + + path: Path + persist: bool # False in --dry-run: never write the file + processed_org_ids: set[str] = field(default_factory=set) + last_source_uri: str | None = None + _dirty: bool = False + _last_save: float = 0.0 + + @classmethod + def load(cls, path: Path, *, persist: bool) -> Progress: + progress = cls(path=path, persist=persist) + if not path.exists(): + return progress + try: + state = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SystemExit(f"Could not read progress file {path}: {exc}") from exc + + if ( + state.get("source_index") != SOURCE_INDEX + or state.get("output_index") != OUTPUT_INDEX + ): + raise SystemExit( + f"Progress file {path} belongs to a different source/output index. " + "Choose another --progress-file or move the old file." + ) + progress.processed_org_ids = set(state.get("processed_org_doc_ids", [])) + progress.last_source_uri = state.get("last_source_uri") + return progress + + def reset(self) -> None: + self.processed_org_ids.clear() + self.last_source_uri = None + + def mark_org_done(self, org_doc_id: str) -> None: + self.processed_org_ids.add(org_doc_id) + self._dirty = True + + def advance_cursor(self, uri: str | None) -> None: + if uri and uri != self.last_source_uri: + self.last_source_uri = uri + self._dirty = True + + def save(self, *, force: bool = False) -> None: + if not self.persist or not self._dirty: + return + now = time.monotonic() + if not force and now - self._last_save < PROGRESS_SAVE_INTERVAL_S: + return + state = { + "version": PROGRESS_VERSION, + "source_index": SOURCE_INDEX, + "output_index": OUTPUT_INDEX, + "processed_org_doc_ids": sorted(self.processed_org_ids), + "last_source_uri": self.last_source_uri, + "updated_at": datetime.now(UTC).isoformat(), + } + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_suffix(self.path.suffix + ".tmp") + tmp.write_text( + json.dumps(state, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + os.replace(tmp, self.path) # atomic: never leaves a half-written file + self._dirty = False + self._last_save = now + + +# ============================================================================= +# Step 1: READ organizations from the source index +# ============================================================================= + + +class PitExpired(Exception): + """The point-in-time search context is gone and must be reopened.""" + + +def _scan_query(start_uri: str | None) -> dict[str, Any]: + if not start_uri: + return {"match_all": {}} + # Organizations without a URI sort first and can never satisfy a range + # filter, so include them explicitly; already-processed IDs are skipped later. + return { + "bool": { + "should": [ + {"range": {"uri.keyword": {"gte": start_uri}}}, + {"bool": {"must_not": {"exists": {"field": "uri.keyword"}}}}, + ], + "minimum_should_match": 1, + } + } + + +async def _scan_pages( + client: httpx.AsyncClient, + url: str, + headers: dict[str, str], + start_uri: str | None, +) -> AsyncIterator[list[Hit]]: + """Open a point-in-time and yield pages of hits, sorted by URI.""" + response = await client.post( + f"{url}/{SOURCE_INDEX}/_pit", + params={"keep_alive": PIT_KEEP_ALIVE}, + headers=headers, + ) + response.raise_for_status() + pit_id = response.json()["id"] + search_after: list[Any] | None = None + + try: + while True: + payload: dict[str, Any] = { + "size": SCAN_PAGE_SIZE, + "query": _scan_query(start_uri), + "pit": {"id": pit_id, "keep_alive": PIT_KEEP_ALIVE}, + "sort": [ + {"uri.keyword": {"order": "asc", "missing": "_first"}}, + {"_shard_doc": "asc"}, + ], + "track_total_hits": False, + "_source": ["uri", "staff", "name", "org_name", "organization_name"], + } + if search_after is not None: + payload["search_after"] = search_after + + response = await client.post(f"{url}/_search", json=payload, headers=headers) + if response.status_code == 404 and "search_context_missing" in response.text: + raise PitExpired + response.raise_for_status() + + result = response.json() + hits = result.get("hits", {}).get("hits", []) + if not hits: + return + + pit_id = result.get("pit_id", pit_id) + search_after = hits[-1].get("sort") + yield hits + if search_after is None or len(hits) < SCAN_PAGE_SIZE: + return + finally: + try: + await client.request( + "DELETE", f"{url}/_pit", json={"id": pit_id}, headers=headers + ) + except Exception: + logger.warning("Could not close the point-in-time.", exc_info=True) + + +async def scan_organizations( + client: httpx.AsyncClient, + url: str, + headers: dict[str, str], + start_after_uri: str | None, +) -> AsyncIterator[Hit]: + """Yield organizations one by one, in URI order. + + If the point-in-time expires, reopen it and continue from the last URI seen. + Organizations that were already finished are skipped by the caller. + """ + resume_uri = start_after_uri + restarts = 0 + + while True: + try: + async with aclosing(_scan_pages(client, url, headers, resume_uri)) as pages: + async for page in pages: + restarts = 0 + resume_uri = page[-1].get("_source", {}).get("uri") or resume_uri + for hit in page: + yield hit + return + except PitExpired: + restarts += 1 + if restarts > MAX_PIT_RESTARTS: + raise RuntimeError("Point-in-time kept expiring; giving up.") from None + logger.warning( + "Point-in-time expired; reopening from uri=%r (restart %d/%d).", + resume_uri, + restarts, + MAX_PIT_RESTARTS, + ) + + +# ============================================================================= +# Step 3: BUILD one document per (organization, OpenAlex person) +# ============================================================================= + + +def normalize_org_uri(uri: str | None) -> str | None: + if not uri: + return None + normalized = uri.strip().rstrip("/") + if normalized.endswith("/index"): + normalized = normalized[: -len("/index")].rstrip("/") + return normalized or None + + +def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup: + """Map normalized organization links to (display name, path from the root).""" + lookup: HierarchyLookup = {} + + def visit(node: Any, ancestors: list[str]) -> None: + name = getattr(node, "name_de", None) or getattr(node, "name_en", None) + path = [*ancestors, name] if name else ancestors + if name: + for link in (getattr(node, "link_de", None), getattr(node, "link_en", None)): + if normalized := normalize_org_uri(link): + lookup[normalized] = (name, path) + for child in getattr(node, "children", None) or []: + visit(child, path) + + for root in hierarchy: + visit(root, []) + return lookup + + +def organization_details( + source: dict[str, Any], hierarchy_lookup: HierarchyLookup +) -> tuple[str, list[str], str | None]: + """Return (org name, hierarchy path, org URI), with fallbacks for the name.""" + org_uri = source.get("uri") + hierarchy_name, hierarchy_path = hierarchy_lookup.get( + normalize_org_uri(org_uri) or "", ("", []) + ) + org_name = ( + source.get("org_name") + or source.get("organization_name") + or source.get("name") + or hierarchy_name + or org_uri + or "Unknown organization" + ) + return str(org_name), hierarchy_path, org_uri + + +def stable_document_id(org_uri: str | None, org_doc_id: str, openalex_id: str) -> str: + """Deterministic ID so re-uploads overwrite instead of duplicating.""" + org_identity = normalize_org_uri(org_uri) or org_doc_id + return hashlib.sha256(f"{org_identity}\0{openalex_id}".encode()).hexdigest() + + +def _canonical(value: Any) -> str: + return json.dumps(value, sort_keys=True, ensure_ascii=False, default=str) + + +def make_person_documents( + source: dict[str, Any], + source_doc_id: str, + verified_entries: list[dict[str, Any]], + hierarchy_lookup: HierarchyLookup, + verified_at: str, +) -> list[tuple[str, Hit]]: + """Turn verified staff entries into [(doc_id, document)], one per OpenAlex person. + + A person may be matched by several staff entries and several collaborators, + so entries and evidence are de-duplicated per person first. + """ + org_name, hierarchy_path, org_uri = organization_details(source, hierarchy_lookup) + + # openalex_id -> {canonical staff json -> staff dict} + staff_by_person: dict[str, dict[str, dict[str, Any]]] = {} + # openalex_id -> {(openalex_id, collaborator_id) -> evidence dict} + evidence_by_person: dict[str, dict[tuple[Any, Any], dict[str, Any]]] = {} + + for entry in verified_entries: + staff = entry["staff"] + staff_key = _canonical(staff) + for openalex_id in entry["openalex_ids"]: + staff_by_person.setdefault(openalex_id, {}).setdefault(staff_key, staff) + seen = evidence_by_person.setdefault(openalex_id, {}) + for evidence in entry["collaboration_evidence"]: + if evidence["openalex_id"] == openalex_id: + key = (evidence["openalex_id"], evidence.get("collaborator_openalex_id")) + seen.setdefault(key, evidence) + + documents: list[tuple[str, Hit]] = [] + for openalex_id, staff_map in staff_by_person.items(): + staff_entries = list(staff_map.values()) + primary_staff = staff_entries[0] + document = { + "name": primary_staff.get("name"), + "org_name": org_name, + "org_uri": org_uri, + "org_hierarchy_path": hierarchy_path, + "openalex_id": openalex_id, + "staff": primary_staff, + "staff_entries": staff_entries, + "source_index": SOURCE_INDEX, + "source_org_doc_id": source_doc_id, + "verification_method": "collab_graph", + "verification_evidence": list(evidence_by_person[openalex_id].values()), + "verified_at": verified_at, + } + doc_id = stable_document_id(org_uri, source_doc_id, openalex_id) + documents.append((doc_id, document)) + return documents + + +# ============================================================================= +# Step 4: UPLOAD documents to the output index +# ============================================================================= + + +async def ensure_output_index( + client: httpx.AsyncClient, url: str, headers: dict[str, str] +) -> None: + """Create the output index with its mapping if it doesn't exist yet.""" + head = await client.head(f"{url}/{OUTPUT_INDEX}", headers=headers) + if head.status_code == 200: + logger.info("Output index %r already exists.", OUTPUT_INDEX) + return + if head.status_code != 404: + head.raise_for_status() + + response = await client.put( + f"{url}/{OUTPUT_INDEX}", json={"mappings": INDEX_MAPPING}, headers=headers + ) + if response.status_code == 400 and "resource_already_exists" in response.text: + logger.info("Output index %r was created concurrently.", OUTPUT_INDEX) + return + response.raise_for_status() + logger.info("Created output index %r.", OUTPUT_INDEX) + + +def _bulk_chunk(doc_id: str, document: Hit) -> str: + action = json.dumps({"index": {"_index": OUTPUT_INDEX, "_id": doc_id}}) + return f"{action}\n{json.dumps(document, ensure_ascii=False)}\n" + + +def _split_batches(items: list[tuple[str, str]]) -> Iterable[list[tuple[str, str]]]: + """Group (doc_id, ndjson) items by document count and payload size.""" + batch: list[tuple[str, str]] = [] + size = 0 + for item in items: + item_size = len(item[1].encode("utf-8")) + if batch and (len(batch) >= BULK_MAX_DOCS or size + item_size > BULK_MAX_BYTES): + yield batch + batch, size = [], 0 + batch.append(item) + size += item_size + if batch: + yield batch + + +async def _post_bulk( + client: httpx.AsyncClient, + url: str, + api_key: str, + batch: list[tuple[str, str]], +) -> dict[str, Any]: + """Send one bulk request, retrying on network errors and retryable statuses.""" + body = "".join(chunk for _, chunk in batch).encode("utf-8") + headers = make_headers(api_key, "application/x-ndjson") + + async def send() -> dict[str, Any]: + response = await client.post(f"{url}/_bulk", content=body, headers=headers) + response.raise_for_status() + return response.json() + + return await retry_async(send, description="Bulk request") + + +async def bulk_index( + client: httpx.AsyncClient, + url: str, + api_key: str, + documents: list[tuple[str, Hit]], +) -> tuple[int, list[tuple[str, str]]]: + """Upsert documents. Return (success count, [(doc_id, error), ...]). + + Items rejected with a retryable status (typically 429 under load) are sent + again with backoff. Everything else that fails is reported as a failure. + """ + pending = [(doc_id, _bulk_chunk(doc_id, doc)) for doc_id, doc in documents] + succeeded = 0 + failures: dict[str, str] = {} + + for attempt in range(1, MAX_ATTEMPTS + 1): + retry: list[tuple[str, str]] = [] + + for batch in _split_batches(pending): + result = await _post_bulk(client, url, api_key, batch) + items = result.get("items", []) + if len(items) != len(batch): + raise RuntimeError( + "Elasticsearch bulk response item count did not match the request." + ) + + for (doc_id, chunk), item in zip(batch, items): + outcome = item.get("index", {}) + status = outcome.get("status", 0) + error = json.dumps(outcome.get("error", outcome), ensure_ascii=False) + if 200 <= status < 300: + succeeded += 1 + failures.pop(doc_id, None) + elif status in RETRYABLE_STATUS: + retry.append((doc_id, chunk)) + failures[doc_id] = error + else: + failures[doc_id] = error + + if not retry: + break + pending = retry + if attempt < MAX_ATTEMPTS: + logger.warning( + "%d bulk items were rejected; retrying (attempt %d/%d).", + len(retry), + attempt, + MAX_ATTEMPTS, + ) + await asyncio.sleep(backoff_delay(attempt)) + + return succeeded, sorted(failures.items()) + + +# ============================================================================= +# Processing a single organization (steps 2-4) +# ============================================================================= + + +@dataclass +class Context: + """Everything `process_organization` needs, bundled in one place.""" + + client: httpx.AsyncClient + url: str + api_key: str + hierarchy_lookup: HierarchyLookup + stats: Stats + dry_run: bool + fail_fast: bool + verified_at: str + + +def staff_of(source: dict[str, Any]) -> list[dict[str, Any]]: + raw = source.get("staff") + if not isinstance(raw, list): + return [] + return [staff for staff in raw if isinstance(staff, dict)] + + +async def process_organization(hit: Hit, ctx: Context) -> bool: + """Verify one organization's staff and upload the result. + + Returns True if the organization is completely done (nothing to retry). + """ + doc_id = str(hit.get("_id") or "") + source = hit.get("_source", {}) + label = source.get("uri") or doc_id + + staff_list = staff_of(source) + if not staff_list: + return True # nothing to verify + + logger.info("Processing organization %s (%d staff entries).", label, len(staff_list)) + + try: + # Step 2: verify staff against the collaboration graph. + verified_entries = await retry_async( + lambda: logic.get_verified_staff_with_collab_graph( + staff_list, + INSTITUTION_URL, + max_concurrent_queries=GRAPH_QUERIES_AT_A_TIME, + ), + description=f"Collab-graph verification for {label}", + ) + + # Step 3: build one document per OpenAlex person. + documents = make_person_documents( + source, doc_id, verified_entries, ctx.hierarchy_lookup, ctx.verified_at + ) + ctx.stats.person_docs += len(documents) + + if ctx.dry_run: + logger.info( + "DRY RUN org=%s verified_staff=%d person_org_docs=%d", + label, + len(verified_entries), + len(documents), + ) + return True + + # Step 4: upload. + uploaded, failures = await bulk_index(ctx.client, ctx.url, ctx.api_key, documents) + ctx.stats.uploaded += uploaded + for failed_id, error in failures: + ctx.stats.doc_errors += 1 + logger.error("Failed to index document %s (org %s): %s", failed_id, label, error) + return not failures + + except Exception: + logger.exception("Failed processing organization %s (_id=%s).", label, doc_id) + if ctx.fail_fast: + raise + return False + + +# ============================================================================= +# Main flow +# ============================================================================= + + +def reset_checkpoint_files(progress_file: Path) -> None: + """Implements --fresh: delete the progress file (and a leftover .tmp file).""" + tmp_file = progress_file.with_suffix(progress_file.suffix + ".tmp") + existed = progress_file.exists() + removed = [] + for path in (progress_file, tmp_file): + try: + path.unlink() + removed.append(str(path)) + except FileNotFoundError: + pass + logger.info( + "--fresh: removed %s. Output index %r is kept and will be updated by upserts.", + removed, + OUTPUT_INDEX, + ) + if existed: + logger.warning( + "--fresh discarded the existing checkpoint. If a saved job command " + "contains --fresh, it restarts from the first organization on every " + "run; remove the flag to resume instead." + ) + + +def prepare_progress(args: argparse.Namespace) -> Progress: + """Load (or reset) the checkpoint according to the CLI flags.""" + if args.fresh: + reset_checkpoint_files(args.progress_file) + + progress = Progress.load(args.progress_file, persist=not args.dry_run) + if args.ignore_progress: + progress.reset() + + logger.info( + "Checkpoint %s: %d finished organizations, resume cursor=%r.", + args.progress_file, + len(progress.processed_org_ids), + progress.last_source_uri, + ) + if not args.dry_run and checkpoint_dir_is_mounted(args.progress_file) is False: + logger.warning( + "Checkpoint directory %s is not a mounted volume, so progress is lost " + "as soon as the container is removed. Set the job's persistent directory " + "to %s.", + args.progress_file.parent, + args.progress_file.parent, + ) + return progress + + +async def run(args: argparse.Namespace) -> int: + # Setup --------------------------------------------------------------- + url, api_key = require_es_credentials() # fail fast, before slow work + headers = make_headers(api_key) + progress = prepare_progress(args) + + hierarchy = await logic.get_hierarchy(INSTITUTION_URL) + hierarchy_lookup = build_hierarchy_lookup(hierarchy) + logger.info("Loaded %d hierarchy URL mappings for UDE.", len(hierarchy_lookup)) + + stats = Stats() + organizations_handled = 0 # for --limit + cursor_blocked = False # set after the first failure; cursor stops moving + last_log = time.monotonic() + + async with httpx.AsyncClient(timeout=httpx.Timeout(90.0)) as client: + if not args.dry_run: + await ensure_output_index(client, url, headers) + + ctx = Context( + client=client, + url=url, + api_key=api_key, + hierarchy_lookup=hierarchy_lookup, + stats=stats, + dry_run=args.dry_run, + fail_fast=args.fail_fast, + verified_at=datetime.now(UTC).isoformat(), + ) + + # Main loop: one organization at a time ----------------------------- + try: + async with aclosing( + scan_organizations(client, url, headers, progress.last_source_uri) + ) as organizations: + async for hit in organizations: + stats.scanned += 1 + org_doc_id = str(hit.get("_id") or "") + org_uri = hit.get("_source", {}).get("uri") + + # Already uploaded in an earlier run. + if org_doc_id in progress.processed_org_ids: + if not cursor_blocked: + progress.advance_cursor(org_uri) + continue + + if args.limit is not None and organizations_handled >= args.limit: + logger.info("Reached --limit=%d.", args.limit) + break + + organizations_handled += 1 + if await process_organization(hit, ctx): + stats.orgs_done += 1 + if not args.dry_run: + progress.mark_org_done(org_doc_id) + if not cursor_blocked: + progress.advance_cursor(org_uri) + else: + stats.orgs_failed += 1 + cursor_blocked = True # retry this one on the next run + + progress.save() + if time.monotonic() - last_log >= PROGRESS_LOG_INTERVAL_S: + logger.info("Progress: %s", stats.summary()) + last_log = time.monotonic() + finally: + progress.save(force=True) + + logger.info("Finished: %s progress_file=%s", stats.summary(), args.progress_file) + return 1 if stats.has_errors else 0 + + +# ============================================================================= +# Command line +# ============================================================================= + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Upload UDE OrgMiner persons verified by the collaboration graph." + ) + parser.add_argument( + "--progress-file", + type=Path, + default=DEFAULT_PROGRESS_FILE, + help=f"JSON checkpoint file (default: {DEFAULT_PROGRESS_FILE})", + ) + parser.add_argument( + "--limit", + type=int, + default=None, + help="Process at most this many not-yet-completed organizations.", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help=( + "Verify and count results without creating the index, uploading, " + "or writing progress. Still reads existing progress unless " + "--ignore-progress is given." + ), + ) + parser.add_argument( + "--ignore-progress", + action="store_true", + help="Start from scratch, ignoring any existing progress file contents.", + ) + parser.add_argument( + "--fresh", + action="store_true", + help=( + "Delete the selected JSON progress checkpoint and start from the " + "first source organization. Existing output-index documents are kept." + ), + ) + parser.add_argument( + "--fail-fast", + action="store_true", + help="Stop at the first organization-level error instead of continuing.", + ) + args = parser.parse_args() + if args.limit is not None and args.limit < 1: + parser.error("--limit must be at least 1.") + return args + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(run(parse_args()))) From 8322fea036143b55fd54c0fe93ace3ba1c33d023 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 21:10:51 +0100 Subject: [PATCH 21/36] reused existing normalize org uri function --- .../upload_orgminer_verified_persons_ude.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py b/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py index 6e8e2a38..7a8017ff 100644 --- a/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py +++ b/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py @@ -56,7 +56,10 @@ sys.path.insert(0, str(SERVICE_DIR / "src" / "main")) from inse import config # noqa: E402 from inse.model import ESIndex # noqa: E402 from inse.orgminer import logic # noqa: E402 -from inse.orgminer.institutions_helper import DEFAULT_INSTITUTION_ID # noqa: E402 +from inse.orgminer.institutions_helper import ( # noqa: E402 + DEFAULT_INSTITUTION_ID, + normalize_org_uri, +) T = TypeVar("T") Hit = dict[str, Any] # one Elasticsearch search hit @@ -422,15 +425,6 @@ async def scan_organizations( # ============================================================================= -def normalize_org_uri(uri: str | None) -> str | None: - if not uri: - return None - normalized = uri.strip().rstrip("/") - if normalized.endswith("/index"): - normalized = normalized[: -len("/index")].rstrip("/") - return normalized or None - - def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup: """Map normalized organization links to (display name, path from the root).""" lookup: HierarchyLookup = {} From 22997f6a169d7b3442124896782b68e274d2ce35 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 21:16:10 +0100 Subject: [PATCH 22/36] added normalize org uri helper --- .../src/main/inse/orgminer/institutions_helper.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/service/src/main/inse/orgminer/institutions_helper.py b/service/src/main/inse/orgminer/institutions_helper.py index d22872da..4b1050bd 100644 --- a/service/src/main/inse/orgminer/institutions_helper.py +++ b/service/src/main/inse/orgminer/institutions_helper.py @@ -39,6 +39,21 @@ def strip_openalex_prefix(institution_id: str) -> str: return institution_id.rsplit("/", 1)[-1] +def normalize_org_uri(uri: str | None) -> str | None: + """Normalize an organization URL so hierarchy links compare reliably. + + Trims whitespace, drops a trailing slash and the common ``/index`` suffix, + so ``https://www.example.org/x/``, ``https://www.example.org/x/index`` and + ``https://www.example.org/x`` all map to the same value. + """ + if not uri: + return None + normalized = uri.strip().rstrip("/") + if normalized.endswith("/index"): + normalized = normalized[: -len("/index")].rstrip("/") + return normalized or None + + def full_institution_url(institution_id: str) -> str: """Normalize any institution id form to the full OpenAlex URL form.""" return f"https://openalex.org/{strip_openalex_prefix(institution_id)}" From a1317810c928215e8b168c03e9bf99398ba1b92a Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 21:20:13 +0100 Subject: [PATCH 23/36] added verified organization endpoint with models --- service/src/main/inse/persons/logic.py | 79 ++++++++++++++++++- service/src/main/inse/persons/model.py | 27 +++++++ service/src/main/inse/persons/service.py | 19 +++++ webapp/src/app/api/api/persons.service.ts | 57 +++++++++++++ webapp/src/app/api/model/models.ts | 2 + .../src/app/api/model/verifiedOrganization.ts | 24 ++++++ .../model/verifiedOrganizationsResponse.ts | 23 ++++++ 7 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 webapp/src/app/api/model/verifiedOrganization.ts create mode 100644 webapp/src/app/api/model/verifiedOrganizationsResponse.ts diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index f6355cf8..96823228 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -15,14 +15,20 @@ from inse.exceptions import ( NotFoundException, ) from inse.integrations import elasticsearch -from inse.model import ESIndex +from inse.model import ESCluster, ESIndex from inse.models.openalex.author import Author from inse.models.openalex.authors_list_response import AuthorsListResponse from inse.models.openalex.meta import Meta +from inse.orgminer.institutions_helper import ( + DEFAULT_INSTITUTION_ID, + normalize_org_uri, + strip_openalex_prefix, +) from inse.persons.model import ( CareerMetrics, CustomAuthor, CustomAuthorsListResponse, + VerifiedOrganization, ) from inse.persons.query_builder import build_authors_search_rescored from inse.works.logic import enrich_topic_descriptions @@ -32,6 +38,77 @@ from .. import config, util logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen +VERIFIED_PERSONS_INDEX = "orgminer_verified_persons_ude" +VERIFIED_PERSONS_INSTITUTION_ID = DEFAULT_INSTITUTION_ID +VERIFIED_PERSON_FIELDS = [ + "openalex_id", + "org_name", + "org_uri", + "org_hierarchy_path", + "verified_at", +] + + +async def get_verified_organizations(author_id: str) -> list[VerifiedOrganization]: + """Return organizations where ``author_id`` is a verified staff member. + + Reads the OrgMiner verified-persons index on the INSE cluster. Documents are + keyed by the person's OpenAlex id field (both raw and full-URL forms are + accepted), so the lookup does not depend on the index's ``_id`` scheme. + + An unavailable index must not break the person page, so failures are logged + and reported as "not verified". + """ + short_id = strip_openalex_prefix(author_id.strip().rstrip("/")) + if not short_id: + return [] + + query = { + "_source": VERIFIED_PERSON_FIELDS, + "size": 50, + "query": { + "terms": { + "openalex_id": [short_id, f"https://openalex.org/{short_id}"] + } + }, + "sort": [ + {"verified_at": {"order": "desc", "missing": "_last"}}, + {"org_name.keyword": {"order": "asc", "missing": "_last"}}, + ], + } + + try: + data = await elasticsearch.search( + body=query, index=VERIFIED_PERSONS_INDEX, cluster=ESCluster.INSE + ) + except Exception: + logger.exception( + "Verified-organization lookup failed for author %r.", author_id + ) + return [] + + organizations: dict[str, VerifiedOrganization] = {} + for hit in data.get("hits", {}).get("hits", []): + source = hit.get("_source") or {} + org_uri = normalize_org_uri(source.get("org_uri")) + org_name = (source.get("org_name") or "").strip() + key = org_uri or org_name.casefold() + if not key: + continue + + # Old sha256-ID and new person-level documents can coexist until the + # index is rebuilt. The newest document wins because of the sort above. + organizations.setdefault( + key, + VerifiedOrganization( + org_name=org_name or org_uri or "Unbekannte Organisation", + org_uri=org_uri, + org_hierarchy_path=source.get("org_hierarchy_path") or [], + verified_at=source.get("verified_at"), + ), + ) + + return list(organizations.values()) async def find_ude_author_by_name(display_name: str) -> dict | None: diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py index 220d5fb2..45ff9e33 100644 --- a/service/src/main/inse/persons/model.py +++ b/service/src/main/inse/persons/model.py @@ -4,6 +4,8 @@ Data models for persons / authors. """ +from datetime import datetime + from pydantic import BaseModel, Field from inse.models.openalex.author import Author @@ -71,6 +73,31 @@ class PersonBio(BaseModel): bio: str = Field(description="The generated biography.") +class VerifiedOrganization(BaseModel): + org_name: str = Field(description="Display name of the verified organization.") + org_uri: str | None = Field( + default=None, description="Organization URL, normalized for hierarchy matching." + ) + org_hierarchy_path: list[str] = Field( + default_factory=list, + description="Path from the hierarchy root to the organization node.", + ) + verified_at: datetime | None = Field( + default=None, description="When the organization membership was verified." + ) + + +class VerifiedOrganizationsResponse(BaseModel): + institution_id: str | None = Field( + default=None, + description="OpenAlex institution ID that the verified memberships belong to.", + ) + organizations: list[VerifiedOrganization] = Field( + default_factory=list, + description="Organizations where the person has verified staff membership.", + ) + + class PersonFilters(BaseModel): institution: str | None = None cited_by_count: int | None = None diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 826ffc4d..4f9f153e 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -75,6 +75,25 @@ async def get_person_by_id( return await logic.get_person_by_id(author_id=id, include=include) +@router.get( + "/person/{id}/verified-organizations", + operation_id="getVerifiedOrganizations", + response_model=model.VerifiedOrganizationsResponse, + summary="Returns the organizations where a person is a verified staff member.", + tags=["Persons"], +) +async def get_verified_organizations( + id: Annotated[ + str, Path(description="OpenAlex author ID", example=["A5093075883"]) + ], +): + organizations = await logic.get_verified_organizations(author_id=id) + return model.VerifiedOrganizationsResponse( + institution_id=logic.VERIFIED_PERSONS_INSTITUTION_ID, + organizations=organizations, + ) + + @router.get( "/persons/searchByName", operation_id="searchPersonsByName", diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index c93ef075..d480fedf 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -24,6 +24,8 @@ import { CustomAuthorsListResponse } from '../model/customAuthorsListResponse'; import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore import { PersonBio } from '../model/personBio'; +// @ts-ignore +import { VerifiedOrganizationsResponse } from '../model/verifiedOrganizationsResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -747,4 +749,59 @@ export class PersonsService extends BaseService { ); } + /** + * Returns the organizations where a person is a verified staff member. + * @endpoint get /api/inse-service/person/{id}/verified-organizations + * @param id OpenAlex author ID + * @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 getVerifiedOrganizations(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getVerifiedOrganizations(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getVerifiedOrganizations(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getVerifiedOrganizations(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getVerifiedOrganizations.'); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/verified-organizations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 115b7196..beb566da 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -319,6 +319,8 @@ export * from './userRole'; export * from './validationError'; export * from './validationErrorLocInner'; export * from './value'; +export * from './verifiedOrganization'; +export * from './verifiedOrganizationsResponse'; export * from './work'; export * from './workBiblio'; export * from './workCitationNormalizedPercentile'; diff --git a/webapp/src/app/api/model/verifiedOrganization.ts b/webapp/src/app/api/model/verifiedOrganization.ts new file mode 100644 index 00000000..860589fc --- /dev/null +++ b/webapp/src/app/api/model/verifiedOrganization.ts @@ -0,0 +1,24 @@ +/** + * 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 VerifiedOrganization { + /** + * Display name of the verified organization. + */ + org_name: string; + org_uri?: string | null; + /** + * Path from the hierarchy root to the organization node. + */ + org_hierarchy_path?: Array; + verified_at?: string | null; +} + diff --git a/webapp/src/app/api/model/verifiedOrganizationsResponse.ts b/webapp/src/app/api/model/verifiedOrganizationsResponse.ts new file mode 100644 index 00000000..c7a2725c --- /dev/null +++ b/webapp/src/app/api/model/verifiedOrganizationsResponse.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { VerifiedOrganization } from './verifiedOrganization'; + + +export interface VerifiedOrganizationsResponse { + /** + * OpenAlex institution ID that the verified memberships belong to. + */ + institution_id?: string | null; + /** + * Organizations where the person has verified staff membership. + */ + organizations?: Array; +} + From 41cc3a7ac64fcee6c2431702c6182b7980232f8c Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 21:20:28 +0100 Subject: [PATCH 24/36] tests for verified organization and institution helper added --- .../inse/orgminer/test_institutions_helper.py | 32 +++++ .../persons/test_verified_organizations.py | 119 ++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 service/src/main/inse/orgminer/test_institutions_helper.py create mode 100644 service/src/main/inse/persons/test_verified_organizations.py diff --git a/service/src/main/inse/orgminer/test_institutions_helper.py b/service/src/main/inse/orgminer/test_institutions_helper.py new file mode 100644 index 00000000..da381940 --- /dev/null +++ b/service/src/main/inse/orgminer/test_institutions_helper.py @@ -0,0 +1,32 @@ +from inse.orgminer.institutions_helper import ( + normalize_org_uri, + strip_openalex_prefix, +) + + +def test_normalize_org_uri_matches_equivalent_hierarchy_links(): + assert ( + normalize_org_uri(" https://www.uni-due.de/zmb/ ") + == "https://www.uni-due.de/zmb" + ) + assert ( + normalize_org_uri("https://www.uni-due.de/zmb/index") + == "https://www.uni-due.de/zmb" + ) + assert ( + normalize_org_uri("https://www.uni-due.de/zmb/index/") + == "https://www.uni-due.de/zmb" + ) + + +def test_normalize_org_uri_returns_none_for_missing_values(): + assert normalize_org_uri(None) is None + assert normalize_org_uri(" ") is None + + +def test_strip_openalex_prefix_accepts_raw_and_full_author_ids(): + assert strip_openalex_prefix("A5018971503") == "A5018971503" + assert ( + strip_openalex_prefix("https://openalex.org/A5018971503") + == "A5018971503" + ) diff --git a/service/src/main/inse/persons/test_verified_organizations.py b/service/src/main/inse/persons/test_verified_organizations.py new file mode 100644 index 00000000..9cca3cbc --- /dev/null +++ b/service/src/main/inse/persons/test_verified_organizations.py @@ -0,0 +1,119 @@ +import asyncio + +from inse.model import ESCluster +from inse.persons import logic, service + + +def _hit( + *, + org_name: str, + org_uri: str | None, + verified_at: str | None = "2026-01-02T03:04:05Z", +) -> dict: + return { + "_source": { + "openalex_id": "https://openalex.org/A5018971503", + "org_name": org_name, + "org_uri": org_uri, + "org_hierarchy_path": ["Fakultät", org_name], + "verified_at": verified_at, + } + } + + +def test_get_verified_organizations_uses_person_id_field_and_deduplicates(monkeypatch): + calls: list[dict] = [] + + async def fake_search(**kwargs): + calls.append(kwargs) + return { + "hits": { + "hits": [ + _hit( + org_name="Zentrum für Mikroskopie", + org_uri="https://www.uni-due.de/zmb/", + ), + # Same organization from an older sha256-ID document. + _hit( + org_name="Zentrum für Mikroskopie", + org_uri="https://www.uni-due.de/zmb/index", + ), + _hit(org_name="Institut für Physik", org_uri=None), + _hit(org_name="Institut für Physik", org_uri=None), + ] + } + } + + monkeypatch.setattr(logic.elasticsearch, "search", fake_search) + + result = asyncio.run( + logic.get_verified_organizations("https://openalex.org/A5018971503") + ) + + assert len(calls) == 1 + assert calls[0]["index"] == logic.VERIFIED_PERSONS_INDEX + assert calls[0]["cluster"] == ESCluster.INSE + assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [ + "A5018971503", + "https://openalex.org/A5018971503", + ] + assert [organization.org_name for organization in result] == [ + "Zentrum für Mikroskopie", + "Institut für Physik", + ] + assert result[0].org_uri == "https://www.uni-due.de/zmb" + assert result[0].org_hierarchy_path == [ + "Fakultät", + "Zentrum für Mikroskopie", + ] + assert result[0].verified_at is not None + + +def test_get_verified_organizations_accepts_raw_author_id(monkeypatch): + calls: list[dict] = [] + + async def fake_search(**kwargs): + calls.append(kwargs) + return {"hits": {"hits": []}} + + monkeypatch.setattr(logic.elasticsearch, "search", fake_search) + + assert asyncio.run(logic.get_verified_organizations(" A5018971503/ ")) == [] + assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [ + "A5018971503", + "https://openalex.org/A5018971503", + ] + + +def test_get_verified_organizations_returns_empty_on_search_failure(monkeypatch): + async def failing_search(**kwargs): + raise RuntimeError("INSE is unavailable") + + monkeypatch.setattr(logic.elasticsearch, "search", failing_search) + + assert asyncio.run(logic.get_verified_organizations("A5018971503")) == [] + + +def test_get_verified_organizations_skips_search_without_author_id(monkeypatch): + async def unexpected_search(**kwargs): + raise AssertionError("search must not be called without an author id") + + monkeypatch.setattr(logic.elasticsearch, "search", unexpected_search) + + assert asyncio.run(logic.get_verified_organizations(" ")) == [] + + +def test_service_response_includes_verified_data_institution(monkeypatch): + async def fake_get_verified_organizations(author_id: str): + return [] + + monkeypatch.setattr( + logic, "get_verified_organizations", fake_get_verified_organizations + ) + + response = asyncio.run( + service.get_verified_organizations(id="A5018971503") + ) + + assert response.institution_id == logic.VERIFIED_PERSONS_INSTITUTION_ID + assert response.organizations == [] From 6b6a5c7cffc35f59c92eec306fad1855ef0c56b8 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 21:25:51 +0100 Subject: [PATCH 25/36] added organization badge to person profile --- .../app/modules/person/person.component.html | 74 ++++++++++++++----- .../app/modules/person/person.component.scss | 49 ++++++++++++ .../app/modules/person/person.component.ts | 74 ++++++++++++++++++- webapp/src/app/resolvers/person.resolver.ts | 15 +++- 4 files changed, 190 insertions(+), 22 deletions(-) diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 27f9bec5..2fafa6f6 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -29,27 +29,61 @@ }}
- @if (resolvedInstitution(); as inst) { + @if (resolvedInstitution() || verifiedOrganizations().length > 0) {
- - @if (secondaryInstitutions().length > 0) { - + @if (resolvedInstitution(); as inst) { + + @if (secondaryInstitutions().length > 0) { + + } + } + @for (org of verifiedOrganizations(); track $index) { + @if (canOpenOrganizationHierarchy(org)) { + + } @else { + + {{ VERIFIED_ICON }} + {{ org.org_name }} + + } }
} diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index 538226ca..d5a38c0f 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -146,6 +146,55 @@ font-size: 13px; } +.verified-org-chip { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 24px; + max-width: 100%; + padding: 2px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: var(--sg-surface-muted); + color: var(--sg-text); + font-size: 13px; + font-weight: 600; + line-height: 1.2; + text-decoration: none; + transition: + border-color 0.15s, + background 0.15s; + + span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + mat-icon { + flex: 0 0 auto; + width: 16px; + height: 16px; + font-size: 16px; + color: var(--sg-success); + } + + &[type='button'] { + cursor: pointer; + } + + &[type='button']:hover, + &[type='button']:focus-visible { + border-color: var(--sg-success); + background: var(--sg-primary-soft); + outline: none; + } + + &.static { + cursor: default; + } +} + .stats-line { display: flex; align-items: center; diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index c096b160..f69feef5 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -39,12 +39,17 @@ import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/care import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component'; import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; import { PersonInstitutionTooltipListComponent } from '../../shared/ui/person-institution-tooltip-list/person-institution-tooltip-list.component'; -import { DehydratedInstitution, WorksService } from '../../api'; +import { + DehydratedInstitution, + VerifiedOrganization, + WorksService, +} from '../../api'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { PersonBioResolved } from '../../resolvers/person-bio.resolver'; import { PersonDataResolved } from '../../resolvers/person.resolver'; import { BookmarkService } from '../../shared/services/bookmark.service'; import { AuthorAffiliationService } from '../../shared/services/author-affiliation.service'; +import { CredentialService } from '../../shared/services/credential.service'; import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver'; import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { @@ -73,6 +78,16 @@ import { } from '../../shared/ui/icons'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; +/** Accepts raw and full-URL OpenAlex IDs, e.g. `I123` or `.../I123`. */ +const normalizeInstitutionId = ( + value: string | null | undefined, +): string => + (value ?? '') + .trim() + .replace(/^https:\/\/openalex\.org\//i, '') + .replace(/\/+$/, '') + .toUpperCase(); + @Component({ selector: 'app-person', imports: [ @@ -116,6 +131,7 @@ export class PersonComponent { private readonly destroyRef = inject(DestroyRef); readonly bookmarkService = inject(BookmarkService); private readonly authorAffiliationService = inject(AuthorAffiliationService); + private readonly credentialService = inject(CredentialService); canFetchGdprRelevantData = input.required(); @@ -206,6 +222,33 @@ export class PersonComponent { .subscribe(); } + canOpenOrganizationHierarchy(organization: VerifiedOrganization): boolean { + return ( + this.canOpenVerifiedOrganizationHierarchy() && + !!organization.org_uri && + (organization.org_hierarchy_path?.length ?? 0) > 0 + ); + } + + openOrganizationHierarchy(organization: VerifiedOrganization): void { + if (!this.canOpenOrganizationHierarchy(organization)) return; + void this.router.navigate(['/hierarchy'], { + queryParams: { + orgFocus: organization.org_uri, + orgFocusPath: JSON.stringify(organization.org_hierarchy_path ?? []), + hierarchyExpanded: true, + organizationExpanded: false, + orgUrl: null, + orgName: null, + orgExpanded: null, + orgSelectionCategory: null, + orgSelectionIndex: null, + classifiedCategory: null, + classifiedPage: null, + }, + }); + } + readonly personBio = toSignal( combineLatest([this.activatedRoute.data, toObservable(this.person)]).pipe( switchMap(([data, person]) => { @@ -249,6 +292,35 @@ export class PersonComponent { readonly secondaryInstitutions = computed(() => this.authorAffiliationService.resolveSecondaryInstitutions(this.person()), ); + readonly verifiedOrganizationData = toSignal( + this.activatedRoute.data.pipe( + switchMap((data) => { + const resolved = data['personData'] as PersonDataResolved | undefined; + return resolved?.verifiedOrganizations$ ?? of(null); + }), + ), + { initialValue: null }, + ); + readonly verifiedOrganizations = computed( + () => this.verifiedOrganizationData()?.organizations ?? [], + ); + /** + * Verified organizations come from one institution's OrgMiner data. Only + * users of that institution have a hierarchy where the nodes can be found. + */ + readonly canOpenVerifiedOrganizationHierarchy = computed(() => { + const userInstitutionId = normalizeInstitutionId( + this.credentialService.effectiveInstitutionId(), + ); + const dataInstitutionId = normalizeInstitutionId( + this.verifiedOrganizationData()?.institution_id, + ); + return ( + !!userInstitutionId && + !!dataInstitutionId && + userInstitutionId === dataInstitutionId + ); + }); readonly worksCount = computed(() => this.person()?.works_count ?? null); readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null); readonly h_index = computed( diff --git a/webapp/src/app/resolvers/person.resolver.ts b/webapp/src/app/resolvers/person.resolver.ts index 56dcbfbc..4b2e5268 100644 --- a/webapp/src/app/resolvers/person.resolver.ts +++ b/webapp/src/app/resolvers/person.resolver.ts @@ -4,6 +4,7 @@ import { CompanyConnectionsService, CustomAuthorsListResponse, PersonsService, + VerifiedOrganizationsResponse, } from '../api'; import { Observable, @@ -20,6 +21,7 @@ import { toObservable } from '@angular/core/rxjs-interop'; export interface PersonDataResolved { personData$: Observable; companyConnectionsAvailable$: Observable; + verifiedOrganizations$: Observable; } export const personResolver: ResolveFn = (route, state) => { @@ -38,6 +40,7 @@ export const personResolver: ResolveFn = (route, state) => { return { personData$: of(null), companyConnectionsAvailable$: of(false), + verifiedOrganizations$: of(null), }; } @@ -51,6 +54,16 @@ export const personResolver: ResolveFn = (route, state) => { shareReplay(1), ); + const verifiedOrganizations$ = personsService + .getVerifiedOrganizations(authorId) + .pipe( + catchError((err) => { + console.error('Failed to load verified organizations:', err); + return of(null); + }), + shareReplay(1), + ); + const companyConnectionsAvailable$ = toObservable( credentialService.effectiveInstitutionId, ).pipe( @@ -76,5 +89,5 @@ export const personResolver: ResolveFn = (route, state) => { shareReplay({ bufferSize: 1, refCount: true }), ); - return { personData$, companyConnectionsAvailable$ }; + return { personData$, companyConnectionsAvailable$, verifiedOrganizations$ }; }; From d60c17abf497d22719c86fa4ea5eb3b031d64d11 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 21:28:42 +0100 Subject: [PATCH 26/36] added highlighting for organization on navigation --- .../hierarchy-chart.component.ts | 257 +++++++++++++++++- .../modules/hierarchy/hierarchy.component.ts | 4 + 2 files changed, 259 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts index 01ce9d25..ad9ddcc4 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts +++ b/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts @@ -50,6 +50,9 @@ interface TreeLevel { const QUERY_PARAM_PATH = 'path'; const QUERY_PARAM_LANG = 'lang'; +const QUERY_PARAM_ORGANIZATION_FOCUS = 'orgFocus'; +const QUERY_PARAM_ORGANIZATION_FOCUS_PATH = 'orgFocusPath'; +const QUERY_PARAM_ORGANIZATION_URL = 'orgUrl'; const LEAF_ROW_HEIGHT = 22; const MIN_TREE_HEIGHT = 200; @@ -99,6 +102,8 @@ export class HierarchyChartComponent implements OnInit { readonly loading = signal(true); readonly lang = signal<'de' | 'en'>('de'); readonly levels = signal([]); + /** Node highlighted after a badge navigation or an analysis click. */ + readonly highlightedId = signal(null); private readonly chartHost = viewChild>('chartHost'); @@ -109,6 +114,10 @@ export class HierarchyChartComponent implements OnInit { private readonly snackBar = inject(MatSnackBar); private readonly idMap = new Map(); + /** Several hierarchy nodes can share one URL; keep every candidate. */ + private readonly urlToNodeIds = new Map(); + /** Last `orgFocus` value + path that was applied, so unrelated query changes don't re-focus. */ + private lastFocusKey: string | null = null; universityRoot: RawNode | null = null; /** @@ -187,7 +196,37 @@ export class HierarchyChartComponent implements OnInit { this.isOwnNavigation = false; return; } + + const langParam = params.get(QUERY_PARAM_LANG); + if (langParam === 'de' || langParam === 'en') { + this.lang.set(langParam); + } + + const focus = this.normalizeOrgUrl( + params.get(QUERY_PARAM_ORGANIZATION_FOCUS), + ); + const focusPath = this.parseFocusPath( + params.get(QUERY_PARAM_ORGANIZATION_FOCUS_PATH), + ); + const focusKey = focus + ? `${focus}\u0000${focusPath.join('\u0000')}` + : null; + if ( + focus && + focusKey !== this.lastFocusKey && + this.focusOrganization(focus, focusPath) + ) { + this.lastFocusKey = focusKey; + return; + } + if (!focus) { + this.lastFocusKey = null; + } + this.restoreFromUrl(params); + this.highlightAnalyzedOrganization( + params.get(QUERY_PARAM_ORGANIZATION_URL), + ); }); this.initialized = true; } @@ -241,6 +280,7 @@ export class HierarchyChartComponent implements OnInit { const copy = structuredClone(children ?? []) as RawNode[]; this.idMap.clear(); + this.urlToNodeIds.clear(); this.assignIds(copy, 'root'); this.universityRoot = { @@ -267,6 +307,16 @@ export class HierarchyChartComponent implements OnInit { node.id = id; if (registerInMap) { this.idMap.set(id, node); + for (const link of [node.link_de, node.link_en]) { + const normalized = this.normalizeOrgUrl(link); + if (!normalized) continue; + const candidates = this.urlToNodeIds.get(normalized); + if (candidates) { + if (!candidates.includes(id)) candidates.push(id); + } else { + this.urlToNodeIds.set(normalized, [id]); + } + } } if (node.children?.length) { this.assignIds(node.children, id, registerInMap); @@ -301,6 +351,184 @@ export class HierarchyChartComponent implements OnInit { this.updateQueryParams(); } + /* --------------------------- organization focus --------------------------- */ + + /** + * Normalizes a hierarchy organization URL the same way the backend does: + * trim, drop trailing slashes and the common `/index` suffix. + */ + private normalizeOrgUrl(value: string | null | undefined): string | null { + if (!value) return null; + const normalized = value.trim().replace(/\/+$/, ''); + const withoutIndex = normalized.endsWith('/index') + ? normalized.slice(0, -'/index'.length).replace(/\/+$/, '') + : normalized; + return withoutIndex || null; + } + + private findNodeIdByUrl( + value: string | null | undefined, + expectedPath: string[] = [], + preferVisible = false, + ): string | null { + const normalized = this.normalizeOrgUrl(value); + const candidates = normalized + ? (this.urlToNodeIds.get(normalized) ?? []) + : []; + if (!candidates.length) return null; + + // Hierarchy URLs are not unique (several nodes can link to the same site), + // so the index-provided name path decides which node is meant. + if (expectedPath.length) { + const pathMatch = candidates.find((id) => + this.matchesNamePath(id, expectedPath), + ); + if (pathMatch) return pathMatch; + } + + // Reloads only carry `orgUrl`; prefer the candidate on the open path. + if (preferVisible) { + const visible = candidates.find((id) => this.isNodeVisible(id)); + if (visible) return visible; + } + + return candidates[0]; + } + + /** Parses the hierarchy path (`orgFocusPath`) sent by the person badge. */ + private parseFocusPath(value: string | null | undefined): string[] { + if (!value) return []; + try { + const parsed: unknown = JSON.parse(value); + if (!Array.isArray(parsed)) return []; + return parsed + .filter((segment): segment is string => typeof segment === 'string') + .map((segment) => segment.trim()) + .filter(Boolean); + } catch { + return []; + } + } + + /** Ancestor + node names from the faculty down (synthetic `root` excluded). */ + private nodeNamePath(nodeId: string): RawNode[] { + return [...this.ancestorIds(nodeId).slice(1), nodeId] + .map((id) => this.idMap.get(id)) + .filter((node): node is RawNode => !!node); + } + + private matchesNamePath(nodeId: string, expectedPath: string[]): boolean { + if (!expectedPath.length) return false; + const actual = this.nodeNamePath(nodeId); + if (actual.length !== expectedPath.length) return false; + return expectedPath.every((name, index) => + this.nodeMatchesName(actual[index], name), + ); + } + + private nodeMatchesName(node: RawNode, expected: string): boolean { + const normalize = (value: string | null | undefined) => + (value ?? '').replace(/\s+/g, ' ').trim().toLocaleLowerCase(); + const wanted = normalize(expected); + return ( + normalize(node.name_de) === wanted || normalize(node.name_en) === wanted + ); + } + + /** Mirrors `buildLevel`: a level shows its children and group grandchildren. */ + private levelRendersNode(levelId: string, nodeId: string): boolean { + const level = this.idMap.get(levelId); + if (!level) return false; + if (level.id === nodeId) return true; + + for (const child of level.children ?? []) { + if (child.id === nodeId) return true; + const isGroup = child.type === 'institutes' || child.type === 'chairs'; + if ( + isGroup && + child.children?.some((grandchild) => grandchild.id === nodeId) + ) { + return true; + } + } + return false; + } + + private isNodeVisible(nodeId: string): boolean { + return this.levels().some((level) => + this.levelRendersNode(level.id, nodeId), + ); + } + + /** Positional parent ids of a node, e.g. `root-2-0-5` -> `root`, `root-2`, `root-2-0`. */ + private ancestorIds(nodeId: string): string[] { + const ids = ['root']; + const parts = nodeId.split('-'); + for (let index = 2; index < parts.length; index++) { + ids.push(parts.slice(0, index).join('-')); + } + return ids; + } + + /** + * Opens the levels that display the requested organization and highlights + * its node. Used by the person-page badge (`orgFocus` query param). + */ + private focusOrganization( + orgUrl: string, + expectedPath: string[] = [], + ): boolean { + const nodeId = this.findNodeIdByUrl(orgUrl, expectedPath); + if (!nodeId) return false; + + // Open the faculty level, not the group directly above the target: the + // faculty chart shows the organization inside the full faculty subtree. + // For deeper nodes, keep opening levels until the target is rendered. + const fullPath = [...this.ancestorIds(nodeId), nodeId]; + let lastLevelIndex = fullPath.findIndex( + (id) => this.idMap.get(id)?.type === 'faculty', + ); + if (lastLevelIndex < 0) { + lastLevelIndex = Math.max(0, fullPath.length - 2); + } + while ( + lastLevelIndex < fullPath.length - 1 && + !this.levelRendersNode(fullPath[lastLevelIndex], nodeId) + ) { + lastLevelIndex++; + } + + const levels = fullPath + .slice(0, lastLevelIndex + 1) + .map((id) => this.idMap.get(id)) + .filter((node): node is RawNode => !!node) + .map((node) => this.buildLevel(node)); + if (!levels.length) return false; + + this.highlightedId.set(nodeId); + this.levels.set(levels); + this.updateQueryParams(); + return true; + } + + /** Keeps the analyzed organization highlighted after query-param navigation. */ + private highlightAnalyzedOrganization(orgUrl: string | null): void { + const nodeId = this.findNodeIdByUrl(orgUrl, [], true); + if (!nodeId || nodeId === this.highlightedId()) return; + this.highlightedId.set(nodeId); + if (this.universityRoot) { + this.rebuildLevelsKeepingPath(); + } + } + + private setHighlightedNode(nodeId: string | null): void { + if (this.highlightedId() === nodeId) return; + this.highlightedId.set(nodeId); + if (this.universityRoot) { + this.rebuildLevelsKeepingPath(); + } + } + /** Writes the current levels path + language into the URL as query params. */ private updateQueryParams(): void { const path = this.levels() @@ -386,6 +614,7 @@ export class HierarchyChartComponent implements OnInit { } private onLeafSelect(raw: RawNode): void { + this.setHighlightedNode(raw.id); this.analyzeOrgEvent.emit({ name: raw.name_de ?? raw.name_en ?? '', url: raw.link_de ?? raw.link_en ?? '', @@ -394,6 +623,18 @@ export class HierarchyChartComponent implements OnInit { /* ------------------------------ tree building ----------------------------- */ + /** Extra ECharts item style that marks the focused/analyzed node. */ + private highlightStyle(nodeId: string): Record { + if (this.highlightedId() !== nodeId) return {}; + const warning = this.chartTheme.colors().warning; + return { + borderColor: warning, + borderWidth: 3, + shadowBlur: 10, + shadowColor: warning, + }; + } + private getLink(raw: RawNode): string | null | undefined { return this.lang() === 'en' ? (raw.link_en ?? raw.link_de) @@ -428,6 +669,7 @@ export class HierarchyChartComponent implements OnInit { (isGroup ? this.chartTheme.colors().blueHighlight : this.chartTheme.colors().success), + ...this.highlightStyle(raw.id), }, }; @@ -451,7 +693,15 @@ export class HierarchyChartComponent implements OnInit { } private buildLevel(raw: RawNode): TreeLevel { - const children = (raw.children || []).map((c) => this.toChartNode(c, true)); + // Leaves inherit the icon of the group that contains them, including the + // direct children of a group that is itself the root of this level. + const parentType = + raw.type === 'institutes' || raw.type === 'chairs' + ? raw.type + : undefined; + const children = (raw.children || []).map((c) => + this.toChartNode(c, true, parentType), + ); const rootData = { id: raw.id, @@ -459,7 +709,10 @@ export class HierarchyChartComponent implements OnInit { nodeType: raw.type, hasChildren: true, link: this.getLink(raw), - itemStyle: { color: raw['color'] || this.chartTheme.colors().primary }, + itemStyle: { + color: raw['color'] || this.chartTheme.colors().primary, + ...this.highlightStyle(raw.id), + }, children, }; diff --git a/webapp/src/app/modules/hierarchy/hierarchy.component.ts b/webapp/src/app/modules/hierarchy/hierarchy.component.ts index ab3ff918..2499b427 100644 --- a/webapp/src/app/modules/hierarchy/hierarchy.component.ts +++ b/webapp/src/app/modules/hierarchy/hierarchy.component.ts @@ -21,6 +21,8 @@ import { HierarchySuggestion } from '../../api/model/hierarchySuggestion'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; const ORGANIZATION_URL_PARAM = 'orgUrl'; const ORGANIZATION_NAME_PARAM = 'orgName'; +const ORGANIZATION_FOCUS_PARAM = 'orgFocus'; +const ORGANIZATION_FOCUS_PATH_PARAM = 'orgFocusPath'; const ORGMINER_EXPANDED_PARAM = 'orgExpanded'; const ORGMINER_SELECTION_CATEGORY_PARAM = 'orgSelectionCategory'; const ORGMINER_SELECTION_INDEX_PARAM = 'orgSelectionIndex'; @@ -119,6 +121,8 @@ export class HierarchyComponent implements OnInit { queryParams: { [ORGANIZATION_URL_PARAM]: organizationUrl, [ORGANIZATION_NAME_PARAM]: org.name, + [ORGANIZATION_FOCUS_PARAM]: null, + [ORGANIZATION_FOCUS_PATH_PARAM]: null, [ORGMINER_EXPANDED_PARAM]: null, [ORGMINER_SELECTION_CATEGORY_PARAM]: null, [ORGMINER_SELECTION_INDEX_PARAM]: null, From 728d8c96465bcc5bb9f790ccd3476fd980b1a0ec Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 23:07:21 +0100 Subject: [PATCH 27/36] added to_person_profile navigation --- .../founder-dashboard.component.html | 11 ++++++- .../founder-dashboard.component.ts | 15 ++++++--- .../researcher-network.component.html | 15 ++++++++- .../researcher-network.component.scss | 18 +++++++++++ .../researcher-network.component.ts | 31 ++++++++++++++----- 5 files changed, 76 insertions(+), 14 deletions(-) diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html index aacbb981..aedfa295 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html @@ -137,7 +137,16 @@
Ausgewählt -

{{ row.name }}

+ + +

{{ row.name }}

+
Math.max(50, Math.min(100, toNumber(this.queryParams().get('threshold')) ?? 90)), + readonly threshold = computed(() => + Math.max( + 50, + Math.min(100, toNumber(this.queryParams().get('threshold')) ?? 90), + ), ); readonly screened = computed( () => this.queryParams().get('screened') === 'true', diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html index 1743f8ab..6e70c284 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html @@ -1,9 +1,22 @@
+

+ @if (researcher()?.author_id; as authorId) { + + {{ name() }} + + } @else { + {{ name() }} + } +

@if (!unavailable()) {
@if (careerBucket()) { diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss index 4fb68456..cca692e1 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss @@ -216,7 +216,25 @@ line-height: 1.4; } } +.author-name { + margin: 0; + color: var(--sg-text); +} +.author-name__link { + color: inherit; + text-decoration: none; + + &:hover { + text-decoration: underline; + } + + &:focus-visible { + border-radius: 2px; + outline: 2px solid var(--sg-blue-highlight); + outline-offset: 2px; + } +} .metric-label { cursor: help; text-decoration: underline dotted; diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts index ffc1ade8..16981eb3 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts @@ -1,6 +1,13 @@ -import { Component, computed, inject, input, TemplateRef, viewChild } from '@angular/core'; +import { + Component, + computed, + inject, + input, + TemplateRef, + viewChild, +} from '@angular/core'; import { CommonModule } from '@angular/common'; -import { Router, RouterModule } from '@angular/router'; +import { Router, RouterLink } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; @@ -38,6 +45,8 @@ import { PERSON_OFF_ICON, WARNING_ICON, } from '../../../shared/ui/icons'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; +import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component'; const ROLE_ORDER = ['ego', 'cohort', 'mentee', 'industry', 'external']; const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen'; @@ -70,7 +79,6 @@ interface MetricGroup { standalone: true, imports: [ CommonModule, - RouterModule, MatButtonModule, MatCardModule, MatIconModule, @@ -81,6 +89,8 @@ interface MetricGroup { ChipComponent, MultiplierRoleScoresComponent, PageContainerComponent, + RouterLink, + ComponentTooltipDirective, ], templateUrl: './researcher-network.component.html', styleUrl: './researcher-network.component.scss', @@ -91,7 +101,7 @@ export class ResearcherNetworkComponent { readonly PERSON_OFF_ICON = PERSON_OFF_ICON; readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON; readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON; - + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; readonly page = input.required(); private readonly router = inject(Router); @@ -146,10 +156,14 @@ export class ResearcherNetworkComponent { this.researcher()?.author_id ?? 'Unbekannt', ); - readonly careerBucket = computed(() => this.researcher()?.career_bucket ?? null); + readonly careerBucket = computed( + () => this.researcher()?.career_bucket ?? null, + ); readonly activeYears = computed(() => this.researcher()?.active_years ?? 0); readonly nWorks = computed(() => this.researcher()?.n_works ?? 0); - readonly suspicious = computed(() => this.researcher()?.suspicious_profile ?? false); + readonly suspicious = computed( + () => this.researcher()?.suspicious_profile ?? false, + ); readonly tags = computed(() => this.researcher()?.tags ?? []); readonly tagLabel = tagLabel; readonly tagDescription = tagDescription; @@ -189,8 +203,9 @@ export class ResearcherNetworkComponent { private readonly metricTemplate = viewChild.required>('metricTemplate'); - private readonly metricValueTemplate = - viewChild.required>('metricValueTemplate'); + private readonly metricValueTemplate = viewChild.required< + TemplateRef + >('metricValueTemplate'); private readonly metricRankTemplate = viewChild.required>('metricRankTemplate'); private readonly metricHeader = From d1827cf86b6e512c173b2735dce6ce0513b14a49 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 17 Nov 2026 23:07:34 +0100 Subject: [PATCH 28/36] new model files added --- webapp/src/app/api/.openapi-generator/FILES | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 26cb2bb5..f4c406bc 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -356,6 +356,8 @@ model/userRole.ts model/validationError.ts model/validationErrorLocInner.ts model/value.ts +model/verifiedOrganization.ts +model/verifiedOrganizationsResponse.ts model/work.ts model/workBiblio.ts model/workCitationNormalizedPercentile.ts From dc79d16dfba8649b43de3520a964d8e84f3b2735 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 15:10:22 +0100 Subject: [PATCH 29/36] removed "suspicious profile" note next to person names --- .../founder-potential.utils.ts | 9 -------- .../multipliers-dashboard.component.scss | 14 ------------ .../multipliers-dashboard.component.ts | 1 - .../researcher-network.component.html | 11 ---------- .../researcher-network.component.scss | 22 ------------------- .../researcher-network.component.ts | 8 ------- .../multiplier-network-graph.component.ts | 4 ---- 7 files changed, 69 deletions(-) diff --git a/webapp/src/app/modules/founder-potential/founder-potential.utils.ts b/webapp/src/app/modules/founder-potential/founder-potential.utils.ts index fc11b3c4..73d36de3 100644 --- a/webapp/src/app/modules/founder-potential/founder-potential.utils.ts +++ b/webapp/src/app/modules/founder-potential/founder-potential.utils.ts @@ -92,15 +92,6 @@ export const METRIC_GROUP_META: Record< }, }; -/** German labels for the funnel stages, keyed by their stable key. */ -export const FUNNEL_STAGE_LABELS: Record = { - ALL: 'Alle Forschenden im Index', - IN_POPULATION: 'Vom Modell bewertbar (mind. 4 Publikationen)', - NOT_SUSPICIOUS: 'Kein zusammengeführtes Profil', - CAREER_AGE_PLAUSIBLE: 'Plausible Karrieredauer (max. 40 Jahre)', - MIN_PUBLICATIONS: 'Mind. 7 Publikationen', -}; - /** Ordered metric definitions for the researcher detail table. */ export interface MetricDef { key: keyof ResearcherMetrics; diff --git a/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.scss b/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.scss index a2cfad3f..73836ea7 100644 --- a/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.scss +++ b/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.scss @@ -78,20 +78,6 @@ } } -.warning { - display: inline-flex; - align-items: center; - gap: 3px; - color: var(--sg-warning); - cursor: help; - - &__icon { - width: 13px; - height: 13px; - font-size: 13px; - } -} - .th-help { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.ts b/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.ts index 7b04cf8b..cdcdc460 100644 --- a/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.ts +++ b/webapp/src/app/modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component.ts @@ -12,7 +12,6 @@ import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; - import { MultiplierTag, ResearcherSummary, diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html index 6e70c284..bacf3390 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.html @@ -29,17 +29,6 @@ {{ fmtInt(nWorks()) }} Publikationen · {{ fmtInt(activeYears()) }} aktive Jahre - @if (suspicious()) { - - {{ WARNING_ICON }} - Zusammengeführtes Profil · Daten vorsichtig interpretieren - {{ HELP_OUTLINE_ICON }} - - }
@if (tags().length) {
diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss index cca692e1..2a0ae208 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.scss @@ -27,28 +27,6 @@ margin: 2px 0 8px; } -.suspicious { - display: inline-flex; - align-items: center; - gap: 4px; - color: var(--sg-error); - font-size: 12.5px; - cursor: help; - - mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - } - - .help-icon { - color: var(--sg-text-soft); - font-size: 15px; - width: 15px; - height: 15px; - } -} - .tags { display: flex; flex-wrap: wrap; diff --git a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts index 16981eb3..554992dc 100644 --- a/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts +++ b/webapp/src/app/modules/founder-potential/researcher-network/researcher-network.component.ts @@ -43,7 +43,6 @@ import { HELP_OUTLINE_ICON, INFO_OUTLINE_ICON, PERSON_OFF_ICON, - WARNING_ICON, } from '../../../shared/ui/icons'; import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component'; @@ -97,7 +96,6 @@ interface MetricGroup { }) export class ResearcherNetworkComponent { readonly ARROW_BACK_ICON = ARROW_BACK_ICON; - readonly WARNING_ICON = WARNING_ICON; readonly PERSON_OFF_ICON = PERSON_OFF_ICON; readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON; readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON; @@ -161,9 +159,6 @@ export class ResearcherNetworkComponent { ); readonly activeYears = computed(() => this.researcher()?.active_years ?? 0); readonly nWorks = computed(() => this.researcher()?.n_works ?? 0); - readonly suspicious = computed( - () => this.researcher()?.suspicious_profile ?? false, - ); readonly tags = computed(() => this.researcher()?.tags ?? []); readonly tagLabel = tagLabel; readonly tagDescription = tagDescription; @@ -173,9 +168,6 @@ export class ResearcherNetworkComponent { readonly pageTooltip = 'Das Netzwerk zeigt, mit wem diese Person gemeinsam publiziert hat. Je dicker die Linie, desto häufiger haben die beiden zusammengearbeitet.'; - readonly suspiciousTooltip = - 'Bei diesem Profil wurden vermutlich mehrere Personen vermischt, zum Beispiel wegen gleicher Namen oder einer unplausibel langen Karriere. Die Angaben zu Publikationen, Netzwerk und Rollen sind deshalb unsicher.'; - readonly rolesTooltip = 'Wie stark die drei Rollen ausgeprägt sind. Ab 85 % wird ein Badge vergeben.'; diff --git a/webapp/src/app/shared/ui/multiplier-network-graph/multiplier-network-graph.component.ts b/webapp/src/app/shared/ui/multiplier-network-graph/multiplier-network-graph.component.ts index 92f46369..e2597b56 100644 --- a/webapp/src/app/shared/ui/multiplier-network-graph/multiplier-network-graph.component.ts +++ b/webapp/src/app/shared/ui/multiplier-network-graph/multiplier-network-graph.component.ts @@ -107,9 +107,6 @@ export class MultiplierNetworkGraphComponent { if (d.role === 'ego' && d.nWorks != null) { lines.push(`${d.nWorks} Publikationen`); } - if (d.suspicious) { - lines.push('Profil möglicherweise zusammengeführt'); - } return lines.join('
'); }, }, @@ -167,7 +164,6 @@ export class MultiplierNetworkGraphComponent { role, inst: node.inst ?? '', activeYears, - suspicious: node.suspicious ?? false, nWorks: isEgo ? nWorks : undefined, symbolSize: isEgo ? 24 : clamp(8 + activeYears * 1.1, 8, 26), itemStyle: { From 48a10dbca39b1e64256ee618083b6035b07f1a20 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 15:10:58 +0100 Subject: [PATCH 30/36] threshold is opt-in now --- webapp/src/app/resolvers/founder-statistics.resolver.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/resolvers/founder-statistics.resolver.ts b/webapp/src/app/resolvers/founder-statistics.resolver.ts index c2c1643a..b1c9a42d 100644 --- a/webapp/src/app/resolvers/founder-statistics.resolver.ts +++ b/webapp/src/app/resolvers/founder-statistics.resolver.ts @@ -6,12 +6,15 @@ import { FounderStatistics, MultiplicatorsService } from '../api'; * Founder-potential statistics for the dashboard (KPIs, funnel, career-stage * and research-area breakdowns). Re-resolved when the `threshold` query param * changes, so the shortlist counts always match the slider in the URL. + * + * The threshold is opt-in. When the param is absent there is no shortlist cut, + * so 0 is used: every scored profile counts, matching the unfiltered list. */ export const founderStatisticsResolver: ResolveFn = ( route, ) => { const service = inject(MultiplicatorsService); - const threshold = toNumber(route.queryParamMap.get('threshold')) ?? 90; + const threshold = toNumber(route.queryParamMap.get('threshold')) ?? 0; // Remaining cutoffs mirror the backend defaults; only the threshold is // exposed to the user for now. return service.getFounderStatistics(threshold, 7, 0.7, 40, 40); From e9a72f88c1330cac008f915214c7d72b57c3abbc Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 15:12:27 +0100 Subject: [PATCH 31/36] moved selected row to table detail row --- .../founder-dashboard.component.html | 344 +++++++----------- .../founder-dashboard.component.scss | 92 ++--- .../founder-dashboard.component.ts | 176 ++++----- 3 files changed, 240 insertions(+), 372 deletions(-) diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html index aedfa295..490c615f 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html @@ -13,7 +13,7 @@ Erklären
- @if (hasData() && hasScores()) { + @if (hasData()) {
-
-
- - Mindestwert - - {{ INFO_OUTLINE_ICON }} - - - - - - {{ thresholdDraft() }} - - Auffällige Profile ausblenden - - - {{ fmtInt(total()) }} {{ total() === 1 ? 'Person' : 'Personen' }} - + + +
+ {{ fmtInt(total()) }} {{ total() === 1 ? 'Person' : 'Personen' }}
@@ -110,14 +67,13 @@ + queryParamSortDirectionKey="sortOrder" /> } @else {

{{ emptyListMessage() }}

- @if (threshold() > 50) { + @if (thresholdEnabled() && threshold() > 50) {
- } @else if (hasData()) { - - - {{ FOUNDER_ICON }} -

Noch keine Gründungspotenzial-Scores

-

- Für die {{ universityName() }} liegen - Forschungsdaten vor, aber die Gründungspotenzial-Auswertung wurde - noch nicht berechnet. Sobald sie vorliegt, erscheinen hier die - Kandidat:innen und ihre Werte. -

-
-
} @else { @@ -322,7 +127,17 @@ - {{ fmt1(row.score) }} + @if (row.score === null) { + + (nicht bewertet) + + } @else { + {{ fmt1(row.score) }} + } @@ -383,3 +198,124 @@ + + +
+
+ Details + + +

{{ row.name }}

+
+
+ + {{ row.candidate.career_bucket ?? '–' }} + + @if (row.areaLabel) { + · {{ row.areaLabel }} + } + · {{ fmtInt(row.candidate.active_years) }} Jahre mit Publikationen +
+
+ +

+ Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten. 90 + heißt: stärker als 90 % der Vergleichsgruppe. +

+ +
+
+ Potenzial + @if (row.score === null) { + (nicht bewertet) + } @else { + {{ fmt1(row.score) }} + } +
+
+ Signal 1 Jahr + {{ fmt1(row.within[0]) }} +
+
+ Signal 3 Jahre + {{ fmt1(row.within[1]) }} +
+
+ Signal 5 Jahre + {{ fmt1(row.within[2]) }} +
+
+ +
+ + Publikationen + {{ fmtInt(row.candidate.founder_features?.publications) }} + + + Patente + {{ fmtInt(row.candidate.founder_features?.patents) }} + + + Arbeiten mit Industrie + {{ + fmtInt(row.candidate.founder_features?.industry_collab_papers) + }} + + + Förderprojekte + {{ fmtInt(row.candidate.founder_features?.grants) }} + + + Aktive Jahre + {{ fmtInt(row.candidate.active_years) }} + +
+
+
diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss index d2590d8c..6fd17256 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss @@ -77,42 +77,10 @@ } } -.controls { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 10px 22px; - margin-bottom: 16px; - padding: 12px 14px; - border: 1px solid var(--sg-border); - border-radius: 10px; - background: var(--sg-surface-muted); - font-size: 13px; - - &__range { - display: inline-flex; - align-items: center; - gap: 6px; - color: var(--sg-text-muted); - } - - &__value { - display: inline-block; - min-width: 24px; - color: var(--sg-text); - font-weight: 700; - font-variant-numeric: tabular-nums; - } - - &__count { - margin-left: auto; - color: var(--sg-text-soft); - } - - &__slider { - width: 220px; - min-width: 160px; - } +.list-count { + margin: 1rem 0; + font-size: 0.875rem; + color: var(--sg-text-soft); } .list-card { @@ -142,6 +110,10 @@ color: var(--sg-text); } + tr.detail-row .mat-mdc-cell { + padding: 0; + } + .mat-column-name { width: 32%; } @@ -205,7 +177,7 @@ } .list__career, -.card__career { +.row-detail__career { cursor: help; text-decoration: underline dotted; text-underline-offset: 2px; @@ -220,6 +192,14 @@ text-align: right; } +.list__score-missing { + color: var(--sg-text-soft); + font-size: 11.5px; + font-style: italic; + cursor: help; + white-space: nowrap; +} + .list__within-nums { color: var(--sg-text-muted); font-size: 12px; @@ -238,32 +218,28 @@ font-size: 13.5px; } -// -- Detail card -------------------------------------------------------- +// -- Detail row --------------------------------------------------------- -.card { - margin-top: 16px; +.row-detail { + padding: 18px 20px 20px; + border-top: 1px solid var(--sg-border); background: var(--sg-surface-muted); - .mat-mdc-card-content { - padding: 20px; - } - h3 { margin: 0 0 2px; color: var(--sg-text); - font-size: 20px; + font-size: 18px; } } -.card__head { +.row-detail__head { display: flex; - flex-wrap: wrap; + flex-direction: column; align-items: flex-start; - justify-content: space-between; - gap: 12px; + gap: 2px; } -.card__eyebrow { +.row-detail__eyebrow { display: block; margin-bottom: 2px; color: var(--sg-text-soft); @@ -273,17 +249,12 @@ text-transform: uppercase; } -.card__meta { - margin-bottom: 16px; +.row-detail__meta { + margin-bottom: 14px; color: var(--sg-text-soft); font-size: 12.5px; } -.card__flag { - color: var(--sg-error); - cursor: help; -} - .score-caption { margin: 0 0 12px; color: var(--sg-text-soft); @@ -325,6 +296,13 @@ &--primary strong { color: var(--sg-blue-highlight); } + + &__missing { + color: var(--sg-text-soft); + font-size: 15px; + font-weight: 600; + font-style: italic; + } } .facts { diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts index d77471db..4fd747b3 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts @@ -1,10 +1,8 @@ import { Component, computed, - effect, inject, input, - signal, TemplateRef, viewChild, } from '@angular/core'; @@ -15,8 +13,6 @@ import { MatCardModule } from '@angular/material/card'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; -import { MatSlideToggleModule } from '@angular/material/slide-toggle'; -import { MatSliderModule } from '@angular/material/slider'; import { MatTooltipModule } from '@angular/material/tooltip'; import { RouterLink } from '@angular/router'; import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; @@ -48,17 +44,18 @@ import { INSIGHTS_ICON, PERSONS_ICON, STAR_ICON, - VERIFIED_ICON, } from '../../../shared/ui/icons'; import { CredentialService } from '../../../shared/services/credential.service'; import { FounderExplainerPanelComponent } from './founder-explainer-panel/founder-explainer-panel.component'; +import { FounderFiltersComponent } from '../founder-filters/founder-filters.component'; const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen'; +const DEFAULT_THRESHOLD = 90; /** * A shortlist row: the generated candidate plus only the values that the - * table derives from it (display name, the 1/3/5-year slice, the headline - * screen reason). Everything else is read from `candidate` directly. + * table derives from it (display name, the 1/3/5-year slice, and the reason a + * profile has no score). */ interface FounderRow { candidate: FounderCandidate; @@ -66,7 +63,8 @@ interface FounderRow { areaLabel: string | null; score: number | null; within: (number | null)[]; - flagLabel: string | null; + /** Explanation shown in the "(nicht bewertet)" tooltip; null when scored. */ + notScoredReason: string | null; } @Component({ @@ -77,8 +75,6 @@ interface FounderRow { MatCardModule, MatButtonModule, MatIconModule, - MatSlideToggleModule, - MatSliderModule, MatTooltipModule, QueryParamPaginatorComponent, ChipComponent, @@ -87,6 +83,7 @@ interface FounderRow { PageContainerComponent, RouterLink, ComponentTooltipDirective, + FounderFiltersComponent, ], templateUrl: './founder-dashboard.component.html', styleUrl: './founder-dashboard.component.scss', @@ -99,7 +96,6 @@ export class FounderDashboardComponent { readonly INSIGHTS_ICON = INSIGHTS_ICON; readonly PERSONS_ICON = PERSONS_ICON; readonly STAR_ICON = STAR_ICON; - readonly VERIFIED_ICON = VERIFIED_ICON; readonly statistics = input.required(); readonly candidates = input.required(); @@ -123,25 +119,22 @@ export class FounderDashboardComponent { initialValue: this.route.snapshot.queryParamMap, }); - readonly threshold = computed(() => - Math.max( - 50, - Math.min(100, toNumber(this.queryParams().get('threshold')) ?? 90), - ), + /** The threshold is opt-in: it only applies when the URL param is present. */ + readonly thresholdEnabled = computed( + () => toNumber(this.queryParams().get('threshold')) !== null, ); + + readonly threshold = computed(() => { + const value = toNumber(this.queryParams().get('threshold')); + return value === null + ? DEFAULT_THRESHOLD + : Math.max(50, Math.min(100, value)); + }); + readonly screened = computed( () => this.queryParams().get('screened') === 'true', ); - /** Live value while dragging the slider; committed to the URL on release. */ - readonly thresholdDraft = signal(90); - - constructor() { - effect(() => this.thresholdDraft.set(this.threshold()), { - allowSignalWrites: true, - }); - } - // -- Explanations (tooltips only) -------------------------------------- readonly pageTooltip = @@ -153,28 +146,18 @@ export class FounderDashboardComponent { readonly scoreableTooltip = 'Nur diese Personen haben genug Publikationen (mindestens 4), um vom Modell bewertet zu werden. Für alle anderen gibt es keinen Score.'; - readonly qualityTooltip = computed( - () => - `${this.kpis().passed.toLocaleString('de-DE')} von ${this.kpis().total.toLocaleString('de-DE')} Forschenden (${this.kpis().share} %) haben ein vollständiges und plausibles Profil. Nur diese Werte sind gut belastbar.`, - ); - - readonly shortlistTooltip = computed( - () => - `Personen mit dem stärksten Gründungspotenzial. Angezeigt werden alle ab einem Rang von ${this.threshold()}. ${ - this.screened() - ? 'Auffällige Profile sind ausgeblendet.' - : 'Auffällige Profile sind enthalten.' - }`, - ); + readonly shortlistTooltip = computed(() => { + const thresholdPart = this.thresholdEnabled() + ? `Ab einem Rang von ${this.threshold()}.` + : 'Ohne Mindestwert werden alle Profile angezeigt.'; + const screenPart = this.screened() + ? 'Auffällige Profile sind ausgeblendet.' + : 'Auffällige Profile sind enthalten.'; + return `Personen mit dem stärksten Gründungspotenzial. ${thresholdPart} ${screenPart}`; + }); readonly shortlistSectionTooltip = - 'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Regler legt fest, ab welchem Rang jemand in die Liste kommt.'; - - readonly thresholdTooltip = - 'Legt fest, ab welchem Rang Personen in der Shortlist erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte.'; - - readonly screeningTooltip = - 'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Scores dieser Personen sind weniger verlässlich.'; + 'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Mindestwert ist optional: ohne ihn werden alle Profile angezeigt.'; readonly scoreTooltip = 'Rang des Gründungspotenzials von 0 bis 100. 90 heißt: stärker als 90 % der rund 9.000 vergleichbaren Wissenschaftler:innen anderer Universitäten. Kein Wahrscheinlichkeitswert.'; @@ -185,9 +168,6 @@ export class FounderDashboardComponent { readonly evidenceTooltip = 'Die Signale, auf denen die Einschätzung beruht: Publikationen, Patente, Förderungen und gemeinsame Arbeiten mit der Industrie. Die Werte sind Zählungen, keine Bewertung der Person.'; - readonly flagTooltip = - 'Möglicherweise wurden mehrere Personen mit gleichem Namen zusammengeführt oder die Karriereangaben sind unplausibel. Die Werte sind dann unsicher. Bitte Identität und Profil prüfen, bevor Sie die Person ansprechen.'; - readonly careerBucketTooltip = careerBucketDescription; // -- KPIs --------------------------------------------------------------- @@ -196,34 +176,35 @@ export class FounderDashboardComponent { const stats = this.statistics(); const total = stats.provenance?.document_count ?? 0; const scoreable = stats.overall?.in_population ?? 0; - const passed = stats.overall?.screened ?? 0; - const share = total ? Math.round((passed / total) * 100) : 0; const shortlisted = this.candidates().total ?? 0; - return { total, scoreable, passed, share, shortlisted }; + return { total, scoreable, shortlisted }; }); - /** True when the pipeline has produced at least one score for this university. */ - readonly hasScores = computed( - () => (this.statistics().overall?.in_population ?? 0) > 0, - ); - readonly scoreableShare = computed(() => { const { total, scoreable } = this.kpis(); return total ? Math.round((scoreable / total) * 100) : 0; }); - readonly qualityDetail = computed( - () => `${this.kpis().share} % der Forschenden`, - ); readonly scoreableDetail = computed( () => `${this.scoreableShare()} % der Forschenden`, ); - readonly shortlistDetail = computed(() => `ab Rang ${this.threshold()}`); + + readonly shortlistDetail = computed(() => + this.thresholdEnabled() ? `ab Rang ${this.threshold()}` : 'alle Profile', + ); readonly emptyListMessage = computed(() => - this.screened() - ? `Niemand erreicht den Mindestwert von ${this.threshold()} und hat zugleich ein unauffälliges Profil. Senken Sie den Mindestwert oder blenden Sie auffällige Profile wieder ein.` - : `Niemand erreicht den Mindestwert von ${this.threshold()}. Senken Sie den Mindestwert, um mehr Personen zu sehen.`, + this.thresholdEnabled() + ? `Niemand erreicht den Mindestwert von ${this.threshold()}${ + this.screened() ? ' und hat zugleich ein unauffälliges Profil' : '' + }. Senken Sie den Mindestwert${ + this.screened() + ? ' oder blenden Sie auffällige Profile wieder ein' + : ' oder deaktivieren Sie ihn' + }, um mehr Profile zu sehen.` + : this.screened() + ? 'Mit ausgeblendeten auffälligen Profilen wurde niemand gefunden. Blenden Sie auffällige Profile wieder ein, um mehr zu sehen.' + : 'Für diese Auswahl wurden keine Personen gefunden. Setzen Sie die Filter zurück, um mehr Profile zu sehen.', ); // -- Shortlist ---------------------------------------------------------- @@ -242,6 +223,8 @@ export class FounderDashboardComponent { viewChild.required>('withinHeader'); private readonly evidenceHeader = viewChild.required>('evidenceHeader'); + readonly detailTemplate = + viewChild.required>('rowDetailTemplate'); readonly columns = computed[]>(() => [ { @@ -280,52 +263,15 @@ export class FounderDashboardComponent { (this.candidates().elements ?? []).map((c) => toRow(c)), ); - readonly selectedId = signal(null); - - readonly selectedRow = computed(() => { - const id = this.selectedId(); - const rows = this.rows(); - if (id) { - return rows.find((r) => r.candidate.author_id === id) ?? null; - } - return rows[0] ?? null; - }); - - selectCandidate(id: string): void { - this.selectedId.set(id); - } - // -- Controls ----------------------------------------------------------- - /** Discrete label inside the Material slider thumb. */ - readonly formatThreshold = (value: number): string => String(value); - - onSliderInput(value: number): void { - if (Number.isFinite(value)) this.thresholdDraft.set(value); - } - - onSliderCommit(value = this.thresholdDraft()): void { - if (!Number.isFinite(value)) return; - this.thresholdDraft.set(value); - if (value === this.threshold()) return; - void this.router.navigate([], { - relativeTo: this.route, - queryParams: { threshold: value, page: 0 }, - queryParamsHandling: 'merge', - }); - } - - onScreenedChange(checked: boolean): void { - void this.router.navigate([], { - relativeTo: this.route, - queryParams: { screened: checked ? 'true' : 'false', page: 0 }, - queryParamsHandling: 'merge', - }); - } - onLowerThreshold(): void { const next = Math.max(50, this.threshold() - 10); - this.onSliderCommit(next); + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { threshold: next, page: 0 }, + queryParamsHandling: 'merge', + }); } /** Opens the global model explanation; independent of the selection. */ @@ -351,24 +297,32 @@ export class FounderDashboardComponent { function toRow(c: FounderCandidate): FounderRow { const fp = c.founder_potential; - const reasons = c.screen.reasons ?? []; + const score = fp?.external_percentile ?? null; return { candidate: c, name: c.display_name ?? c.author_id, areaLabel: c.founder_features?.publication_research_area_label ?? null, - score: fp?.external_percentile ?? null, + score, within: [ fp?.external_percentile_within_1y ?? null, fp?.external_percentile_within_3y ?? null, fp?.external_percentile_within_5y ?? null, ], - flagLabel: - reasons.length > 0 - ? (SCREEN_REASON_LABELS[reasons[0]] ?? reasons[0]) - : null, + notScoredReason: score === null ? notScoredReason(c) : null, }; } +/** Plain-language explanation for why a profile has no score. */ +function notScoredReason(c: FounderCandidate): string { + const reasons = (c.screen.reasons ?? []).map( + (reason) => SCREEN_REASON_LABELS[reason] ?? reason, + ); + const detail = reasons.length + ? ` Gründe: ${reasons.join(', ')}.` + : ''; + return `Für dieses Profil liegt kein Score vor. Das Modell braucht mindestens 4 Publikationen und ein vollständiges, plausibles Profil.${detail}`; +} + function toNumber(value: string | null): number | null { if (value === null || value === '') return null; const parsed = Number(value); From e2be1fc57d82350f7100bf0755e138207aaad527 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 18:18:53 +0100 Subject: [PATCH 32/36] added filters for founder table --- .../founder-filters.component.html | 28 ++++++ .../founder-filters.component.scss | 12 +++ .../founder-filters.component.ts | 89 +++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.html create mode 100644 webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.scss create mode 100644 webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.ts diff --git a/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.html b/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.html new file mode 100644 index 00000000..517f5af8 --- /dev/null +++ b/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.html @@ -0,0 +1,28 @@ +
+ + +
+ + + +
+ + +
diff --git a/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.scss b/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.scss new file mode 100644 index 00000000..2c4bef12 --- /dev/null +++ b/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.scss @@ -0,0 +1,12 @@ +.content { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.filter-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 1rem; + align-items: start; +} diff --git a/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.ts b/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.ts new file mode 100644 index 00000000..fcc23a9f --- /dev/null +++ b/webapp/src/app/modules/founder-potential/founder-filters/founder-filters.component.ts @@ -0,0 +1,89 @@ +import { Component, computed, input } from '@angular/core'; +import { MatTooltipModule } from '@angular/material/tooltip'; + +import { CareerBucket, FounderStatistics } from '../../../api'; +import { QueryParamInputComponent } from '../../../shared/ui/query-param-input/query-param-input.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../../shared/ui/query-param-selector/query-param-selector.component'; +import { + FilterObserver, + SelectedFiltersComponent, +} from '../../../shared/ui/selected-filters/selected-filters.component'; +import { PERSON_ICON, SEARCH_ICON } from '../../../shared/ui/icons'; + +@Component({ + selector: 'app-founder-filters', + standalone: true, + imports: [ + MatTooltipModule, + QueryParamInputComponent, + QueryParamSelectorComponent, + SelectedFiltersComponent, + ], + templateUrl: './founder-filters.component.html', + styleUrl: './founder-filters.component.scss', +}) +export class FounderFiltersComponent { + /** Stats carry the research-area codes/labels that the backend filters on. */ + readonly statistics = input.required(); + + readonly careerOptions: SelectorOption[] = [ + { value: CareerBucket.Early, display_name: 'Early (1–4 Jahre)' }, + { value: CareerBucket.Emerging, display_name: 'Emerging (5–9 Jahre)' }, + { + value: CareerBucket.Established, + display_name: 'Established (10–14 Jahre)', + }, + { value: CareerBucket.Senior, display_name: 'Senior (15+ Jahre)' }, + ]; + + /** + * The backend filters research areas by the 2-digit FOR division code + * (`founding_features.publication_research_area`), so the selector must use + * the code as its value, not the human-readable label. + */ + readonly researchAreaOptions = computed(() => + (this.statistics().research_areas ?? []) + .filter((area) => !!area.code) + .map((area) => ({ + value: area.code, + display_name: area.label ? `${area.label} (${area.code})` : area.code, + })) + .sort((a, b) => a.display_name.localeCompare(b.display_name, 'de')), + ); + + readonly observers: FilterObserver[] = [ + { + id: 'name', + queryParamKey: 'name', + icon: SEARCH_ICON, + removable: true, + template: undefined, + }, + { + id: 'researchArea', + queryParamKey: 'researchArea', + icon: SEARCH_ICON, + valueFormatter: (value) => + value + .split(',') + .map((code) => { + const area = this.statistics().research_areas?.find( + (a) => a.code === code, + ); + return area?.label ? `${area.label} (${code})` : code; + }) + .join(', '), + removable: true, + }, + { + id: 'career', + queryParamKey: 'careerBucket', + icon: PERSON_ICON, + valueFormatter: (value) => value.split(',').join(', '), + removable: true, + }, + ]; +} From eb2fa92225eeb8f9fb6fadd4cd2f699a8ed0af61 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 18:20:45 +0100 Subject: [PATCH 33/36] show all founder profiles per default --- service/src/main/inse/multiplicators/router.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/multiplicators/router.py b/service/src/main/inse/multiplicators/router.py index 72ff4a47..400fadab 100644 --- a/service/src/main/inse/multiplicators/router.py +++ b/service/src/main/inse/multiplicators/router.py @@ -122,10 +122,10 @@ async def search_founder_candidates( in_population: Annotated[ bool | None, Query( - description="Restrict to researchers the model can score (default). " - "Pass false for the unscored, or leave unset for everyone." + description="Restrict to researchers the model can score. " + "Pass true for the scored, false for the unscored, or leave unset for everyone." ), - ] = True, + ] = None, min_external_percentile: Annotated[ float | None, Query(description="Minimum founder percentile (0-100, vs the external reference cohort).", ge=0, le=100), From 722f95fad1f72746bdff4dfb7f2d1f73e5d23a0d Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 18:21:07 +0100 Subject: [PATCH 34/36] added founder table filters to the founder dashboard --- .../founder-dashboard.component.html | 49 +++++++++++++- .../founder-dashboard.component.scss | 40 ++++++++++-- .../founder-dashboard.component.ts | 64 +++++++++++++++++++ 3 files changed, 147 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html index 490c615f..87aaa471 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.html @@ -57,8 +57,53 @@ -
- {{ fmtInt(total()) }} {{ total() === 1 ? 'Person' : 'Personen' }} +
+ + Mindestwert + + {{ INFO_OUTLINE_ICON }} + + + + Aktiv + + + + + {{ thresholdDraft() }} + + Auffällige Profile ausblenden + + + {{ fmtInt(total()) }} {{ total() === 1 ? 'Person' : 'Personen' }} +
diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss index 6fd17256..8ccb2ac9 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.scss @@ -77,10 +77,42 @@ } } -.list-count { - margin: 1rem 0; - font-size: 0.875rem; - color: var(--sg-text-soft); +.controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px 22px; + margin-bottom: 16px; + padding: 12px 14px; + border: 1px solid var(--sg-border); + border-radius: 10px; + background: var(--sg-surface-muted); + font-size: 13px; + + &__range { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--sg-text-muted); + } + + &__value { + display: inline-block; + min-width: 24px; + color: var(--sg-text); + font-weight: 700; + font-variant-numeric: tabular-nums; + } + + &__count { + margin-left: auto; + color: var(--sg-text-soft); + } + + &__slider { + width: 220px; + min-width: 160px; + } } .list-card { diff --git a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts index 4fd747b3..5a79549f 100644 --- a/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts +++ b/webapp/src/app/modules/founder-potential/founder-dashboard/founder-dashboard.component.ts @@ -1,8 +1,10 @@ import { Component, computed, + effect, inject, input, + signal, TemplateRef, viewChild, } from '@angular/core'; @@ -13,6 +15,8 @@ import { MatCardModule } from '@angular/material/card'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; +import { MatSliderModule } from '@angular/material/slider'; +import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatTooltipModule } from '@angular/material/tooltip'; import { RouterLink } from '@angular/router'; import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; @@ -75,6 +79,8 @@ interface FounderRow { MatCardModule, MatButtonModule, MatIconModule, + MatSliderModule, + MatSlideToggleModule, MatTooltipModule, QueryParamPaginatorComponent, ChipComponent, @@ -170,6 +176,15 @@ export class FounderDashboardComponent { readonly careerBucketTooltip = careerBucketDescription; + readonly thresholdTooltip = + 'Legt fest, ab welchem Rang Personen in der Liste erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte. Ohne Mindestwert werden alle Profile angezeigt.'; + + readonly thresholdToggleTooltip = + 'Standardmäßig werden alle Profile angezeigt. Aktiviere den Mindestwert, um nur Personen ab einem bestimmten Rang zu sehen.'; + + readonly screeningTooltip = + 'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Werte dieser Personen sind weniger verlässlich. Ist die Option aus, werden alle Profile angezeigt.'; + // -- KPIs --------------------------------------------------------------- readonly kpis = computed(() => { @@ -265,6 +280,55 @@ export class FounderDashboardComponent { // -- Controls ----------------------------------------------------------- + /** Live slider value while dragging; committed to the URL on release. */ + readonly thresholdDraft = signal(DEFAULT_THRESHOLD); + + constructor() { + effect(() => this.thresholdDraft.set(this.threshold())); + } + + readonly formatThreshold = (value: number): string => String(value); + + /** Enables or disables the threshold filter (writes/removes the URL param). */ + onThresholdEnabledChange(enabled: boolean): void { + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { + threshold: enabled ? this.thresholdDraft() : null, + page: 0, + }, + queryParamsHandling: 'merge', + }); + } + + onSliderInput(value: number): void { + if (Number.isFinite(value)) this.thresholdDraft.set(value); + } + + /** Commits the threshold value to the URL. */ + onSliderCommit(value = this.thresholdDraft()): void { + if (!this.thresholdEnabled() || !Number.isFinite(value)) return; + this.thresholdDraft.set(value); + if (value === this.threshold()) return; + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { threshold: value, page: 0 }, + queryParamsHandling: 'merge', + }); + } + + /** + * `screened=false` means "only rejected profiles" on the backend, so turning + * the toggle off must REMOVE the param (everyone), not set false. + */ + onScreenedChange(checked: boolean): void { + void this.router.navigate([], { + relativeTo: this.route, + queryParams: { screened: checked ? 'true' : null, page: 0 }, + queryParamsHandling: 'merge', + }); + } + onLowerThreshold(): void { const next = Math.max(50, this.threshold() - 10); void this.router.navigate([], { From ea5e3ca942f42b2b31a296699a4e96d650c39a4d Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 18:21:34 +0100 Subject: [PATCH 35/36] added filter params to founders resolver --- .../resolvers/founder-candidates.resolver.ts | 49 ++++++++++++++----- 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/webapp/src/app/resolvers/founder-candidates.resolver.ts b/webapp/src/app/resolvers/founder-candidates.resolver.ts index 04f36435..7eba369f 100644 --- a/webapp/src/app/resolvers/founder-candidates.resolver.ts +++ b/webapp/src/app/resolvers/founder-candidates.resolver.ts @@ -1,6 +1,7 @@ import { ResolveFn } from '@angular/router'; import { inject } from '@angular/core'; import { + CareerBucket, FounderCandidatePage, FounderSortBy, MultiplicatorsService, @@ -9,12 +10,19 @@ import { const FOUNDER_SORT_FIELDS = Object.values(FounderSortBy); const SORT_DIRECTIONS = Object.values(SortDirection); -const DEFAULT_THRESHOLD = 90; +const VALID_CAREER_BUCKETS = Object.values(CareerBucket); /** * The founder-candidate list for the dashboard. Driven entirely by query - * params (threshold, screened, page, size, sort) so the page state stays in - * the URL and re-resolves when any of them change. + * params so the page state stays in the URL and re-resolves when any of them + * change. + * + * URL keys are the camelCase names used by the shared query-param controls and + * are mapped to the snake_case arguments of `searchFounderCandidates` here. + * + * Everyone is shown by default (`in_population` unset). The "Mindestwert" is + * opt-in: only when `threshold` is present is `min_external_percentile` sent. + * "Auffällige Profile ausblenden" sets `screened=true`. */ export const founderCandidatesResolver: ResolveFn = ( route, @@ -24,11 +32,14 @@ export const founderCandidatesResolver: ResolveFn = ( const page = Math.max(0, toInt(params.get('page'), 0)); const size = clamp(toInt(params.get('size'), 25), 1, 100); - const thresholdRaw = toNumber(params.get('threshold')); - const threshold = clamp(thresholdRaw ?? DEFAULT_THRESHOLD, 0, 100); - const screenedRaw = params.get('screened'); - const screened = screenedRaw === null ? undefined : screenedRaw === 'true'; + const thresholdRaw = toNumber(params.get('threshold')); + const minPercentile = + thresholdRaw === null ? undefined : clamp(thresholdRaw, 0, 100); + + // `screened=true` keeps only profiles that pass the data-quality screen. + // `screened=false` would mean "only the rejects", so it is never sent. + const screened = params.get('screened') === 'true' ? true : undefined; const sortBy = asMember(params.get('sortBy'), FOUNDER_SORT_FIELDS) ?? @@ -36,19 +47,26 @@ export const founderCandidatesResolver: ResolveFn = ( const sortOrder = asMember(params.get('sortOrder'), SORT_DIRECTIONS) ?? SortDirection.Desc; + const careerBuckets = splitCommaSeparated(params.getAll('careerBucket')).filter( + (value): value is CareerBucket => + (VALID_CAREER_BUCKETS as readonly string[]).includes(value), + ); + const researchAreas = splitCommaSeparated(params.getAll('researchArea')); + const name = params.get('name')?.trim() || undefined; + return service.searchFounderCandidates( page, size, - true, // in_population: only researchers the model can score - threshold, + undefined, // in_population: show everyone, scored and unscored + minPercentile, undefined, // max_external_percentile - undefined, // career_bucket + careerBuckets.length ? careerBuckets : undefined, screened, undefined, // min_publications undefined, // has_patents - undefined, // research_area + researchAreas.length ? researchAreas : undefined, undefined, // tags - undefined, // name + name, undefined, // screen_min_publications undefined, // screen_max_career_age sortBy, @@ -65,6 +83,13 @@ function asMember( : null; } +function splitCommaSeparated(values: string[]): string[] { + return values + .flatMap((value) => value.split(',')) + .map((value) => value.trim()) + .filter(Boolean); +} + function clamp(value: number, min: number, max: number): number { return Math.max(min, Math.min(max, value)); } From d90bf9b83735b0ab9eab89ba6449d1d032239fae Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 18 Nov 2026 18:21:55 +0100 Subject: [PATCH 36/36] navigate to founders with no threshold per default --- webapp/src/app/shared/ui/app-menu/app-menu.component.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index cb9e5a38..4ceade80 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -237,7 +237,6 @@ export class AppMenuComponent { route: '/founders', disabled: false, queryParams: { - threshold: 90, screened: 'true', page: 0, size: 10,