Merge dev into dfg PG authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...

This commit is contained in:
spsaefan
2026-07-25 23:53:49 +02:00
636 changed files with 263187 additions and 20304 deletions
@@ -0,0 +1,18 @@
@if (isEmptyGraph()) {
<div class="warning-container">
<mat-icon>warning</mat-icon>
<p>Das Netzwerk ist leer.</p>
</div>
} @else if (!isDisplayableGraph()) {
<div class="warning-container">
<mat-icon>warning</mat-icon>
<p>Das Netzwerk ist zu groß für eine detaillierte Darstellung.</p>
</div>
} @else {
<div
class="graph"
echarts
[options]="options()"
[autoResize]="true"
(chartClick)="onChartEvent($event, 'chartClick')"></div>
}
@@ -0,0 +1,37 @@
:host {
display: flex;
width: 100%;
}
mat-card {
display: flex;
flex-direction: column;
width: 100%;
background-color: var(--sg-background);
}
mat-card > mat-card-content {
flex: 1 1 auto;
min-height: 0;
align-items: center;
padding: 0px;
}
.graph {
width: 100%;
height: 100%;
min-height: 60vh;
overscroll-behavior: contain;
touch-action: none;
user-select: none;
cursor: grab;
}
.warning-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
padding: 24px;
}
@@ -0,0 +1,200 @@
import { Component, computed, input, output } from '@angular/core';
import { CollaborationGraph } from '../../api';
import { EChartsCoreOption } from 'echarts';
import { MatIconModule } from '@angular/material/icon';
import { NgxEchartsDirective } from 'ngx-echarts';
import * as echarts from 'echarts/core';
import {
GridComponent,
LegendComponent,
TitleComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { GraphChart } from 'echarts/charts';
echarts.use([
GridComponent,
CanvasRenderer,
GraphChart,
TitleComponent,
LegendComponent,
]);
export type NodeCategory = 'author' | 'collaborator' | 'work' | 'institution';
export interface NodeClickEvent {
id: string;
name: string;
category: NodeCategory;
}
@Component({
selector: 'app-collaboration-graph',
imports: [MatIconModule, NgxEchartsDirective],
templateUrl: './collaboration-graph.component.html',
styleUrl: './collaboration-graph.component.scss',
})
export class CollaborationGraphComponent {
collaborationGraph = input.required<CollaborationGraph>();
handleNodeClick = output<NodeClickEvent>();
readonly isEmptyGraph = computed(() => {
const graph = this.collaborationGraph();
return (
graph === undefined ||
(graph.authors?.length ?? 0) === 0 ||
(graph.edges?.length ?? 0) === 0
);
});
readonly isDisplayableGraph = computed(() => {
const graph = this.collaborationGraph();
return (
graph !== undefined &&
(graph.authors?.length ?? 0) > 0 &&
(graph.authors?.length ?? 0) < 1000 &&
(graph.edges?.length ?? 0) > 0
);
});
categoryLabels: Record<string, string> = {
author: 'Autor',
collaborator: 'Kollaborierender',
institution: 'Institution',
work: 'Publikation',
};
options = computed<EChartsCoreOption>(() => {
const graph = this.collaborationGraph();
if (!graph) {
return {};
}
const frequencies = this.occurenceFrequencies();
const minFrequency = Math.min(...Object.values(frequencies));
const maxFrequency = Math.max(...Object.values(frequencies));
const frequencyDenominator = maxFrequency - minFrequency || 1;
const nodes = [
...(graph.authors ?? []).map((author) => ({
id: author.id,
name: author.display_name,
category:
author.id === graph.root_author_id ? 'author' : 'collaborator',
label: {
show: true,
formatter: '{b}',
},
symbolSize:
25 +
(((frequencies[author.id] ?? 0) - minFrequency) /
frequencyDenominator) *
30,
})),
...(graph.institutions ?? []).map((institution) => ({
id: institution.id,
name: institution.display_name,
category: 'institution' as NodeCategory,
label: {
show: true,
formatter: '{b}',
},
symbolSize:
25 +
(((frequencies[institution.id] ?? 0) - minFrequency) /
frequencyDenominator) *
30,
})),
...(graph.works ?? []).map((work) => ({
id: work.id,
name: work.display_name,
category: 'work' as NodeCategory,
label: {
show: false,
},
emphasis: {
label: {
show: true,
formatter: '{b}',
},
},
symbolSize: 15,
})),
];
const links = (graph.edges ?? []).map((edge) => ({
source: edge.source,
target: edge.target,
}));
const categories = [
{ name: 'author' },
{ name: 'collaborator' },
{ name: 'institution' },
{ name: 'work' },
];
return {
legend: {
data: categories.map((category) => category.name),
bottom: 0,
orient: 'horizontal',
formatter: (name: string) => this.categoryLabels[name] || name,
itemGap: 20,
},
series: {
type: 'graph',
layout: 'force',
symbolSize: 15,
animation: false,
data: nodes,
links: links,
categories: categories,
roam: true,
roamTrigger: 'global', // + 2 hours because of incomplete documentation https://github.com/apache/echarts/issues/17214
zoom: 0.1,
force: {
repulsion: 10000,
friction: 0.9,
gravity: 0.2,
},
emphasis: {
focus: 'adjacency',
lineStyle: {
width: 5,
},
},
},
};
});
occurenceFrequencies = computed(() => {
const graph = this.collaborationGraph();
if (!graph) {
return {};
}
const frequencies: Record<string, number> = {};
graph.edges?.forEach((edge) => {
frequencies[edge.source] = (frequencies[edge.source] ?? 0) + 1;
frequencies[edge.target] = (frequencies[edge.target] ?? 0) + 1;
});
return frequencies;
});
onChartEvent(event: any, type: string) {
if (type !== 'chartClick') {
return;
}
const id = event?.data?.id;
const name = event?.data?.name;
const category = event?.data?.category;
if (!id || !name || !category) {
return;
}
this.handleNodeClick.emit({ id, name, category });
}
}
@@ -0,0 +1,179 @@
<div class="compare-layout">
<header class="compare-header">
<h1>Autoren-Vergleich</h1>
<div class="compare-meta">
@if (keywords().length > 0) {
<span class="meta-chip">
<mat-icon>topic</mat-icon>
{{ keywords().join(', ') }}
</span>
}
@if (timespan(); as span) {
<span class="meta-chip">
<mat-icon>date_range</mat-icon>
{{ span.from }}–{{ span.to }}
</span>
}
</div>
@if (hasData()) {
<ul class="author-legend">
@for (author of summary(); track author.authorId) {
<li class="legend-item">
<span
class="legend-swatch"
[style.background]="author.color"></span>
<span class="legend-name">{{ author.name }}</span>
</li>
}
</ul>
}
</header>
@if (loading()) {
<p class="compare-hint">Lädt…</p>
} @else if (!hasData()) {
<p class="compare-hint">Keine Daten für die ausgewählten Autoren.</p>
} @else {
<!-- section 1: stats over the topic-filtered works -->
<section class="card">
<h2 class="card-title">Kennzahlen zu den Keywords</h2>
<p class="card-sub">
Bester Wert je Zeile ist hervorgehoben. „–“ bedeutet, dass der Wert für
diese:n Autor:in nicht vorliegt.
</p>
<ng-container
[ngTemplateOutlet]="statsTable"
[ngTemplateOutletContext]="{ rows: topicRows() }" />
</section>
<!-- section 2: author-level stats, independent of the keywords and time -->
<section class="card">
<h2 class="card-title">Kennzahlen zur Person</h2>
<p class="card-sub">Unabhängig von den Keywords und Zeitraum.</p>
<ng-container
[ngTemplateOutlet]="statsTable"
[ngTemplateOutletContext]="{ rows: staticRows() }" />
</section>
<!-- section 3: topic profile over ALL works of each author -->
<section class="card">
<h2 class="card-title">Themenprofil</h2>
<p class="card-sub">"Topic-Analyse"</p>
@if (profileLoading()) {
<p class="compare-hint">Lädt…</p>
} @else if (orderedProfiles().length > 0) {
<h3 class="chart-title">Themenverteilung nach Subfield</h3>
<p class="chart-hint">
Von allen Arbeiten der Autor:innen im Zeitraum: der Anteil je
Subfield, bestimmt über das Primärthema jeder Arbeit. (Top 5)
</p>
<div
echarts
[options]="subfieldChart()"
class="profile-chart profile-chart-wide"></div>
<div class="chart-grid">
<div class="chart-box">
<h3 class="chart-title">Themen-Fokus</h3>
<p class="chart-hint">
Anzahl der Werke zum Suchthema im Verhältnis zum Gesamtwerk – und
wie viele davon das Suchthema als Primärthema tragen.
</p>
<div echarts [options]="focusChart()" class="profile-chart"></div>
</div>
<div class="chart-box">
<h3 class="chart-title">Themenbreite</h3>
<p class="chart-hint">
Einzigartige Primärthemen, Subfields und Fields im Gesamtwerk
(Primary Topic)
</p>
<div echarts [options]="breadthChart()" class="profile-chart"></div>
</div>
</div>
} @else {
<p class="compare-hint">Keine Daten für das Themenprofil.</p>
}
</section>
}
</div>
<ng-template #statsTable let-rows="rows">
<div class="table-scroll">
<table class="compare-table">
<thead>
<tr>
<th class="metric-col">Kennzahl</th>
@for (author of summary(); track author.authorId) {
<th class="author-col">
<span class="th-name">
<span
class="legend-swatch"
[style.background]="author.color"></span>
{{ author.name }}
</span>
</th>
}
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr>
<th scope="row" class="metric-col">
<span class="metric-label">{{ row.label }}</span>
<span class="metric-hint">{{ row.hint }}</span>
@if (row.kind === 'group') {
<span class="position-legend">
@for (seg of row.segments; track $index; let i = $index) {
@if (i > 0) {
<span class="pos-sep">|</span>
}
<span class="pos {{ seg.colorClass }}">{{
seg.label
}}</span>
}
</span>
}
</th>
@if (row.kind === 'group') {
@for (gc of row.groupCells; track $index) {
<td class="value-cell position-cell">
@for (v of gc.values; track $index; let i = $index) {
@if (i > 0) {
<span class="pos-sep">|</span>
}
<span class="pos {{ row.segments[i].colorClass }}">
{{
v === null
? '–'
: row.segments[i].plain
? v
: row.segments[i].decimals
? (v | number: '1.2-2')
: (v | number)
}}
</span>
}
</td>
}
} @else {
@for (cell of row.cells; track $index) {
<td class="value-cell" [class.best]="cell.best">
@if (cell.raw === null) {
<span class="value-empty">–</span>
} @else if (row.decimals) {
{{ cell.raw | number: '1.2-2' }}
} @else {
{{ cell.raw | number }}
}
</td>
}
}
</tr>
}
</tbody>
</table>
</div>
</ng-template>
@@ -0,0 +1,279 @@
.compare-layout {
padding: 28px 32px 42px;
display: flex;
flex-direction: column;
gap: 18px;
max-width: 1280px;
margin: 0 auto;
box-sizing: border-box;
}
/* ---- header ---- */
.compare-header {
display: flex;
flex-direction: column;
gap: 12px;
h1 {
margin: 0;
font-size: 24px;
font-weight: 700;
color: var(--sg-text, #101a3d);
}
}
.compare-meta {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.meta-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 12px;
border-radius: 999px;
background: var(--sg-surface-muted, #f7f9ff);
border: 1px solid var(--sg-border, #dde5f2);
color: var(--sg-text-muted, #64708f);
font-size: 13px;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
color: var(--sg-text-soft, #8a95b3);
}
}
.author-legend {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 8px 18px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 600;
color: var(--sg-text, #101a3d);
}
.legend-swatch {
width: 12px;
height: 12px;
border-radius: 3px;
flex: 0 0 auto;
}
/* ---- cards ---- */
.card {
background: #fff;
border: 1px solid #d7e4ff;
border-radius: 16px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
padding: 20px 22px;
}
.card-title {
margin: 0;
font-size: 16px;
font-weight: 700;
color: var(--sg-text, #101a3d);
}
.card-sub {
margin: 4px 0 0;
font-size: 13px;
color: var(--sg-text-muted, #64708f);
}
.compare-hint {
padding: 24px;
text-align: center;
color: var(--sg-text-muted, #64708f);
}
/* ---- comparison table ---- */
.table-scroll {
margin-top: 14px;
overflow-x: auto;
}
.compare-table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
thead th {
text-align: left;
padding: 0 16px 10px;
border-bottom: 2px solid var(--sg-border, #dde5f2);
vertical-align: bottom;
}
.author-col {
text-align: right;
}
.th-name {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 700;
color: var(--sg-text, #101a3d);
}
tbody tr + tr th,
tbody tr + tr td {
border-top: 1px solid var(--sg-border, #dde5f2);
}
tbody th,
tbody td {
padding: 12px 16px;
}
}
.metric-col {
min-width: 220px;
}
.metric-label {
display: block;
font-weight: 600;
color: var(--sg-text, #101a3d);
}
.metric-hint {
display: block;
margin-top: 2px;
font-size: 12px;
font-weight: 400;
color: var(--sg-text-soft, #8a95b3);
}
.value-cell {
text-align: right;
font-variant-numeric: tabular-nums;
color: var(--sg-text, #101a3d);
white-space: nowrap;
&.best {
font-weight: 700;
color: var(--sg-primary, #0b1020);
background: var(--sg-surface-soft, #f3f6fd);
}
}
.value-empty {
color: var(--sg-text-soft, #8a95b3);
}
/* author-position row: first / middle / last shown together, colour-coded */
.position-cell {
white-space: nowrap;
}
.pos {
font-weight: 700;
font-variant-numeric: tabular-nums;
&.pos-first {
color: #16a34a;
}
&.pos-middle {
color: #d97706;
}
&.pos-last {
color: #2563eb;
}
&.rel-count {
color: #7c3aed;
}
&.rel-avg {
color: #0891b2;
}
&.cit-total {
color: #b91c1c;
}
&.cit-avg {
color: #ea580c;
}
&.fwci-count {
color: #4d7c0f;
}
&.fwci-avg {
color: #0d9488;
}
&.year-from {
color: #6d28d9;
}
&.year-to {
color: #be185d;
}
&.ind-count {
color: #92400e;
}
&.ind-share {
color: #1d4ed8;
}
}
.pos-sep {
margin: 0 4px;
color: var(--sg-text-soft, #b6bed6);
font-weight: 400;
}
.position-legend {
display: block;
margin-top: 4px;
font-size: 11px;
font-weight: 600;
}
/* ---- section 3: topic profile charts ---- */
.chart-title {
margin: 18px 0 0;
font-size: 14px;
font-weight: 700;
color: var(--sg-text, #101a3d);
}
.chart-hint {
margin: 2px 0 8px;
font-size: 12px;
color: var(--sg-text-muted, #64708f);
}
.profile-chart {
width: 100%;
height: 260px;
}
.profile-chart-wide {
height: 320px;
}
.chart-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 24px;
}
@media (max-width: 900px) {
.compare-layout {
padding: 20px 16px 32px;
}
.chart-grid {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,719 @@
import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { DecimalPipe, NgTemplateOutlet } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import {
AuthorStaticStats,
AuthorTopicProfile,
AuthorTopicStats,
PublicationType,
RankingService,
SelectedAuthorsRequest,
} from '../../api';
const AUTHOR_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
const SUBFIELD_COLORS = [
'#2563eb',
'#16a34a',
'#d97706',
'#7c3aed',
'#0891b2',
'#db2777',
'#65a30d',
'#b45309',
];
const OTHER_COLOR = '#9ca3af';
const SUBFIELD_LIMIT = 5;
interface AuthorSummary {
authorId: string;
name: string;
color: string;
// section 1
// topic stats
totalWorks: number | null;
corresponding: number | null;
avgPercentile: number | null;
top10: number | null;
top1: number | null;
fwciAboveOne: number | null;
avgFwci: number | null;
// citations over the topic works
citationsTotal: number | null;
avgCitations: number | null;
maxCitations: number | null;
hIndex: number | null;
// industry collaboration (works with a company co-author institution)
industryWorks: number | null;
industryShare: number | null;
// active years within the topic
firstYear: number | null;
lastYear: number | null;
// topic-relevance (matched keyword score)
relevanceAbove80: number | null;
avgRelevance: number | null;
// author-position split (first / middle / last)
firstAuthor: number | null;
middleAuthor: number | null;
lastAuthor: number | null;
// section 2: author-level stats (keyword-independent)
companies: number | null;
news: number | null;
patents: number | null;
}
interface MetricCell {
raw: number | null;
best: boolean;
}
interface GroupSegment {
label: string;
colorClass: string;
decimals: boolean;
// render the value as-is, without the number pipe (e.g. years)
plain: boolean;
}
interface GroupCell {
values: (number | null)[];
}
interface MetricRow {
label: string;
hint: string;
decimals: boolean;
kind: 'scalar' | 'group';
cells: MetricCell[];
segments: GroupSegment[];
groupCells: GroupCell[];
}
interface RowDef {
label: string;
hint: string;
select: (a: AuthorSummary) => number | null;
decimals?: boolean;
}
interface SegmentDef {
label: string;
colorClass: string;
select: (a: AuthorSummary) => number | null;
decimals?: boolean;
plain?: boolean;
}
@Component({
selector: 'app-compare-authors',
standalone: true,
imports: [DecimalPipe, NgTemplateOutlet, MatIconModule, NgxEchartsDirective],
templateUrl: './compare-authors.component.html',
styleUrl: './compare-authors.component.scss',
})
export class CompareAuthorsComponent implements OnInit {
private readonly route = inject(ActivatedRoute);
private readonly rankingService = inject(RankingService);
readonly keywords = signal<string[]>([]);
readonly timespan = signal<{ from: number; to: number } | null>(null);
// full OpenAlex ids in the requested order — the source of truth for colour + order
readonly authorIds = signal<string[]>([]);
// section 1: combined topic stats, one entry per author
readonly topic = signal<AuthorTopicStats[]>([]);
// section 2: keyword-independent author-level stats
readonly staticStats = signal<AuthorStaticStats[]>([]);
// section 3: topic profile over ALL works of each author
readonly profile = signal<AuthorTopicProfile[]>([]);
readonly profileLoading = signal(false);
readonly loading = signal(false);
// maps both sections onto one row per author, in the requested order
readonly summary = computed<AuthorSummary[]>(() => {
const topicById = new Map(this.topic().map((a) => [a.author_id, a]));
const staticById = new Map(this.staticStats().map((a) => [a.author_id, a]));
return this.authorIds().map((id, index) => {
const t = topicById.get(id);
const m = staticById.get(id);
const name =
t?.display_name ?? m?.display_name ?? id.split('/').pop() ?? id;
const authorSummary: AuthorSummary = {
authorId: id,
name,
color: AUTHOR_COLORS[index % AUTHOR_COLORS.length],
totalWorks: t ? t.works_total : null,
corresponding: t ? t.corresponding_count : null,
avgPercentile: t ? t.avg_percentile : null,
top10: t ? t.top10_count : null,
top1: t ? t.top1_count : null,
fwciAboveOne: t?.fwci_above_one_count ?? null,
avgFwci: t?.avg_fwci ?? null,
citationsTotal: t?.citations_total ?? null,
avgCitations: t?.avg_citations ?? null,
maxCitations: t?.max_citations ?? null,
hIndex: t?.h_index ?? null,
industryWorks: t?.industry_works_count ?? null,
industryShare:
t && t.works_total > 0
? (t.industry_works_count ?? 0) / t.works_total
: null,
firstYear: t?.first_year ?? null,
lastYear: t?.last_year ?? null,
relevanceAbove80: t?.relevance_above_80_count ?? null,
avgRelevance: t?.avg_relevance ?? null,
firstAuthor: t?.first_author_count ?? null,
middleAuthor: t?.middle_author_count ?? null,
lastAuthor: t?.last_author_count ?? null,
companies: m?.companies_count ?? null,
news: m?.news_count ?? null,
patents: m?.patents_count ?? null,
};
return authorSummary;
});
});
readonly hasData = computed(() => this.summary().length > 0);
// section 1 table: stats over the topic-filtered works
readonly topicRows = computed<MetricRow[]>(() => [
...this.buildRows([
{
label: 'Werke gesamt',
hint: 'Publikationen zum Thema im Zeitraum',
select: (a) => a.totalWorks,
},
{
label: 'Corresponding-Author-Werke',
hint: 'Werke, in denen die Person korrespondierende:r Autor:in ist',
select: (a) => a.corresponding,
},
]),
this.buildGroupRow(
'Zitationen',
'Zitationen der Themen-Werke: gesamt | Ø pro Werk',
[
{
label: 'gesamt',
colorClass: 'cit-total',
select: (a) => a.citationsTotal,
},
{
label: 'Ø',
colorClass: 'cit-avg',
decimals: true,
select: (a) => a.avgCitations,
},
],
),
...this.buildRows([
{
label: 'Ø Impact-Perzentil',
hint: 'Feld-normalisiertes Zitations-Perzentil (0–1)',
select: (a) => a.avgPercentile,
decimals: true,
},
{
label: 'h-Index',
hint: 'h-Index über die Werke zum Thema',
select: (a) => a.hIndex,
},
{
label: 'Meistzitiertes Werk',
hint: 'Zitationen des meistzitierten Werks zum Thema',
select: (a) => a.maxCitations,
},
{
label: 'Top-10%-Werke',
hint: 'Werke unter den 10% meistzitierten',
select: (a) => a.top10,
},
{
label: 'Top-1%-Werke',
hint: 'Werke unter den 1% meistzitierten',
select: (a) => a.top1,
},
]),
this.buildGroupRow(
'FWCI',
'Field-Weighted Citation Impact: Werke über Feld-Durchschnitt | Ø über alle',
[
{
label: '> 1',
colorClass: 'fwci-count',
select: (a) => a.fwciAboveOne,
},
{
label: 'Ø',
colorClass: 'fwci-avg',
decimals: true,
select: (a) => a.avgFwci,
},
],
),
this.buildGroupRow(
'Themen-Relevanz',
'Match-Score der Keywords: Werke > 80% | Ø über alle',
[
{
label: '> 80%',
colorClass: 'rel-count',
select: (a) => a.relevanceAbove80,
},
{
label: 'Ø',
colorClass: 'rel-avg',
decimals: true,
select: (a) => a.avgRelevance,
},
],
),
this.buildGroupRow(
'Autor-Position',
'Werke nach Position (Erst | Mittel | Letzt)',
[
{
label: 'Erst',
colorClass: 'pos-first',
select: (a) => a.firstAuthor,
},
{
label: 'Mittel',
colorClass: 'pos-middle',
select: (a) => a.middleAuthor,
},
{ label: 'Letzt', colorClass: 'pos-last', select: (a) => a.lastAuthor },
],
),
this.buildGroupRow(
'Industrie-Kollaboration',
'Werke mit Co-Autor:in aus einem Unternehmen: Anzahl | Anteil',
[
{
label: 'Anzahl',
colorClass: 'ind-count',
select: (a) => a.industryWorks,
},
{
label: 'Anteil',
colorClass: 'ind-share',
decimals: true,
select: (a) => a.industryShare,
},
],
),
this.buildGroupRow(
'Aktiv im Thema',
'Erstes und letztes Publikationsjahr zum Thema',
[
{
label: 'von',
colorClass: 'year-from',
plain: true,
select: (a) => a.firstYear,
},
{
label: 'bis',
colorClass: 'year-to',
plain: true,
select: (a) => a.lastYear,
},
],
),
]);
// section 2 table: author-level stats, independent of the keywords
readonly staticRows = computed<MetricRow[]>(() =>
this.buildRows([
{
label: 'Unternehmensgründungen',
hint: 'Handelsregister-Verbindungen über den Namen',
select: (a) => a.companies,
},
{
label: 'News-Artikel',
hint: 'Nachrichtenartikel, die die Person namentlich nennen',
select: (a) => a.news,
},
{
label: 'Patente',
hint: 'Der Person zugeordnete Patente',
select: (a) => a.patents,
},
]),
);
// section 3: profiles in the requested author order (drives all charts)
readonly orderedProfiles = computed<AuthorTopicProfile[]>(() => {
const byId = new Map(this.profile().map((p) => [p.author_id, p]));
return this.authorIds()
.map((id) => byId.get(id))
.filter((p): p is AuthorTopicProfile => p !== undefined);
});
// colours the author names on the chart axes like the legend chips
private authorAxisLabel(profiles: AuthorTopicProfile[]) {
const rich: Record<string, { color: string; fontWeight: number }> = {};
profiles.forEach((_, i) => {
rich[`a${i}`] = {
color: AUTHOR_COLORS[i % AUTHOR_COLORS.length],
fontWeight: 600,
};
});
return {
formatter: (value: string) => {
const index = profiles.findIndex((p) => p.display_name === value);
return index >= 0 ? `{a${index}|${value}}` : value;
},
rich,
// rich-text labels are measured slightly too narrow — leave some slack
margin: 12,
};
}
// chart 1: how each author's complete body of work distributes over subfields
readonly subfieldChart = computed<EChartsOption>(() => {
const profiles = this.orderedProfiles();
if (profiles.length === 0) return {};
// union of the biggest subfields across all authors, one colour each
const totals = new Map<string, number>();
for (const p of profiles) {
for (const s of p.subfields || []) {
totals.set(s.name, (totals.get(s.name) ?? 0) + s.count);
}
}
const topSubfields = [...totals.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, SUBFIELD_LIMIT)
.map(([name]) => name);
const shownCounts = profiles.map((p) =>
topSubfields.map(
(name) => p.subfields?.find((s) => s.name === name)?.count ?? 0,
),
);
const series: any[] = topSubfields.map((name, si) => ({
name,
type: 'bar',
stack: 'profil',
barWidth: 22,
emphasis: { focus: 'series' },
itemStyle: { color: SUBFIELD_COLORS[si % SUBFIELD_COLORS.length] },
data: profiles.map((p, ai) => {
const count = shownCounts[ai][si];
return {
value:
p.works_total > 0
? Math.round((count / p.works_total) * 1000) / 10
: 0,
count,
};
}),
}));
// everything outside the shown subfields (incl. works without primary topic)
series.push({
name: 'Sonstige',
type: 'bar',
stack: 'profil',
barWidth: 22,
emphasis: { focus: 'series' },
itemStyle: { color: OTHER_COLOR },
data: profiles.map((p, ai) => {
const rest =
p.works_total - shownCounts[ai].reduce((sum, c) => sum + c, 0);
return {
value:
p.works_total > 0
? Math.round((rest / p.works_total) * 1000) / 10
: 0,
count: rest,
};
}),
});
return {
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
formatter: (params: any) => {
const lines = params
.filter((p: any) => p.data.count > 0)
.map(
(p: any) =>
`${p.marker} ${p.seriesName}: <b>${p.data.value} %</b> (${p.data.count} Werke)`,
);
return `<b>${params[0]?.name ?? ''}</b><br/>${lines.join('<br/>')}`;
},
},
legend: { type: 'scroll', top: 0 },
grid: { left: 16, right: 24, top: 56, bottom: 8, containLabel: true },
xAxis: {
type: 'value',
max: 100,
axisLabel: { formatter: '{value} %' },
},
yAxis: {
type: 'category',
inverse: true,
data: profiles.map((p) => p.display_name),
axisLabel: this.authorAxisLabel(profiles),
},
series,
} as EChartsOption;
});
// chart 2: topic focus — how much of the complete body of work is on the searched topic
readonly focusChart = computed<EChartsOption>(() => {
const profiles = this.orderedProfiles();
if (profiles.length === 0) return {};
const pct = (part: number, whole: number) =>
whole > 0 ? Math.round((part / whole) * 1000) / 10 : 0;
return {
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
formatter: (params: any) => {
const lines = params.map(
(p: any) =>
`${p.marker} ${p.seriesName}: <b>${p.data.value} %</b> (${p.data.part} von ${p.data.whole} Werken)`,
);
return `<b>${params[0]?.name ?? ''}</b><br/>${lines.join('<br/>')}`;
},
},
legend: { top: 0 },
grid: { left: 16, right: 40, top: 32, bottom: 8, containLabel: true },
xAxis: {
type: 'value',
max: 100,
axisLabel: { formatter: '{value} %' },
},
yAxis: {
type: 'category',
inverse: true,
data: profiles.map((p) => p.display_name),
axisLabel: this.authorAxisLabel(profiles),
},
series: [
{
name: 'Anteil am Gesamtwerk',
type: 'bar',
itemStyle: { color: '#2563eb' },
label: { show: true, position: 'right', formatter: '{c} %' },
data: profiles.map((p) => ({
value: pct(p.matched_works, p.works_total),
part: p.matched_works,
whole: p.works_total,
})),
},
{
name: 'davon Primärthema',
type: 'bar',
itemStyle: { color: '#7c3aed' },
label: { show: true, position: 'right', formatter: '{c} %' },
data: profiles.map((p) => ({
value: pct(p.primary_topic_matches, p.matched_works),
part: p.primary_topic_matches,
whole: p.matched_works,
})),
},
],
} as EChartsOption;
});
// chart 3: topic breadth — how many distinct (sub)fields the author publishes in
readonly breadthChart = computed<EChartsOption>(() => {
const profiles = this.orderedProfiles();
if (profiles.length === 0) return {};
return {
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: { top: 0 },
grid: { left: 16, right: 40, top: 32, bottom: 8, containLabel: true },
xAxis: { type: 'value' },
yAxis: {
type: 'category',
inverse: true,
data: profiles.map((p) => p.display_name),
axisLabel: this.authorAxisLabel(profiles),
},
series: [
{
name: 'Themen',
type: 'bar',
itemStyle: { color: '#0891b2' },
label: { show: true, position: 'right' },
data: profiles.map((p) => p.distinct_topics),
},
{
name: 'Subfields',
type: 'bar',
itemStyle: { color: '#d97706' },
label: { show: true, position: 'right' },
data: profiles.map((p) => p.distinct_subfields),
},
{
name: 'Fields',
type: 'bar',
itemStyle: { color: '#16a34a' },
label: { show: true, position: 'right' },
data: profiles.map((p) => p.distinct_fields),
},
],
} as EChartsOption;
});
// turns row definitions into table rows, marking the best value per row
private buildRows(defs: RowDef[]): MetricRow[] {
const authors = this.summary();
return defs.map((def) => {
const values = authors.map(def.select);
const present = values.filter((v): v is number => v !== null);
const max = present.length ? Math.max(...present) : null;
return {
label: def.label,
hint: def.hint,
decimals: def.decimals ?? false,
kind: 'scalar' as const,
cells: values.map((raw) => ({
raw,
best: raw !== null && max !== null && raw === max && max > 0,
})),
segments: [],
groupCells: [],
};
});
}
private buildGroupRow(
label: string,
hint: string,
segs: SegmentDef[],
): MetricRow {
return {
label,
hint,
decimals: false,
kind: 'group' as const,
cells: [],
segments: segs.map((s) => ({
label: s.label,
colorClass: s.colorClass,
decimals: s.decimals ?? false,
plain: s.plain ?? false,
})),
groupCells: this.summary().map((a) => ({
values: segs.map((s) => s.select(a)),
})),
};
}
ngOnInit(): void {
// everything is read from the URL so a shared link lands on the same view
const rawAuthors = this.route.snapshot.queryParamMap.get('authors') ?? '';
const rawKeywords = this.route.snapshot.queryParamMap.get('keywords') ?? '';
const rawOperator = this.route.snapshot.queryParamMap.get('operator');
const rawPubType = this.route.snapshot.queryParamMap.get('pubType');
const rawTFrom = this.route.snapshot.queryParamMap.get('tFrom');
const rawTTo = this.route.snapshot.queryParamMap.get('tTo');
const authorIds = this.parseList(rawAuthors);
const keywords = this.parseList(rawKeywords);
this.keywords.set(keywords);
if (authorIds.length === 0 || keywords.length === 0) {
return;
}
const operator = rawOperator === 'and' ? 'and' : 'or';
const publication_types = rawPubType
? this.parseList(rawPubType)
.map((s) => this.getPublicationType(s))
.filter((v): v is PublicationType => !!v)
: undefined;
const timespan =
rawTFrom && rawTTo ? { from: +rawTFrom, to: +rawTTo } : undefined;
this.timespan.set(timespan ?? null);
// ids in the url are bare (A5036...); the endpoint expects full OpenAlex urls
const fullIds = authorIds.map((id) => `https://openalex.org/${id}`);
this.authorIds.set(fullIds);
const request: SelectedAuthorsRequest = {
author_ids: fullIds,
keywords: keywords,
operator: operator,
filter_type: 'topic',
publication_types: publication_types,
timespan: timespan,
};
// section 1: topic-filtered works stats
this.loading.set(true);
this.rankingService.topicStatsApiRankTopicStatsPost(request).subscribe({
next: (results) => {
this.topic.set(results);
this.loading.set(false);
},
error: (error) => {
console.error(error);
this.topic.set([]);
this.loading.set(false);
},
});
// section 3: topic profile over ALL works (same filter, own endpoint)
this.profileLoading.set(true);
this.rankingService.topicProfileApiRankTopicProfilePost(request).subscribe({
next: (results) => {
this.profile.set(results);
this.profileLoading.set(false);
},
error: (error) => {
console.error(error);
this.profile.set([]);
this.profileLoading.set(false);
},
});
// section 2: keyword-independent author-level stats
this.rankingService
.staticStatsApiRankStaticStatsPost({ author_ids: fullIds })
.subscribe({
next: (results) => {
this.staticStats.set(results);
},
error: (error) => {
console.error(error);
this.staticStats.set([]);
},
});
}
private parseList(raw: string): string[] {
return raw
.split(',')
.map((value) => value.trim())
.filter(Boolean);
}
getPublicationType(str: string): PublicationType | null {
const normalized = str.trim().toLowerCase();
for (const [key, value] of Object.entries(PublicationType)) {
if (value.toLowerCase() === normalized) {
return value as PublicationType;
}
}
return null;
}
}
@@ -3,6 +3,7 @@ import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Configuration } from '../../api';
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
export type TopAuthorsWorksPeriod = 'all_time' | 'last_5_years';
@@ -11,6 +12,7 @@ export interface DashboardStatistics {
organization_name: string;
publications: number;
persons: number;
patents: number;
projects: number;
dfg_projects: number;
eu_projects: number;
@@ -23,9 +25,41 @@ export interface DashboardStatisticValue {
value: number;
}
export interface EuProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
export interface BmbfProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
export interface DfgProjectTopic {
id: string;
name: string;
subfield?: string | null;
field?: string | null;
domain?: string | null;
project_count: number;
}
export interface DfgProjectTopics {
institution_id: string;
organization_name: string;
project_count: number;
matched_project_count: number;
topics: DfgProjectTopic[];
}
export interface TopAuthor {
id?: string | null;
dfg_person_id?: number | null;
name: string;
count: number;
}
@@ -34,28 +68,20 @@ export interface TopAuthorStatistics {
institution_id: string;
works: TopAuthor[];
projects: TopAuthor[];
eu_projects: TopAuthor[];
patents: TopAuthor[];
news: TopAuthor[];
}
export interface TopicHeatmapValue {
year: number;
count: number;
share: number;
}
export interface TopicHeatmapField {
export interface TopicWordCloudWord {
id: string;
name: string;
total: number;
values: TopicHeatmapValue[];
count: number;
}
export interface TopicHeatmap {
institution_id: string;
organization_name: string;
years: number[];
fields: TopicHeatmapField[];
export interface TopicWordCloud {
topic_id: string;
words: TopicWordCloudWord[];
}
@Injectable({ providedIn: 'root' })
@@ -81,12 +107,30 @@ export class DashboardStatisticsService {
);
}
getPatentCount(): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`,
);
}
getEuProjectCount(): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`,
);
}
getEuProjectStatuses(): Observable<EuProjectStatusStatistics> {
return this.httpClient.get<EuProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`,
);
}
getBmbfProjectStatuses(): Observable<BmbfProjectStatusStatistics> {
return this.httpClient.get<BmbfProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`,
);
}
getBmbfProjectCount(): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
@@ -99,6 +143,12 @@ export class DashboardStatisticsService {
);
}
getDfgProjectTopics(): Observable<DfgProjectTopics> {
return this.httpClient.get<DfgProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`,
);
}
getTopAuthors(
worksPeriod: TopAuthorsWorksPeriod = 'all_time',
): Observable<TopAuthorStatistics> {
@@ -110,17 +160,31 @@ export class DashboardStatisticsService {
);
}
getTopicHeatmap(
getTopicTreemap(
fromYear?: number,
toYear?: number,
): Observable<TopicHeatmap> {
): Observable<TopicTreemapData> {
const params: Record<string, number> = {};
if (fromYear !== undefined) params['from_year'] = fromYear;
if (toYear !== undefined) params['to_year'] = toYear;
return this.httpClient.get<TopicHeatmap>(
return this.httpClient.get<TopicTreemapData>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-heatmap`,
{ params },
);
}
getTopicWordCloud(
topicId: string,
fromYear?: number,
toYear?: number,
): Observable<TopicWordCloud> {
const params: Record<string, string | number> = { topicId };
if (fromYear !== undefined) params['from_year'] = fromYear;
if (toYear !== undefined) params['to_year'] = toYear;
return this.httpClient.get<TopicWordCloud>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-wordcloud`,
{ params },
);
}
}
@@ -23,10 +23,31 @@
</div>
</a>
<a
class="statistics-card"
[routerLink]="['/institution', institutionRouteId(), 'patents']"
[class.disabled]="!institutionRouteId()"
[attr.aria-disabled]="!institutionRouteId()"
[attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'">
<div class="statistics-icon statistics-icon--patents">
<mat-icon>description</mat-icon>
</div>
<div>
<span>Patente</span>
<strong>
{{
isStatisticLoading('patents')
? '…'
: ((statistics?.patents | number) ?? '–')
}}
</strong>
</div>
</a>
<a
class="statistics-card"
routerLink="/persons"
[queryParams]="{ institutionName: organizationName() }"
[queryParams]="personListQueryParams()"
[attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'">
<div class="statistics-icon statistics-icon--persons">
<mat-icon>groups</mat-icon>
@@ -108,67 +129,139 @@
<p class="statistics-error">Die Kennzahlen konnten nicht geladen werden.</p>
}
@if (topicHeatmapLoading || topicHeatmapError || hasTopicHeatmapData()) {
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
euProjectStatusesError ||
bmbfProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses)
) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Projektstatus nach Fördergeber</h2>
<p>
Laufende, kommende und abgeschlossene EU- und Bund-Projekte Ihrer
Organisation.
</p>
</div>
@if (euProjectStatuses && bmbfProjectStatuses) {
<div class="project-status-summary">
<span>
EU:
{{
euProjectStatuses.ongoing +
euProjectStatuses.upcoming +
euProjectStatuses.completed | number
}}
</span>
<span>
Bund:
{{
bmbfProjectStatuses.ongoing +
bmbfProjectStatuses.upcoming +
bmbfProjectStatuses.completed | number
}}
</span>
</div>
}
</header>
@if (euProjectStatusesLoading || bmbfProjectStatusesLoading) {
<div class="project-status-loading" role="status" aria-live="polite">
<app-loading
text="Projektstatus wird geladen …"
icon="stacked_bar_chart"
size="64"
diameter="64"></app-loading>
</div>
} @else if (euProjectStatusesError || bmbfProjectStatusesError) {
<p class="statistics-error">
Der Status der EU- und Bund-Projekte konnte nicht geladen werden.
</p>
} @else if (euProjectStatuses && bmbfProjectStatuses) {
<app-eu-project-status-chart
[statuses]="euProjectStatuses"
[bmbfStatuses]="bmbfProjectStatuses"></app-eu-project-status-chart>
}
</section>
}
@if (topicTreemapLoading || topicTreemapError || hasTopicTreemapData()) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Field Treemap</h2>
<p>Publikationen Ihrer Organisation nach Field.</p>
</div>
<div class="topic-treemap-period-controls" aria-label="Zeitraum">
<div class="topic-treemap-period-toggle">
<button
type="button"
[class.active]="topicTreemapPeriod === 'last_5_years'"
(click)="setTopicTreemapPeriod('last_5_years')">
5 Jahre
</button>
<button
type="button"
[class.active]="topicTreemapPeriod === 'last_10_years'"
(click)="setTopicTreemapPeriod('last_10_years')">
10 Jahre
</button>
<button
type="button"
[class.active]="topicTreemapPeriod === 'all_time'"
(click)="setTopicTreemapPeriod('all_time')">
Alle
</button>
</div>
<label>
Von
<input
type="number"
min="1900"
max="2100"
[value]="topicTreemapFromYear"
(change)="
onTopicTreemapYearChange('from', $any($event.target).value)
" />
</label>
<label>
Bis
<input
type="number"
min="1900"
max="2100"
[value]="topicTreemapToYear"
(change)="
onTopicTreemapYearChange('to', $any($event.target).value)
" />
</label>
<div class="topic-treemap-year-slider">
<app-year-range-slider
[minYear]="topicTreemapMinYear"
[maxYear]="topicTreemapMaxYear"
[(startYear)]="topicTreemapFromYear"
[(endYear)]="topicTreemapToYear"
(startYearChange)="onTopicTreemapRangeChange()"
(endYearChange)="onTopicTreemapRangeChange()">
</app-year-range-slider>
</div>
</header>
@if (topicHeatmapError) {
@if (topicTreemapLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="Treemap-Daten für den gewählten Zeitraum werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (topicTreemapError) {
<p class="statistics-error">
Die Field-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-heatmap
[heatmap]="topicHeatmap"
[loading]="topicHeatmapLoading"></app-topic-heatmap>
<app-topic-treemap
[data]="topicTreemap"
[selectedNodeId]="selectedTopicTreemapNode"
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)"
(topicSelect)="onTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (dfgTopicsLoading || dfgTopicsError || dfgProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>DFG-Projekt-Topics</h2>
<p>
Verteilung der gematchten Topics aus den DFG-Projekten Ihrer
Organisation.
</p>
</div>
@if (dfgProjectTopics) {
<p class="dfg-topic-summary">
{{ dfgProjectTopics.matched_project_count | number }} von
{{ dfgProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@if (dfgTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="DFG-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (dfgTopicsError) {
<p class="statistics-error">
Das DFG-Topic-Diagramm konnte nicht geladen werden.
</p>
} @else {
<app-dfg-topic-donut
[topics]="dfgProjectTopics?.topics ?? []"></app-dfg-topic-donut>
}
</section>
}
@@ -73,6 +73,11 @@
color: #15803d;
}
&--patents {
background: #fee2e2;
color: #b91c1c;
}
&--eu-projects {
background: #e0f2fe;
color: #0369a1;
@@ -129,68 +134,41 @@
}
}
.topic-treemap-period-controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.65rem;
.topic-treemap-year-slider {
width: min(100%, 34rem);
}
label {
display: inline-flex;
align-items: center;
gap: 0.35rem;
.topic-heatmap-loading {
min-height: 25rem;
display: grid;
place-items: center;
}
.project-status-loading {
min-height: 15rem;
display: grid;
place-items: center;
}
.project-status-summary {
display: flex;
flex: 0 0 auto;
gap: 0.5rem;
span {
padding: 0.35rem 0.65rem;
border-radius: 999px;
background: #f1f5f9;
color: #475569;
font-size: 0.9rem;
font-weight: 600;
}
input {
width: 5.5rem;
padding: 0.45rem 0.55rem;
border: 1px solid #cbd5e1;
border-radius: 6px;
color: #0f172a;
font: inherit;
&:focus {
border-color: #93c5fd;
outline: 3px solid #bfdbfe;
outline-offset: 0;
}
}
}
.topic-treemap-period-toggle {
display: inline-flex;
overflow: hidden;
border: 1px solid #cbd5e1;
border-radius: 6px;
background: #fff;
button {
padding: 0.5rem 0.7rem;
border: 0;
border-right: 1px solid #cbd5e1;
background: transparent;
color: #334155;
cursor: pointer;
font: inherit;
font-weight: 600;
&:last-child {
border-right: 0;
}
&.active {
background: #1d4ed8;
color: #fff;
}
&:focus-visible {
outline: 3px solid #93c5fd;
outline-offset: -3px;
}
}
.dfg-topic-summary {
flex: 0 0 auto;
color: #475569;
font-weight: 600;
}
.top-authors-header {
@@ -2,39 +2,61 @@ import { Component, OnInit } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { Observable, finalize } from 'rxjs';
import { RouterLink } from '@angular/router';
import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { DfgTopicDonutComponent } from './dfg-topic-donut/dfg-topic-donut.component';
import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component';
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { TopicTreemapComponent } from '../../shared/ui/topic-treemap/topic-treemap.component';
import {
TopicTreemapData,
TopicTreemapTopicSelect,
} from '../../shared/ui/topic-treemap/topic-treemap.models';
import {
TopicWordCloudDialogComponent,
TopicWordCloudDialogData,
} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component';
import {
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DashboardStatisticsService,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
TopAuthorStatistics,
TopAuthorsWorksPeriod,
TopicHeatmap,
} from './dashboard-statistics.service';
import {
activeInstitutionPersonListQueryParams,
PersonListQueryParams,
} from '../../shared/person-list-query-params';
type DashboardStatisticKey =
| 'publications'
| 'persons'
| 'patents'
| 'eu_projects'
| 'bmbf_projects'
| 'dfg_projects';
type TopicTreemapPeriod =
| 'last_5_years'
| 'last_10_years'
| 'all_time'
| 'custom';
type TopAuthorDataset = {
title: string;
icon: string;
entries: TopAuthor[];
stripAuthorTitle?: boolean;
projectAuthors?: boolean;
};
@Component({
selector: 'dashboard',
imports: [DecimalPipe, MatIconModule, RouterLink, TopicHeatmapComponent],
imports: [
DecimalPipe,
MatIconModule,
RouterLink,
LoadingComponent,
DfgTopicDonutComponent,
EuProjectStatusChartComponent,
TopicTreemapComponent,
YearRangeSliderComponent,
],
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss',
})
@@ -45,6 +67,7 @@ export class DashboardComponent implements OnInit {
statisticLoading: Record<DashboardStatisticKey, boolean> = {
publications: false,
persons: false,
patents: false,
eu_projects: false,
bmbf_projects: false,
dfg_projects: false,
@@ -52,6 +75,7 @@ export class DashboardComponent implements OnInit {
statisticErrors: Record<DashboardStatisticKey, boolean> = {
publications: false,
persons: false,
patents: false,
eu_projects: false,
bmbf_projects: false,
dfg_projects: false,
@@ -61,19 +85,41 @@ export class DashboardComponent implements OnInit {
topAuthorsLoading = false;
topAuthorsError = false;
topAuthorsWorksPeriod: TopAuthorsWorksPeriod = 'all_time';
topicHeatmap?: TopicHeatmap;
topicHeatmapLoading = false;
topicHeatmapError = false;
topicTreemapPeriod: TopicTreemapPeriod = 'last_5_years';
topicTreemapFromYear = new Date().getFullYear() - 4;
topicTreemapToYear = new Date().getFullYear();
topicTreemap?: TopicTreemapData;
topicTreemapLoading = false;
topicTreemapError = false;
dfgProjectTopics?: DfgProjectTopics;
dfgTopicsLoading = false;
dfgTopicsError = false;
euProjectStatuses?: EuProjectStatusStatistics;
euProjectStatusesLoading = false;
euProjectStatusesError = false;
bmbfProjectStatuses?: BmbfProjectStatusStatistics;
bmbfProjectStatusesLoading = false;
bmbfProjectStatusesError = false;
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
topicTreemapFromYear = this.topicTreemapMaxYear - 4;
topicTreemapToYear = this.topicTreemapMaxYear;
selectedTopicTreemapNode?: string;
private topicTreemapReloadQueued = false;
private topicTreemapRequestId = 0;
constructor(private statisticsService: DashboardStatisticsService) {}
constructor(
private statisticsService: DashboardStatisticsService,
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
) {}
ngOnInit() {
this.restoreTopicTreemapState();
this.loadStatistics();
this.loadTopAuthors();
this.loadTopicHeatmap();
this.loadTopicTreemap();
this.loadDfgProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
}
private loadStatistics(): void {
@@ -83,6 +129,7 @@ export class DashboardComponent implements OnInit {
this.statisticsService.getPublicationCount(),
);
this.loadStatistic('persons', this.statisticsService.getPersonCount());
this.loadStatistic('patents', this.statisticsService.getPatentCount());
this.loadStatistic(
'eu_projects',
this.statisticsService.getEuProjectCount(),
@@ -108,6 +155,11 @@ export class DashboardComponent implements OnInit {
icon: 'menu_book',
entries: this.topAuthors?.works ?? [],
},
{
title: 'EU-Projekte',
icon: 'public',
entries: this.topAuthors?.eu_projects ?? [],
},
{
title: 'Patente',
icon: 'description',
@@ -118,7 +170,6 @@ export class DashboardComponent implements OnInit {
icon: 'account_tree',
entries: this.topAuthors?.projects ?? [],
stripAuthorTitle: true,
projectAuthors: true,
},
{ title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] },
];
@@ -137,13 +188,17 @@ export class DashboardComponent implements OnInit {
);
}
hasTopicHeatmapData(): boolean {
return (this.topicHeatmap?.fields ?? []).some(
hasTopicTreemapData(): boolean {
return (this.topicTreemap?.fields ?? []).some(
(field) =>
field.total > 0 || field.values.some((value) => value.count > 0),
);
}
hasDfgTopicData(): boolean {
return (this.dfgProjectTopics?.topics.length ?? 0) > 0;
}
setTopAuthorsWorksPeriod(period: TopAuthorsWorksPeriod): void {
if (period === this.topAuthorsWorksPeriod) return;
this.topAuthorsWorksPeriod = period;
@@ -168,30 +223,15 @@ export class DashboardComponent implements OnInit {
);
}
authorLink(dataset: TopAuthorDataset, entry: TopAuthor): string[] {
if (dataset.projectAuthors && entry.dfg_person_id) {
return ['/person', entry.id!, 'projects'];
}
authorLink(_dataset: TopAuthorDataset, entry: TopAuthor): string[] {
return ['/person', entry.id!, 'overview'];
}
authorQueryParams(
dataset: TopAuthorDataset,
entry: TopAuthor,
_dataset: TopAuthorDataset,
_entry: TopAuthor,
): Record<string, string | number> | null {
if (!dataset.projectAuthors || !entry.dfg_person_id) {
return null;
}
return {
project_type: 'dfg',
page: 0,
size: 10,
sort_by: 'title',
sort_direction: 'asc',
authorId: entry.dfg_person_id,
};
return null;
}
organizationName(): string {
@@ -206,35 +246,78 @@ export class DashboardComponent implements OnInit {
);
}
setTopicTreemapPeriod(period: TopicTreemapPeriod): void {
if (period === this.topicTreemapPeriod && period !== 'custom') return;
const currentYear = new Date().getFullYear();
this.topicTreemapPeriod = period;
if (period === 'last_5_years') {
this.topicTreemapFromYear = currentYear - 4;
this.topicTreemapToYear = currentYear;
} else if (period === 'last_10_years') {
this.topicTreemapFromYear = currentYear - 9;
this.topicTreemapToYear = currentYear;
} else if (period === 'all_time') {
this.topicTreemapFromYear = 1900;
this.topicTreemapToYear = currentYear;
}
this.loadTopicHeatmap();
personListQueryParams(): PersonListQueryParams {
return activeInstitutionPersonListQueryParams(
this.institutionRouteId(),
this.organizationName(),
);
}
onTopicTreemapYearChange(field: 'from' | 'to', value: string): void {
const year = Number(value);
if (!Number.isInteger(year)) return;
onTopicTreemapRangeChange(): void {
this.topicTreemapLoading = true;
this.topicTreemapError = false;
this.topicTreemapRequestId += 1;
this.updateTopicTreemapUrl();
if (this.topicTreemapReloadQueued) return;
this.topicTreemapReloadQueued = true;
setTimeout(() => {
this.topicTreemapReloadQueued = false;
this.loadTopicTreemap();
});
}
if (field === 'from') {
this.topicTreemapFromYear = year;
} else {
this.topicTreemapToYear = year;
onTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedTopicTreemapNode = nodeId;
this.updateTopicTreemapUrl();
}
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: topic,
},
);
}
private restoreTopicTreemapState(): void {
const params = this.route.snapshot.queryParamMap;
this.topicTreemapFromYear = this.parseTreemapYear(
params.get('treemapFrom'),
this.topicTreemapFromYear,
);
this.topicTreemapToYear = this.parseTreemapYear(
params.get('treemapTo'),
this.topicTreemapToYear,
);
if (this.topicTreemapFromYear > this.topicTreemapToYear) {
this.topicTreemapFromYear = this.topicTreemapToYear;
}
this.topicTreemapPeriod = 'custom';
this.loadTopicHeatmap();
this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined;
}
private updateTopicTreemapUrl(): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: {
treemapFrom: this.topicTreemapFromYear,
treemapTo: this.topicTreemapToYear,
treemapNode: this.selectedTopicTreemapNode ?? null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
private parseTreemapYear(value: string | null, fallback: number): number {
const year = Number(value);
return Number.isInteger(year) &&
year >= this.topicTreemapMinYear &&
year <= this.topicTreemapMaxYear
? year
: fallback;
}
private loadStatistic(
@@ -298,23 +381,83 @@ export class DashboardComponent implements OnInit {
});
}
private loadTopicHeatmap(): void {
private loadDfgProjectTopics(): void {
this.dfgTopicsLoading = true;
this.dfgTopicsError = false;
this.statisticsService
.getDfgProjectTopics()
.pipe(finalize(() => (this.dfgTopicsLoading = false)))
.subscribe({
next: (topics) => {
this.dfgProjectTopics = topics;
},
error: () => {
this.dfgTopicsError = true;
},
});
}
private loadEuProjectStatuses(): void {
this.euProjectStatusesLoading = true;
this.euProjectStatusesError = false;
this.statisticsService
.getEuProjectStatuses()
.pipe(finalize(() => (this.euProjectStatusesLoading = false)))
.subscribe({
next: (statuses) => {
this.euProjectStatuses = statuses;
},
error: () => {
this.euProjectStatusesError = true;
},
});
}
private loadBmbfProjectStatuses(): void {
this.bmbfProjectStatusesLoading = true;
this.bmbfProjectStatusesError = false;
this.statisticsService
.getBmbfProjectStatuses()
.pipe(finalize(() => (this.bmbfProjectStatusesLoading = false)))
.subscribe({
next: (statuses) => {
this.bmbfProjectStatuses = statuses;
},
error: () => {
this.bmbfProjectStatusesError = true;
},
});
}
private loadTopicTreemap(): void {
if (this.topicTreemapFromYear > this.topicTreemapToYear) {
this.topicHeatmapError = true;
this.topicTreemapLoading = false;
this.topicTreemapError = true;
return;
}
this.topicHeatmapLoading = true;
this.topicHeatmapError = false;
const requestId = ++this.topicTreemapRequestId;
this.topicTreemapLoading = true;
this.topicTreemapError = false;
this.statisticsService
.getTopicHeatmap(this.topicTreemapFromYear, this.topicTreemapToYear)
.pipe(finalize(() => (this.topicHeatmapLoading = false)))
.getTopicTreemap(this.topicTreemapFromYear, this.topicTreemapToYear)
.pipe(
finalize(() => {
if (requestId === this.topicTreemapRequestId) {
this.topicTreemapLoading = false;
}
}),
)
.subscribe({
next: (heatmap) => {
this.topicHeatmap = heatmap;
next: (treemap) => {
if (requestId === this.topicTreemapRequestId) {
this.topicTreemap = treemap;
}
},
error: () => {
this.topicHeatmapError = true;
if (requestId === this.topicTreemapRequestId) {
this.topicTreemapError = true;
}
},
});
}
@@ -0,0 +1,5 @@
@if (topics.length) {
<div echarts [options]="options" class="dfg-topic-donut-chart"></div>
} @else {
<p class="dfg-topic-donut-empty">Keine gematchten DFG-Topics vorhanden.</p>
}
@@ -1,9 +1,9 @@
.topic-treemap-chart {
.dfg-topic-donut-chart {
width: 100%;
height: 560px;
height: 440px;
}
.topic-treemap-empty {
.dfg-topic-donut-empty {
display: grid;
min-height: 260px;
margin: 0;
@@ -0,0 +1,111 @@
import { Component, Input, OnChanges } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { DfgProjectTopic } from '../dashboard-statistics.service';
@Component({
selector: 'app-dfg-topic-donut',
imports: [NgxEchartsDirective],
templateUrl: './dfg-topic-donut.component.html',
styleUrl: './dfg-topic-donut.component.scss',
})
export class DfgTopicDonutComponent implements OnChanges {
@Input() topics: DfgProjectTopic[] = [];
options: EChartsOption = {};
ngOnChanges(): void {
this.options = {
color: [
'#7255d9',
'#2563eb',
'#0891b2',
'#059669',
'#65a30d',
'#ca8a04',
'#ea580c',
'#dc2626',
'#db2777',
'#9333ea',
],
tooltip: {
trigger: 'item',
confine: true,
formatter: (params: any) =>
`<strong>${this.escapeHtml(String(params.name ?? ''))}</strong><br>${Number(params.value ?? 0).toLocaleString('de-DE')} DFG-Projekte`,
},
legend: {
type: 'scroll',
orient: 'vertical',
top: 'middle',
right: 12,
width: '38%',
textStyle: { color: '#334155' },
formatter: (name: string) => this.truncate(name, 42),
},
graphic: [
{
type: 'text',
left: '30%',
top: '46%',
style: {
text: `${this.topics.length}\nTopics`,
align: 'center',
fill: '#0f172a',
fontSize: 18,
fontWeight: 700,
lineHeight: 25,
},
},
],
series: [
{
name: 'DFG-Topics',
type: 'pie',
radius: ['42%', '72%'],
center: ['32%', '50%'],
avoidLabelOverlap: true,
minAngle: 3,
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
borderRadius: 5,
},
label: { show: false },
emphasis: {
scaleSize: 8,
label: {
show: true,
formatter: '{b}\n{c} Projekte',
fontWeight: 700,
},
},
data: this.topics.map((topic) => ({
id: topic.id,
name: topic.name,
value: topic.project_count,
})),
},
],
};
}
private truncate(value: string, maximum: number): string {
return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;
}
private escapeHtml(value: string): string {
return value.replace(
/[&<>'"]/g,
(character) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
})[character] ?? character,
);
}
}
@@ -0,0 +1,6 @@
<div
echarts
[options]="options"
class="eu-project-status-chart"
role="img"
aria-label="Gestapeltes Balkendiagramm zum Status der EU- und Bund-Projekte"></div>
@@ -0,0 +1,4 @@
.eu-project-status-chart {
width: 100%;
height: 300px;
}
@@ -0,0 +1,102 @@
import { Component, Input, OnChanges } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import {
BmbfProjectStatusStatistics,
EuProjectStatusStatistics,
} from '../dashboard-statistics.service';
@Component({
selector: 'app-eu-project-status-chart',
imports: [NgxEchartsDirective],
templateUrl: './eu-project-status-chart.component.html',
styleUrl: './eu-project-status-chart.component.scss',
})
export class EuProjectStatusChartComponent implements OnChanges {
@Input({ required: true }) statuses!: EuProjectStatusStatistics;
@Input({ required: true }) bmbfStatuses!: BmbfProjectStatusStatistics;
options: EChartsOption = {};
ngOnChanges(): void {
const values = [
{
name: 'Laufend',
data: [this.statuses?.ongoing ?? 0, this.bmbfStatuses?.ongoing ?? 0],
color: '#2563eb',
},
{
name: 'Kommend',
data: [this.statuses?.upcoming ?? 0, this.bmbfStatuses?.upcoming ?? 0],
color: '#f59e0b',
},
{
name: 'Abgeschlossen',
data: [
this.statuses?.completed ?? 0,
this.bmbfStatuses?.completed ?? 0,
],
color: '#64748b',
},
];
this.options = {
color: values.map((item) => item.color),
animationDuration: 500,
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
confine: true,
valueFormatter: (value) =>
`${Number(value ?? 0).toLocaleString('de-DE')} Projekte`,
},
legend: {
top: 0,
left: 'center',
data: values.map((item) => item.name),
textStyle: { color: '#334155' },
},
grid: { top: 56, right: 24, bottom: 30, left: 24, containLabel: true },
xAxis: {
type: 'value',
minInterval: 1,
name: 'Anzahl Projekte',
nameLocation: 'middle',
nameGap: 28,
axisLabel: { color: '#64748b' },
splitLine: { lineStyle: { color: '#e2e8f0' } },
},
yAxis: {
type: 'category',
data: ['EU-Projekte', 'Bund-Projekte'],
axisTick: { show: false },
axisLine: { show: false },
axisLabel: { color: '#334155', fontWeight: 600 },
},
series: values.map((item, index) => ({
name: item.name,
type: 'bar',
stack: 'status',
barWidth: 54,
data: item.data,
label: {
show: true,
position: 'inside',
formatter: (params) =>
Number(params.value ?? 0) > 0 ? String(params.value) : '',
color: '#ffffff',
fontWeight: 700,
},
itemStyle: {
borderRadius:
index === 0
? [6, 0, 0, 6]
: index === values.length - 1
? [0, 6, 6, 0]
: 0,
},
})),
};
}
}
@@ -1,7 +0,0 @@
@if (heatmap?.fields?.length) {
<div echarts [options]="options" class="topic-treemap-chart"></div>
} @else {
<p class="topic-treemap-empty">
{{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }}
</p>
}
@@ -1,212 +0,0 @@
import { Component, Input, OnChanges } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { TopicHeatmap } from '../dashboard-statistics.service';
@Component({
selector: 'app-topic-heatmap',
imports: [NgxEchartsDirective],
templateUrl: './topic-heatmap.component.html',
styleUrl: './topic-heatmap.component.scss',
})
export class TopicHeatmapComponent implements OnChanges {
@Input() heatmap?: TopicHeatmap;
@Input() loading = false;
options: EChartsOption = {};
private readonly colors = [
'#2563eb',
'#059669',
'#d97706',
'#dc2626',
'#7c3aed',
'#0284c7',
'#ea580c',
'#4f46e5',
'#0f766e',
'#be123c',
];
ngOnChanges(): void {
this.options = this.buildOptions();
}
private buildOptions(): EChartsOption {
const fields = this.heatmap?.fields ?? [];
const data = fields.map((field) => ({
id: field.id,
name: field.name,
value: field.total || this.totalCount(field.values),
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
color: '#ffffff',
fontWeight: 700,
lineHeight: 18,
overflow: 'truncate' as const,
},
children: field.values
.filter((value) => value.count > 0)
.map((value) => ({
name: String(value.year),
value: value.count,
share: value.share,
})),
}));
return {
tooltip: {
formatter: (params: any) => {
const count = Number(params.value ?? 0);
const share =
typeof params.data?.share === 'number'
? `<br />Anteil im Jahr: <strong>${(params.data.share * 100).toFixed(1)}%</strong>`
: '';
return `${params.name}<br /><strong>${count}</strong> Publikationen${share}`;
},
},
series: [
{
name: 'Fields',
type: 'treemap',
data,
roam: false,
nodeClick: 'zoomToNode',
sort: 'desc',
drillDownIcon: '',
breadcrumb: {
show: true,
bottom: 0,
height: 24,
left: 8,
right: 8,
emptyItemWidth: 80,
itemStyle: {
color: '#f8fafc',
borderColor: '#cbd5e1',
borderWidth: 1,
textStyle: {
color: '#334155',
fontWeight: 600,
},
},
emphasis: {
itemStyle: {
color: '#e0f2fe',
borderColor: '#93c5fd',
textStyle: {
color: '#0f172a',
fontWeight: 700,
},
},
},
},
color: this.colors,
colorMappingBy: 'id',
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
color: '#ffffff',
fontWeight: 600,
lineHeight: 18,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
overflow: 'truncate',
},
upperLabel: {
show: true,
formatter: (params: any) =>
`${params.name} · ${this.formatCount(params.value)}`,
height: 30,
color: '#ffffff',
fontWeight: 700,
overflow: 'truncate',
},
levels: [
{
color: this.colors,
label: {
show: true,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
{
color: this.colors,
label: {
show: true,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
{
colorSaturation: [0.45, 0.78],
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
color: '#ffffff',
fontWeight: 700,
lineHeight: 18,
overflow: 'truncate',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 2,
gapWidth: 2,
},
},
],
leafDepth: 1,
top: 8,
right: 8,
bottom: 32,
left: 8,
animationDurationUpdate: 450,
emphasis: {
focus: 'self',
label: {
color: '#ffffff',
},
},
itemStyle: {
borderRadius: 4,
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
],
};
}
private totalCount(values: Array<{ count: number }>): number {
return values.reduce((sum, value) => sum + value.count, 0);
}
private formatCount(value: unknown): string {
return Number(value ?? 0).toLocaleString('de-DE');
}
}
@@ -0,0 +1,119 @@
<div class="dialog-title" mat-dialog-title>
<div class="dialog-heading">
<div>
<span class="dialog-eyebrow">Topic Insights</span>
<h2>Keyword Wordcloud</h2>
<p>Die wichtigsten Begriffe zum ausgewählten Forschungsthema</p>
</div>
</div>
<button
class="dialog-close"
mat-icon-button
type="button"
aria-label="Dialog schließen"
mat-dialog-close>
<mat-icon>close</mat-icon>
</button>
</div>
<mat-dialog-content>
<div class="topic-context-card" aria-label="Ausgewählte Themenhierarchie">
<div class="topic-context-item">
<span
class="topic-context-icon topic-context-icon--field"
aria-hidden="true">
<mat-icon>category</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Field</span>
<strong [title]="data.fieldName || ''">{{
data.fieldName || '–'
}}</strong>
</span>
</div>
<mat-icon class="topic-context-arrow" aria-hidden="true"
>chevron_right</mat-icon
>
<div class="topic-context-item">
<span
class="topic-context-icon topic-context-icon--subfield"
aria-hidden="true">
<mat-icon>account_tree</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Subfield</span>
<strong [title]="data.subfieldName || ''">{{
data.subfieldName || '–'
}}</strong>
</span>
</div>
<mat-icon class="topic-context-arrow" aria-hidden="true"
>chevron_right</mat-icon
>
<div class="topic-context-item topic-context-item--topic">
<span
class="topic-context-icon topic-context-icon--topic"
aria-hidden="true">
<mat-icon>label</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Topic</span>
<strong [title]="data.topicName">{{ data.topicName }}</strong>
</span>
</div>
</div>
<section class="word-cloud-panel" aria-labelledby="word-cloud-heading">
<div class="word-cloud-panel-header">
<div>
<h3 id="word-cloud-heading">Top Keywords</h3>
<p>Die Schriftgröße entspricht der Anzahl der Publikationen.</p>
</div>
@if (!loading && !loadFailed && words.length) {
<span class="word-count">{{ words.length }} Begriffe</span>
}
</div>
@if (loading) {
<div class="word-cloud-state">
<span class="state-icon state-icon--loading" aria-hidden="true">
<mat-icon>hourglass_top</mat-icon>
</span>
<strong>Wordcloud wird erstellt</strong>
<span>Die wichtigsten Keywords werden geladen …</span>
</div>
} @else if (loadFailed) {
<div class="word-cloud-state word-cloud-state--error">
<span class="state-icon" aria-hidden="true"
><mat-icon>cloud_off</mat-icon></span
>
<strong>Wordcloud nicht verfügbar</strong>
<span>Die Keywords konnten nicht geladen werden.</span>
</div>
} @else if (words.length) {
<div class="word-cloud-chart" aria-label="Wordcloud verwandter Themen">
@for (word of words; track word.id) {
<span
class="word-cloud-word"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[title]="word.name + ': ' + word.count + ' Publikationen'">
{{ word.name }}
</span>
}
</div>
} @else {
<div class="word-cloud-state">
<span class="state-icon" aria-hidden="true"
><mat-icon>search_off</mat-icon></span
>
<strong>Keine Keywords gefunden</strong>
<span
>Für dieses Topic sind im gewählten Zeitraum keine Daten
vorhanden.</span
>
</div>
}
</section>
</mat-dialog-content>
@@ -0,0 +1,316 @@
.dialog-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
padding: 24px 28px 20px;
border-bottom: 1px solid var(--sg-border, #dde5f2);
background: linear-gradient(135deg, #ffffff 52%, #f6f0ff 100%);
h2 {
margin: 1px 0 3px;
color: var(--sg-text, #101a3d);
font-family: 'Montserrat', sans-serif;
font-size: 1.375rem;
font-weight: 700;
line-height: 1.25;
}
p {
margin: 0;
color: var(--sg-text-muted, #64708f);
font-size: 0.8125rem;
font-weight: 400;
}
}
.dialog-heading {
display: flex;
align-items: center;
}
.dialog-eyebrow {
display: block;
color: #7255d9;
font-size: 0.6875rem;
font-weight: 700;
letter-spacing: 0.08em;
line-height: 1.2;
text-transform: uppercase;
}
.dialog-close {
flex: 0 0 auto;
color: var(--sg-text-muted, #64708f);
&:hover {
background: #f1f3f7;
color: var(--sg-text, #101a3d);
}
}
mat-dialog-content {
min-height: 410px;
padding: 20px 28px 28px !important;
background: #ffffff;
}
.topic-context-card {
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center;
gap: 12px;
margin-bottom: 18px;
padding: 12px;
border: 1px solid var(--sg-border, #dde5f2);
border-radius: 12px;
background: var(--sg-surface-muted, #f7f9ff);
}
.topic-context-item {
display: flex;
min-width: 0;
align-items: center;
gap: 10px;
padding: 5px 6px;
}
.topic-context-icon {
display: grid;
width: 34px;
height: 34px;
flex: 0 0 34px;
place-items: center;
border-radius: 9px;
mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
}
.topic-context-icon--field {
border: 1px solid #bdd4ff;
background: #f0f6ff;
color: #0b63ce;
}
.topic-context-icon--subfield {
border: 1px solid #bdebcf;
background: #effaf3;
color: #24834f;
}
.topic-context-icon--topic {
border: 1px solid #d8cafe;
background: #f6f0ff;
color: #7255d9;
}
.topic-context-copy {
display: flex;
min-width: 0;
flex-direction: column;
gap: 2px;
strong {
overflow: hidden;
color: #334155;
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.35;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.topic-context-item--topic strong {
color: #7255d9;
}
.topic-context-label {
color: var(--sg-text-soft, #8a95b3);
font-size: 0.625rem;
font-weight: 700;
letter-spacing: 0.07em;
line-height: 1.2;
text-transform: uppercase;
}
.topic-context-arrow {
width: 18px;
height: 18px;
color: #a8b2c8;
font-size: 18px;
}
.word-cloud-panel {
overflow: hidden;
border: 1px solid var(--sg-border, #dde5f2);
border-radius: 16px;
background: #ffffff;
box-shadow: var(--sg-shadow-sm);
}
.word-cloud-panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 18px;
border-bottom: 1px solid #e8edf5;
h3 {
margin: 0 0 2px;
color: var(--sg-text, #101a3d);
font-family: 'Montserrat', sans-serif;
font-size: 0.9375rem;
font-weight: 700;
}
p {
margin: 0;
color: var(--sg-text-muted, #64708f);
font-size: 0.75rem;
}
}
.word-count {
flex: 0 0 auto;
padding: 5px 9px;
border: 1px solid #d8cafe;
border-radius: 999px;
background: #f6f0ff;
color: #7255d9;
font-size: 0.6875rem;
font-weight: 700;
}
.word-cloud-chart {
display: flex;
min-height: 280px;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 14px 20px;
padding: 30px 34px;
background:
radial-gradient(
circle at 15% 20%,
rgba(114, 85, 217, 0.06),
transparent 28%
),
radial-gradient(
circle at 85% 75%,
rgba(11, 99, 206, 0.05),
transparent 30%
),
#ffffff;
}
.word-cloud-word {
padding: 3px 5px;
border-radius: 6px;
cursor: help;
line-height: 1.1;
text-align: center;
transition:
transform 150ms ease,
background-color 150ms ease;
&:hover {
background: rgba(241, 243, 247, 0.9);
transform: translateY(-2px);
}
}
.word-cloud-state {
display: flex;
min-height: 280px;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 6px;
padding: 24px;
color: var(--sg-text-muted, #64708f);
text-align: center;
strong {
margin-top: 4px;
color: var(--sg-text, #101a3d);
font-size: 0.9375rem;
}
> span:last-child {
font-size: 0.8125rem;
}
}
.state-icon {
display: grid;
width: 46px;
height: 46px;
place-items: center;
border-radius: 50%;
background: #f1f3f7;
color: #64708f;
}
.state-icon--loading {
background: #f6f0ff;
color: #7255d9;
animation: state-pulse 1.4s ease-in-out infinite;
}
.word-cloud-state--error .state-icon {
background: #fff1f5;
color: #d12f61;
}
@keyframes state-pulse {
50% {
box-shadow: 0 0 0 8px rgba(114, 85, 217, 0.08);
transform: scale(1.04);
}
}
@media (max-width: 700px) {
.dialog-title {
padding: 20px;
}
mat-dialog-content {
padding: 16px 20px 20px !important;
}
.topic-context-card {
grid-template-columns: 1fr;
gap: 4px;
}
.topic-context-arrow {
display: none;
}
.topic-context-copy strong {
white-space: normal;
}
.word-cloud-chart {
min-height: 240px;
gap: 10px 14px;
padding: 24px 18px;
}
}
@media (prefers-reduced-motion: reduce) {
.state-icon--loading {
animation: none;
}
.word-cloud-word {
transition: none;
}
}
@@ -0,0 +1,99 @@
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import {
DashboardStatisticsService,
TopicWordCloudWord,
} from '../dashboard-statistics.service';
export interface TopicWordCloudDialogData {
topicId: string;
topicName: string;
fieldName?: string;
subfieldName?: string;
fromYear?: number;
toYear?: number;
}
interface DisplayWord extends TopicWordCloudWord {
color: string;
fontSize: number;
fontWeight: number;
}
@Component({
selector: 'app-topic-wordcloud-dialog',
standalone: true,
imports: [CommonModule, MatButtonModule, MatDialogModule, MatIconModule],
templateUrl: './topic-wordcloud-dialog.component.html',
styleUrl: './topic-wordcloud-dialog.component.scss',
})
export class TopicWordCloudDialogComponent {
readonly data = inject<TopicWordCloudDialogData>(MAT_DIALOG_DATA);
private readonly statisticsService = inject(DashboardStatisticsService);
private readonly destroyRef = inject(DestroyRef);
words: DisplayWord[] = [];
loading = true;
loadFailed = false;
private readonly colors = [
'#2563eb',
'#059669',
'#d97706',
'#dc2626',
'#7c3aed',
'#0284c7',
'#ea580c',
'#4f46e5',
'#0f766e',
'#be123c',
];
constructor() {
this.statisticsService
.getTopicWordCloud(
this.data.topicId,
this.data.fromYear,
this.data.toYear,
)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (response) => {
this.words = this.buildWords(response.words);
this.loading = false;
},
error: () => {
this.loading = false;
this.loadFailed = true;
},
});
}
private buildWords(words: TopicWordCloudWord[]): DisplayWord[] {
if (!words.length) return [];
const values = words.map((word) => word.count);
const minimum = Math.min(...values);
const maximum = Math.max(...values);
const scaled = words.map((word, index) => {
const intensity =
maximum === minimum ? 1 : (word.count - minimum) / (maximum - minimum);
return {
...word,
color: this.colors[index % this.colors.length],
fontSize: Math.round(14 + intensity * 24),
fontWeight: intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400,
};
});
const centred: DisplayWord[] = [];
scaled.forEach((word, index) => {
if (index % 2 === 0) centred.push(word);
else centred.unshift(word);
});
return centred;
}
}
@@ -22,36 +22,45 @@
<div class="patents-content">
<div class="patents-list">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Matching:</span>
<select
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="rule"></mat-icon>
<mat-select
[value]="activeMatchType"
(change)="setMatchType($any($event.target).value)">
<option value="all">Alle</option>
<option value="institution">Institution</option>
<option value="name">Name</option>
<option value="both">Beides</option>
</select>
</label>
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select
(selectionChange)="setMatchType($event.value)">
<mat-select-trigger>Matching</mat-select-trigger>
<mat-option value="all">Alle</mat-option>
<mat-option value="institution">Institution</mat-option>
<mat-option value="name">Name</mat-option>
<mat-option value="both">Beides</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="filter_alt"></mat-icon>
<mat-select
[value]="activeFilter"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select
(selectionChange)="setFilter($event.value)">
<mat-select-trigger>Filter nach Quelle</mat-select-trigger>
<mat-option value="all">Alle</mat-option>
<mat-option value="EPO">EPO</mat-option>
<mat-option value="USPTO">USPTO</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortMode"
(change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="date">Datum</mat-option>
<mat-option value="title">Titel</mat-option>
</mat-select>
</mat-form-field>
</div>
<table>
@@ -164,9 +173,14 @@
</div>
<div class="stat">
<span class="stat-label">Match-Typ</span>
<span class="stat-value">{{
getMatchTypeLabel(selectedPatent)
}}</span>
<span class="stat-value">
<span
class="match-badge match-badge--{{
selectedPatent.match_type
}}">
{{ getMatchTypeLabel(selectedPatent) }}
</span>
</span>
</div>
@if (getPublicationStageLabel(selectedPatent); as stageLabel) {
<div class="stat">
@@ -227,21 +241,21 @@
}
</p>
<div class="overview-stats">
<div class="overview-stat">
<div class="overview-stat overview-stat--total">
<span class="overview-value">{{ totalPatents }}</span>
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat">
<div class="overview-stat overview-stat--institution">
<span class="overview-value">{{
getInstitutionMatchCount()
}}</span>
<span class="overview-label">Institution</span>
</div>
<div class="overview-stat">
<div class="overview-stat overview-stat--name">
<span class="overview-value">{{ getNameMatchCount() }}</span>
<span class="overview-label">Name</span>
</div>
<div class="overview-stat">
<div class="overview-stat overview-stat--both">
<span class="overview-value">{{ getBothMatchCount() }}</span>
<span class="overview-label">Beides</span>
</div>
@@ -26,29 +26,9 @@
gap: 16px;
}
.sort-control {
display: inline-flex;
align-items: center;
gap: 6px;
.patents-toolbar-field {
width: fit-content;
padding: 10px 14px;
border-radius: 20px;
background: #f2f2f2;
color: #333;
font-size: 14px;
span {
color: #555;
}
select {
border: 0;
background: transparent;
color: #111827;
font: inherit;
cursor: pointer;
outline: none;
}
min-width: 180px;
}
.patents-content {
@@ -247,6 +227,34 @@
color: #888;
margin-top: 4px;
}
&--total {
.overview-value,
.overview-label {
color: #0b63ce;
}
}
&--institution {
.overview-value,
.overview-label {
color: #6d28d9;
}
}
&--name {
.overview-value,
.overview-label {
color: #c2410c;
}
}
&--both {
.overview-value,
.overview-label {
color: #047857;
}
}
}
.overview-hint {
@@ -1,6 +1,9 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { PatentsService } from '../../api/api/patents.service';
import { OrgPatentEntry } from '../../api/model/orgPatentEntry';
import {
@@ -15,7 +18,14 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
@Component({
selector: 'app-institution-patents',
imports: [CommonModule, RouterLink, LoadingComponent],
imports: [
CommonModule,
RouterLink,
LoadingComponent,
MatFormFieldModule,
MatSelectModule,
MatIconModule,
],
templateUrl: './institution-patents.component.html',
styleUrl: './institution-patents.component.scss',
})
@@ -9,12 +9,12 @@ import {
} from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import {
BundProject,
BundProjectPage,
EuOrganizationProjectSummary,
EuOrganizationProjectSummaryPage,
EuCordisProjectSearchPage,
InstitutionFunderSummary,
EuCordisProjectSummary,
} from '../../api';
import { BundProjectSummary } from '../../api/model/bundProjectSummary';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
@@ -77,12 +77,13 @@ export class InstitutionProjectsComponent implements OnInit {
fundingEndTmp = viewChild.required<TemplateRef<any>>('fundingEndTmp');
fundingAmountTmp = viewChild.required<TemplateRef<any>>('fundingAmountTmp');
cordisEuProjectPage = input.required<EuOrganizationProjectSummaryPage>();
cordisEuProjectPage = input.required<EuCordisProjectSearchPage>();
euProjectColumns: GenericColumn<EuProjectRow>[] = [];
euProjectData: EuProjectRow[] = [];
euProjectActionsTmp = viewChild.required<TemplateRef<any>>(
'euProjectActionsTmp',
);
acronymTmp = viewChild.required<TemplateRef<any>>('acronymTmp');
bundProjectPage = input.required<BundProjectPage>();
bundProjectColumns: GenericColumn<BundProjectRow>[] = [];
@@ -165,6 +166,7 @@ export class InstitutionProjectsComponent implements OnInit {
type: 'accessor',
accessorKey: 'topic',
},
{
id: 'funding_start',
header: 'Förderbeginn',
@@ -181,7 +183,7 @@ export class InstitutionProjectsComponent implements OnInit {
},
{
id: 'funding_amount',
header: 'Fördersumme',
header: 'Fördersumme (EC)',
type: 'accessor',
accessorKey: 'funding_amount',
cellTemplate: this.fundingAmountTmp(),
@@ -230,19 +232,19 @@ export class InstitutionProjectsComponent implements OnInit {
];
}
transformEuRow(project: EuOrganizationProjectSummary): EuProjectRow {
transformEuRow(project: EuCordisProjectSummary): EuProjectRow {
return {
id: project.project_id,
id: project.id,
topic: project.title || '',
funding_start: project.start_date
? new Date(project.start_date)
: new Date(0),
funding_end: project.end_date ? new Date(project.end_date) : new Date(0),
funding_amount: Number(project.ec_contribution) || 0,
funding_amount: Number(project.ec_max_contribution) || 0,
};
}
transformBundRow(project: BundProject): BundProjectRow {
transformBundRow(project: BundProjectSummary): BundProjectRow {
return {
id: project.funding_code || '',
topic: project.topic || '',
@@ -37,7 +37,8 @@
<app-publication-table
[page]="institutionWorkPage()"
[authorFilterEnabled]="true" />
[authorFilterEnabled]="true"
[rawOaInstitutionId]="rawOaInstitutionId()" />
<app-query-param-paginator
[total]="total()"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core';
import { Component, computed, inject, input } from '@angular/core';
import { PublicationTableComponent } from '../../shared/ui/publication-table/publication-table.component';
import {
AuthorPage,
@@ -11,6 +11,7 @@ import { PublicationFilterComponent } from '../../shared/ui/publication-filters/
import { PrimaryCategoryYearAggregationChartComponent } from '../../shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component';
import { MatExpansionModule } from '@angular/material/expansion';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-institution-publications',
@@ -26,6 +27,8 @@ import { CommonModule } from '@angular/common';
styleUrl: './institution-publications.component.scss',
})
export class InstitutionPublicationsComponent {
private readonly activatedRoute = inject(ActivatedRoute);
institutionWorkPage = input.required<WorkPageV2>();
selectedAuthorsPage = input.required<AuthorPage>();
selectedTopicsPage = input.required<TopicPageV2>();
@@ -38,4 +41,9 @@ export class InstitutionPublicationsComponent {
const page = this.primaryCategoryYearAggregationPage();
return (page?.elements?.length ?? 0) > 0;
});
rawOaInstitutionId = computed(() => {
const params = this.activatedRoute.parent?.snapshot.paramMap;
return params?.get('institutionId') ?? undefined;
});
}
@@ -54,18 +54,21 @@ export class InstitutionComponent implements OnInit {
this.institution = institution;
});
const institutionId = this.activatedRoute.snapshot.paramMap.get('institutionId');
const institutionId =
this.activatedRoute.snapshot.paramMap.get('institutionId');
if (!institutionId) return;
// The "Patente" tab only makes sense once org_patents has been indexed for
// this institution (currently a manual, ~30-40 min-per-institution process),
// so only show it once we know there is actually data behind it.
this.patentsApi.getOrgPatentsByInstitution(institutionId, undefined, 0, 0).subscribe({
next: (result) => {
if ((result.patent_count ?? 0) > 0) {
this.links = [...this.links, PATENTS_LINK];
}
},
});
this.patentsApi
.getOrgPatentsByInstitution(institutionId, undefined, 0, 0)
.subscribe({
next: (result) => {
if ((result.patent_count ?? 0) > 0) {
this.links = [...this.links, PATENTS_LINK];
}
},
});
}
}
@@ -59,17 +59,21 @@ export class InstitutionsComponent {
const id = this.extractInstitutionId(institution);
if (!id || this.patentsAvailable.has(id)) continue;
this.patentsAvailable.set(id, false);
this.patentsApi.getOrgPatentsByInstitution(id, undefined, 0, 0).subscribe({
next: (result) => {
this.patentsAvailable.set(id, (result.patent_count ?? 0) > 0);
},
});
this.patentsApi
.getOrgPatentsByInstitution(id, undefined, 0, 0)
.subscribe({
next: (result) => {
this.patentsAvailable.set(id, (result.patent_count ?? 0) > 0);
},
});
}
});
}
hasPatents(institution: Institution): boolean {
return this.patentsAvailable.get(this.extractInstitutionId(institution)) ?? false;
return (
this.patentsAvailable.get(this.extractInstitutionId(institution)) ?? false
);
}
sortingOptions: SelectorOption[] = [
@@ -0,0 +1,97 @@
<h2 mat-dialog-title>Logs · {{ data.task.name }}</h2>
<mat-dialog-content>
@if (runsLoading() && runs().length === 0) {
<div class="runs-loading">
<mat-progress-spinner
diameter="24"
mode="indeterminate"></mat-progress-spinner>
<span>Läufe werden geladen …</span>
</div>
} @else if (runsError()) {
<p class="logs-error">{{ runsError() }}</p>
} @else if (runs().length === 0) {
<p class="no-logs">Für diesen Job liegt noch kein Lauf vor.</p>
} @else {
<mat-form-field appearance="outline" class="run-select">
<mat-label>Lauf auswählen</mat-label>
<mat-select
[value]="selectedRunId()"
(selectionChange)="onRunSelected($event.value)">
@for (run of runs(); track run.id) {
<mat-option [value]="run.id">
#{{ run.id }} · {{ statusMeta(run.status!).label }} ·
{{ formatUtcDateAsLocal(run.started_at) }}
@if (run.exit_code != null) {
· Exit {{ run.exit_code }}
}
@if (formatRunDuration(run); as dur) {
· {{ dur }}
}
</mat-option>
}
</mat-select>
</mat-form-field>
<div class="logs-header">
<div class="run-meta">
<span>Lauf #{{ selectedRunId() }}</span>
@if (runStatus()) {
<span
class="task-status"
[ngClass]="statusMeta(runStatus()!).cssClass">
<mat-icon>{{ statusMeta(runStatus()!).icon }}</mat-icon>
{{ statusMeta(runStatus()!).label }}
</span>
}
@if (selectedRun(); as run) {
@if (runStatus() === 'running' || runStatus() === 'stopping') {
@if (formatRunElapsed(run, nowMs()); as elapsed) {
<span class="run-duration">läuft seit {{ elapsed }}</span>
}
} @else if (formatRunDuration(run); as dur) {
<span class="run-duration">Dauer: {{ dur }}</span>
}
}
<span class="logs-hint">zeigt letzte 200 Zeilen</span>
</div>
<div class="logs-actions">
<button
mat-stroked-button
type="button"
[disabled]="selectedRunId() == null"
(click)="downloadLogs()">
<mat-icon>download</mat-icon>
Herunterladen
</button>
<button
mat-icon-button
type="button"
aria-label="Logs aktualisieren"
matTooltip="Logs aktualisieren"
matTooltipPosition="above"
[disabled]="loading() || runsLoading()"
(click)="loadRuns()">
<mat-icon>refresh</mat-icon>
</button>
</div>
</div>
<div #logsPanel class="logs-panel" (scroll)="onLogsScroll()">
@if (loading() && !logs()) {
<div class="logs-loading">
<mat-progress-spinner
diameter="20"
mode="indeterminate"></mat-progress-spinner>
<span>Logs werden geladen …</span>
</div>
} @else {
<pre>{{ logs() }}</pre>
}
</div>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Schließen</button>
</mat-dialog-actions>
@@ -0,0 +1,155 @@
.no-logs {
color: #64748b;
margin: 0;
}
.runs-loading {
display: flex;
align-items: center;
gap: 10px;
min-height: 120px;
color: #64748b;
}
.logs-error {
margin: 0;
padding: 16px;
border-radius: 6px;
background: #fef2f2;
color: #991b1b;
}
.logs-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.run-meta {
display: flex;
align-items: center;
gap: 12px;
font-size: 13px;
color: #64748b;
}
.logs-actions {
display: flex;
gap: 8px;
flex-shrink: 0;
}
.task-status {
display: inline-flex;
align-items: center;
gap: 4px;
font-weight: 600;
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
&--success {
color: #166534;
}
&--failed {
color: #991b1b;
}
&--running {
color: #92400e;
}
&--stopped {
color: #64748b;
}
&--idle {
color: #64748b;
}
}
.logs-panel {
background: #0f172a;
border-radius: 6px;
padding: 12px 14px;
min-width: 520px;
max-width: 80vw;
min-height: 120px;
max-height: 55vh;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #64748b #1e293b;
&::-webkit-scrollbar {
width: 12px;
height: 12px;
}
&::-webkit-scrollbar-track {
background: #1e293b;
border-radius: 6px;
}
&::-webkit-scrollbar-thumb {
background: #64748b;
border-radius: 6px;
border: 3px solid #0f172a;
}
&::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
pre {
margin: 0;
color: #e2e8f0;
font-family: 'Roboto Mono', ui-monospace, monospace;
font-size: 12px;
white-space: pre-wrap;
word-break: break-word;
}
.logs-loading {
color: #cbd5e1;
}
}
.logs-loading {
display: flex;
align-items: center;
gap: 10px;
color: #64748b;
font-size: 13px;
}
.run-select {
width: 100%;
margin-top: 8px;
}
.logs-hint {
color: #94a3b8;
font-size: 12px;
}
.run-duration {
font-size: 13px;
color: #475569;
}
@media (max-width: 640px) {
.logs-header {
flex-direction: column;
align-items: stretch;
}
.logs-panel {
min-width: 0;
}
}
@@ -0,0 +1,196 @@
import { CommonModule } from '@angular/common';
import {
Component,
DestroyRef,
ElementRef,
OnInit,
computed,
inject,
signal,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { finalize, timer } from 'rxjs';
import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api';
import {
formatRunDuration,
formatRunElapsed,
formatUtcDateAsLocal,
statusMeta,
} from '../jobs.utils';
export interface JobLogsDialogData {
task: BackgroundJobTask;
}
@Component({
selector: 'app-job-logs-dialog',
imports: [
CommonModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatProgressSpinnerModule,
MatSelectModule,
MatTooltipModule,
],
templateUrl: './job-logs-dialog.component.html',
styleUrl: './job-logs-dialog.component.scss',
standalone: true,
})
export class JobLogsDialogComponent implements OnInit {
private readonly dialogRef = inject(MatDialogRef<JobLogsDialogComponent>);
private readonly backgroundJobsService = inject(BackgroundJobsService);
private readonly destroyRef = inject(DestroyRef);
protected readonly data = inject<JobLogsDialogData>(MAT_DIALOG_DATA);
protected readonly statusMeta = statusMeta;
protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal;
protected readonly formatRunDuration = formatRunDuration;
protected readonly formatRunElapsed = formatRunElapsed;
protected readonly runs = signal<JobRun[]>([]);
protected readonly runsLoading = signal(false);
protected readonly runsError = signal<string | null>(null);
protected readonly selectedRunId = signal<number | null>(null);
protected readonly loading = signal(false);
protected readonly logs = signal<string>('');
protected readonly runStatus = signal<string | null>(null);
protected readonly nowMs = signal(Date.now());
protected readonly selectedRun = computed(
() => this.runs().find((run) => run.id === this.selectedRunId()) ?? null,
);
private readonly logsPanel = viewChild<ElementRef<HTMLElement>>('logsPanel');
private followTail = true;
private readonly followThresholdPx = 24;
ngOnInit(): void {
this.loadRuns(true);
timer(5000, 5000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.loadRuns());
timer(1000, 1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.nowMs.set(Date.now()));
}
protected loadRuns(selectLatest = false): void {
if (this.runsLoading() || this.loading()) return;
this.runsLoading.set(true);
this.runsError.set(null);
this.backgroundJobsService
.getBackgroundJobTaskRuns(
this.data.task.id,
50,
undefined,
'body',
false,
{ transferCache: false },
)
.pipe(finalize(() => this.runsLoading.set(false)))
.subscribe({
next: (runs) => {
this.runs.set(runs);
const selected = selectLatest
? runs[0]
: (runs.find((run) => run.id === this.selectedRunId()) ?? runs[0]);
if (selected) {
this.selectRun(selected);
}
},
error: () => {
this.runsError.set('Läufe konnten nicht geladen werden.');
},
});
}
protected selectRun(run: JobRun): void {
if (run.id == null) return;
this.selectedRunId.set(run.id);
this.runStatus.set(run.status ?? null);
this.loadLogs();
}
protected onRunSelected(runId: number): void {
const run = this.runs().find((item) => item.id === runId);
if (run) {
this.followTail = true;
this.selectRun(run);
}
}
protected onLogsScroll(): void {
const panel = this.logsPanel()?.nativeElement;
if (!panel) return;
const distanceFromBottom =
panel.scrollHeight - panel.scrollTop - panel.clientHeight;
this.followTail = distanceFromBottom <= this.followThresholdPx;
}
private scrollToBottom(): void {
setTimeout(() => {
const panel = this.logsPanel()?.nativeElement;
if (panel) panel.scrollTop = panel.scrollHeight;
});
}
protected loadLogs(): void {
const runId = this.selectedRunId();
if (runId == null) return;
this.loading.set(true);
this.backgroundJobsService
.getBackgroundJobRunLogs(runId, undefined, 'body', false, {
transferCache: false,
})
.pipe(finalize(() => this.loading.set(false)))
.subscribe({
next: (result) => {
if (!result) {
this.logs.set('Die Log-Anfrage hat keine Daten zurückgegeben.');
return;
}
this.logs.set(result.logs || 'Keine Logs vorhanden.');
this.runStatus.set(result.status);
if (this.followTail) this.scrollToBottom();
},
error: () => {
this.logs.set('Logs konnten nicht geladen werden.');
},
});
}
protected downloadLogs(): void {
const runId = this.selectedRunId();
if (runId == null) return;
const run = this.runs().find((item) => item.id === runId);
const text = run?.logs ?? this.logs();
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = `${this.data.task.command ?? 'job'}-run-${runId}.log`;
anchor.click();
URL.revokeObjectURL(url);
}
protected close(): void {
this.dialogRef.close();
}
}
@@ -0,0 +1,262 @@
<section class="jobs-page">
<header class="page-header">
<div>
<h1>Jobs</h1>
<p>
Background-Jobs zur Aufbereitung und Indizierung der Daten manuell
ausführen oder per Cron-Zeitplan automatisieren.
</p>
</div>
<button
mat-flat-button
color="primary"
type="button"
class="new-job-button"
(click)="openCreateDialog()">
<mat-icon>add</mat-icon>
Neuer Job
</button>
</header>
<div class="health-cards">
<mat-card appearance="outlined" class="health-card">
<mat-card-content class="health-content">
<div class="health-info">
<span
class="state-dot"
[class.state-dot--ok]="dockerHealth()?.reachable"
[class.state-dot--error]="
dockerHealth() && !dockerHealth()?.reachable
">
</span>
<div class="health-text">
<strong>Docker-Daemon</strong>
<div class="health-detail">
{{
dockerHealth()?.reachable ? 'Erreichbar' : 'Nicht erreichbar'
}}
@if (dockerHealth()?.detail) {
<span> · {{ dockerHealth()?.detail }}</span>
}
</div>
</div>
</div>
<button
mat-icon-button
type="button"
aria-label="Docker-Status aktualisieren"
matTooltip="Docker-Status aktualisieren"
[disabled]="dockerHealthLoading()"
(click)="refreshDockerHealth()">
<mat-icon>refresh</mat-icon>
</button>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" class="health-card">
<mat-card-content class="health-content">
<div class="health-info">
<span
class="state-dot"
[class.state-dot--ok]="registryHealth()?.reachable"
[class.state-dot--error]="
registryHealth() && !registryHealth()?.reachable
">
</span>
<div class="health-text">
<div class="health-title">
<strong>Nexus-Registry</strong>
@if (registryHealth()?.host) {
<code class="health-host">{{ registryHealth()?.host }}</code>
}
</div>
<div class="health-detail">
@if (registryHealthLoading() && !registryHealth()) {
<span>Wird geprüft …</span>
} @else {
{{
registryHealth()?.reachable
? 'Erreichbar'
: 'Nicht erreichbar'
}}
@if (registryHealth()?.detail) {
<span> · {{ registryHealth()?.detail }}</span>
}
}
</div>
</div>
</div>
<button
mat-icon-button
type="button"
aria-label="Nexus-Status aktualisieren"
matTooltip="Nexus-Status aktualisieren"
[disabled]="registryHealthLoading()"
(click)="refreshRegistryHealth()">
<mat-icon>refresh</mat-icon>
</button>
</mat-card-content>
</mat-card>
</div>
<mat-card appearance="outlined">
<mat-card-content>
<app-data-table [columns]="taskColumns" [data]="tasks()" />
</mat-card-content>
</mat-card>
</section>
<ng-template #taskNameTmp let-row>
<div class="task-name-cell">
<button
type="button"
class="edit-name-action"
aria-label="Job bearbeiten"
matTooltip="Job bearbeiten"
matTooltipPosition="above"
[disabled]="row.status === 'running' || row.status === 'stopping'"
(click)="openEditDialog(row)">
<mat-icon>edit</mat-icon>
</button>
<div class="task-name-text">
<strong>{{ row.name }}</strong>
<span class="task-description">{{ row.description }}</span>
<code class="task-index">{{ row.target_index }}</code>
</div>
</div>
</ng-template>
<ng-template #taskScheduleTmp let-row>
<div class="task-schedule-cell">
@if (row.schedule) {
<span class="schedule-cron">{{ row.schedule }}</span>
} @else {
<span>Nur manuell</span>
}
@if (row.next_run_at) {
<span class="next-run">
Nächster Lauf: {{ formatUtcDateAsLocal(row.next_run_at) }}
</span>
}
@if (row.schedule) {
<span class="enabled-badge" [class.enabled-badge--on]="row.enabled">
{{ row.enabled ? 'Aktiv' : 'Inaktiv' }}
</span>
}
</div>
</ng-template>
<ng-template #taskStatusTmp let-row>
<span class="task-status" [ngClass]="statusMeta(row.status).cssClass">
@if (row.status === 'running' || row.status === 'stopping') {
<mat-progress-spinner
diameter="14"
mode="indeterminate"></mat-progress-spinner>
} @else {
<mat-icon>{{ statusMeta(row.status).icon }}</mat-icon>
}
{{ statusMeta(row.status).label }}
</span>
</ng-template>
<ng-template #taskLastRunTmp let-row>
@if (row.last_run) {
<div class="last-run-cell">
<span>{{ formatUtcDateAsLocal(row.last_run.started_at) }}</span>
@if (row.status === 'running' || row.status === 'stopping') {
@if (formatRunElapsed(row.last_run, nowMs()); as elapsed) {
<span class="last-run-message">läuft seit {{ elapsed }}</span>
}
} @else if (formatRunDuration(row.last_run); as duration) {
<span class="last-run-message">Dauer: {{ duration }}</span>
}
@if (row.last_run.exit_code != null) {
<span class="last-run-message"
>Exit-Code {{ row.last_run.exit_code }}</span
>
}
</div>
} @else {
<span class="last-run-empty">Noch nicht ausgeführt</span>
}
</ng-template>
<ng-template #taskActionsHeaderTmp>
<div class="actions-header">
<span>Aktionen</span>
<button
mat-icon-button
type="button"
aria-label="Jobs aktualisieren"
matTooltip="Jobs aktualisieren"
matTooltipPosition="above"
(click)="refreshTasks()">
<mat-icon>refresh</mat-icon>
</button>
</div>
</ng-template>
<ng-template #taskActionsTmp let-row>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Jetzt ausführen"
matTooltip="Jetzt ausführen"
matTooltipPosition="above"
[disabled]="row.status === 'running' || row.status === 'stopping'"
(click)="runNow(row)">
<mat-icon>play_arrow</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Stoppen"
matTooltip="Stoppen"
matTooltipPosition="above"
[disabled]="row.status !== 'running'"
(click)="stopNow(row)">
<mat-icon>stop</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Logs anzeigen"
matTooltip="Logs anzeigen"
matTooltipPosition="above"
[disabled]="!row.last_run"
(click)="openLogsDialog(row)">
<mat-icon>description</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Zeitplan bearbeiten"
matTooltip="Zeitplan bearbeiten"
matTooltipPosition="above"
(click)="openScheduleDialog(row)">
<mat-icon>edit_calendar</mat-icon>
</button>
<button
mat-icon-button
type="button"
class="delete-action"
aria-label="Job löschen"
matTooltip="Job löschen"
matTooltipPosition="above"
[disabled]="
row.status === 'running' ||
row.status === 'stopping' ||
deletingTaskIds().has(row.id)
"
(click)="confirmDeleteTask(row)">
@if (deletingTaskIds().has(row.id)) {
<mat-progress-spinner
diameter="18"
mode="indeterminate"></mat-progress-spinner>
} @else {
<mat-icon>delete</mat-icon>
}
</button>
</div>
</ng-template>
@@ -0,0 +1,316 @@
.jobs-page {
display: flex;
flex-direction: column;
gap: 20px;
padding: 24px;
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.new-job-button {
flex-shrink: 0;
white-space: nowrap;
}
h1,
p {
margin: 0;
}
.page-header h1 {
font-size: 26px;
font-weight: 700;
}
.page-header p {
color: #64748b;
margin-top: 6px;
}
mat-card,
mat-paginator {
background-color: var(--sg-background);
}
.health-cards {
display: flex;
gap: 12px;
}
.health-card {
flex: 1 1 0;
min-width: 0;
}
.health-content {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.health-info {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.health-text {
min-width: 0;
}
.state-dot {
width: 12px;
height: 12px;
border-radius: 50%;
background: #94a3b8;
flex-shrink: 0;
&--ok {
background: #16a34a;
}
&--error {
background: #dc2626;
}
}
.health-detail {
font-size: 12px;
color: #64748b;
}
.health-title {
display: flex;
align-items: baseline;
gap: 8px;
flex-wrap: wrap;
}
.health-host {
font-size: 11px;
color: #64748b;
word-break: break-all;
}
:host ::ng-deep .mat-mdc-row {
height: 96px;
}
:host ::ng-deep .mat-mdc-row .mat-mdc-cell {
padding-top: 12px;
padding-bottom: 12px;
vertical-align: middle;
}
:host ::ng-deep .mat-mdc-header-cell {
text-align: center;
}
:host ::ng-deep .mat-mdc-cell:not(:last-child),
:host ::ng-deep .mat-mdc-header-cell:not(:last-child) {
border-right: 1px solid var(--sg-border);
}
:host ::ng-deep .mat-mdc-cell.mat-column-lastRun {
text-align: center;
}
:host ::ng-deep .mat-mdc-cell.mat-column-schedule {
text-align: center;
}
.task-name-cell {
display: flex;
flex-direction: row;
align-items: center;
gap: 6px;
min-width: 220px;
}
.task-name-text {
display: flex;
flex-direction: column;
gap: 2px;
}
.edit-name-action {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: none;
background: none;
cursor: pointer;
color: #64748b;
opacity: 0;
transition: opacity 0.15s ease;
.mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
line-height: 18px;
}
}
.task-name-cell:hover .edit-name-action,
.edit-name-action:focus-visible {
opacity: 1;
}
.edit-name-action[disabled] {
cursor: not-allowed;
color: #cbd5e1;
}
.task-description {
font-size: 12px;
color: #64748b;
}
.task-index {
width: fit-content;
font-size: 11px;
color: #475569;
background: #f1f5f9;
border-radius: 4px;
padding: 1px 6px;
}
.task-schedule-cell {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 4px;
}
.schedule-cron {
white-space: nowrap;
font-family:
ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, monospace;
font-size: 13px;
color: #334155;
}
.next-run {
font-size: 12px;
color: #64748b;
}
.enabled-badge {
width: fit-content;
font-size: 11px;
font-weight: 700;
padding: 1px 8px;
border-radius: 999px;
background: #e2e8f0;
color: #64748b;
&--on {
background: #dcfce7;
color: #166534;
}
}
.task-status {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
font-weight: 600;
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
&--success {
color: #166534;
}
&--failed {
color: #991b1b;
}
&--running {
color: #92400e;
}
&--stopped {
color: #64748b;
}
&--idle {
color: #64748b;
}
}
.last-run-cell {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
font-size: 13px;
white-space: nowrap;
}
.last-run-message {
font-size: 12px;
color: #64748b;
}
.last-run-empty {
font-size: 13px;
color: #64748b;
}
.row-actions {
display: flex;
gap: 4px;
}
.delete-action:not(:disabled) {
color: #b91c1c;
}
.actions-header {
display: grid;
grid-template-columns: 40px 1fr 40px;
align-items: center;
width: 100%;
span {
grid-column: 2;
}
button {
grid-column: 3;
}
}
@media (max-width: 640px) {
.jobs-page {
padding: 16px;
}
.page-header {
align-items: flex-start;
flex-direction: column;
}
.health-cards {
flex-direction: column;
}
}
@@ -0,0 +1,561 @@
import { CommonModule } from '@angular/common';
import {
Component,
DestroyRef,
OnInit,
TemplateRef,
inject,
input,
signal,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
EMPTY,
Subject,
Subscription,
catchError,
merge,
switchMap,
timer,
} from 'rxjs';
import {
BackgroundJobsService,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
} from '../../api';
import {
DataTableComponent,
GenericColumn,
} from '../../shared/ui/data-table/data-table.component';
import {
formatRunDuration,
formatRunElapsed,
formatScheduleCron,
formatUtcDateAsLocal,
statusMeta,
toUtcMs,
} from './jobs.utils';
import {
TaskScheduleDialogComponent,
TaskScheduleDialogData,
TaskScheduleDialogResult,
} from './task-schedule-dialog/task-schedule-dialog.component';
import {
JobLogsDialogComponent,
JobLogsDialogData,
} from './job-logs-dialog/job-logs-dialog.component';
import { TaskCreateDialogComponent } from './task-create-dialog/task-create-dialog.component';
import {
TaskEditDialogComponent,
TaskEditDialogData,
} from './task-edit-dialog/task-edit-dialog.component';
const MAX_IDLE_POLL_WAIT_MS = 60000;
@Component({
selector: 'app-jobs',
imports: [
CommonModule,
MatButtonModule,
MatCardModule,
MatDialogModule,
MatIconModule,
MatProgressSpinnerModule,
MatSnackBarModule,
MatTooltipModule,
DataTableComponent,
],
templateUrl: './jobs.component.html',
styleUrl: './jobs.component.scss',
standalone: true,
})
export class JobsComponent implements OnInit {
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly backgroundJobsService = inject(BackgroundJobsService);
private readonly destroyRef = inject(DestroyRef);
tasksInput = input.required<BackgroundJobTask[]>({ alias: 'tasks' });
dockerHealthInput = input.required<DockerHealth>({ alias: 'dockerHealth' });
protected readonly tasks = signal<BackgroundJobTask[]>([]);
protected readonly dockerHealth = signal<DockerHealth | null>(null);
protected readonly dockerHealthLoading = signal(false);
protected readonly registryHealth = signal<RegistryHealth | null>(null);
protected readonly registryHealthLoading = signal(false);
protected readonly deletingTaskIds = signal<ReadonlySet<number>>(new Set());
protected readonly nowMs = signal(Date.now());
protected readonly statusMeta = statusMeta;
protected readonly formatScheduleCron = formatScheduleCron;
protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal;
protected readonly formatRunDuration = formatRunDuration;
protected readonly formatRunElapsed = formatRunElapsed;
protected taskColumns: GenericColumn<BackgroundJobTask>[] = [];
private readonly taskNameTmp =
viewChild.required<TemplateRef<any>>('taskNameTmp');
private readonly taskScheduleTmp =
viewChild.required<TemplateRef<any>>('taskScheduleTmp');
private readonly taskStatusTmp =
viewChild.required<TemplateRef<any>>('taskStatusTmp');
private readonly taskLastRunTmp =
viewChild.required<TemplateRef<any>>('taskLastRunTmp');
private readonly taskActionsTmp =
viewChild.required<TemplateRef<any>>('taskActionsTmp');
private readonly taskActionsHeaderTmp = viewChild.required<TemplateRef<any>>(
'taskActionsHeaderTmp',
);
private readonly taskRefreshTrigger = new Subject<void>();
private readonly pollNow = new Subject<void>();
private readonly pendingStopTaskIds = new Set<number>();
private pollDelaySub?: Subscription;
private tickSub?: Subscription;
ngOnInit(): void {
this.tasks.set(this.tasksInput());
this.dockerHealth.set(this.dockerHealthInput());
this.refreshRegistryHealth();
merge(this.pollNow, this.taskRefreshTrigger)
.pipe(
switchMap(() =>
this.backgroundJobsService
.getBackgroundJobTasks(undefined, 'body', false, {
transferCache: false,
})
.pipe(
catchError(() => {
this.showError('Jobs konnten nicht aktualisiert werden.');
return EMPTY;
}),
),
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((tasks) => {
this.setTasksPreservingPendingStops(tasks);
this.syncBackgroundWork();
});
this.syncBackgroundWork();
this.taskColumns = [
{
id: 'name',
header: 'Job',
type: 'display',
cellTemplate: this.taskNameTmp(),
},
{
id: 'schedule',
header: 'Zeitplan',
type: 'display',
cellTemplate: this.taskScheduleTmp(),
},
{
id: 'status',
header: 'Status',
type: 'display',
cellTemplate: this.taskStatusTmp(),
},
{
id: 'lastRun',
header: 'Letzter Lauf',
type: 'display',
cellTemplate: this.taskLastRunTmp(),
},
{
id: 'actions',
header: 'Aktionen',
type: 'display',
headerTemplate: this.taskActionsHeaderTmp(),
cellTemplate: this.taskActionsTmp(),
},
];
}
protected refreshTasks(): void {
this.taskRefreshTrigger.next();
}
private hasActiveTask(): boolean {
return this.tasks().some(
(task) => task.status === 'running' || task.status === 'stopping',
);
}
private syncBackgroundWork(): void {
const active = this.hasActiveTask();
if (active && !this.tickSub) {
this.tickSub = timer(1000, 1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.nowMs.set(Date.now()));
} else if (!active && this.tickSub) {
this.tickSub.unsubscribe();
this.tickSub = undefined;
}
this.pollDelaySub?.unsubscribe();
this.pollDelaySub = undefined;
const delayMs = this.nextPollDelayMs(active);
if (delayMs != null) {
this.pollDelaySub = timer(delayMs)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.pollNow.next());
}
}
private nextPollDelayMs(active: boolean): number | null {
if (active) return 5000;
const nextRun = this.earliestUpcomingRun();
if (nextRun == null) return null;
const untilRun = nextRun - Date.now();
if (untilRun <= 0) return 3000;
return Math.min(untilRun + 3000, MAX_IDLE_POLL_WAIT_MS);
}
private earliestUpcomingRun(): number | null {
let earliest: number | null = null;
for (const task of this.tasks()) {
if (!task.enabled || !task.schedule || !task.next_run_at) continue;
const ts = toUtcMs(task.next_run_at);
if (earliest == null || ts < earliest) earliest = ts;
}
return earliest;
}
protected refreshDockerHealth(): void {
this.dockerHealthLoading.set(true);
this.backgroundJobsService.getBackgroundJobsDockerHealth().subscribe({
next: (health) => {
this.dockerHealth.set(health);
this.dockerHealthLoading.set(false);
},
error: () => {
this.dockerHealthLoading.set(false);
this.showError('Docker-Status konnte nicht abgerufen werden.');
},
});
}
protected refreshRegistryHealth(): void {
this.registryHealthLoading.set(true);
this.backgroundJobsService
.getBackgroundJobsRegistryHealth()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (health) => {
this.registryHealth.set(health);
this.registryHealthLoading.set(false);
},
error: () => {
this.registryHealthLoading.set(false);
this.showError('Nexus-Status konnte nicht abgerufen werden.');
},
});
}
private notifyIfRegistryDown(): void {
this.backgroundJobsService
.getBackgroundJobsRegistryHealth()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (health) => {
this.registryHealth.set(health);
if (!health.reachable) {
this.showError(
`Nexus-Registry nicht erreichbar: ${health.detail}. Die Image-Auswahl bleibt leer.`,
);
}
},
});
}
protected runNow(task: BackgroundJobTask): void {
if (['running', 'stopping'].includes(task.status)) return;
this.backgroundJobsService.runBackgroundJobTask(task.id).subscribe({
next: (run) => {
const status = run.status ?? 'running';
this.updateTask(task.id, (current) => ({
...current,
status,
last_run: run,
}));
if (status === 'failed') {
this.showError(
`„${task.name}“ ist fehlgeschlagen — Details in den Logs.`,
);
this.refreshRegistryHealth();
} else {
this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
}
this.refreshTasks();
},
error: (error) =>
this.showError(
error.status === 409
? `„${task.name}“ läuft bereits.`
: `„${task.name}“ konnte nicht gestartet werden.`,
),
});
}
protected stopNow(task: BackgroundJobTask): void {
const runId = task.last_run?.id;
if (task.status !== 'running' || runId == null) return;
this.pendingStopTaskIds.add(task.id);
this.updateTask(task.id, (current) => ({
...current,
status: 'stopping',
}));
this.backgroundJobsService.stopBackgroundJobRun(runId).subscribe({
next: (run) => {
this.pendingStopTaskIds.delete(task.id);
this.updateTask(task.id, (current) => ({
...current,
status: run.status ?? 'running',
last_run: run,
}));
const message =
run.status === 'stopped'
? `„${task.name}“ wurde gestoppt.`
: `„${task.name}“ war bereits beendet.`;
this.snackBar.open(message, 'OK', {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
this.refreshTasks();
},
error: (error) => {
this.pendingStopTaskIds.delete(task.id);
this.updateTask(task.id, (current) => ({
...current,
status: 'running',
}));
this.showError(
error.status === 409
? `„${task.name}“ läuft nicht.`
: `„${task.name}“ konnte nicht gestoppt werden.`,
);
this.refreshTasks();
},
});
}
protected openLogsDialog(task: BackgroundJobTask): void {
if (task.last_run?.id == null) return;
this.dialog.open<JobLogsDialogComponent, JobLogsDialogData>(
JobLogsDialogComponent,
{
width: '640px',
maxWidth: 'calc(100vw - 32px)',
data: { task },
},
);
}
protected openCreateDialog(): void {
this.notifyIfRegistryDown();
const dialogRef = this.dialog.open<
TaskCreateDialogComponent,
void,
BackgroundJobTask | undefined
>(TaskCreateDialogComponent, {
width: '560px',
maxWidth: 'calc(100vw - 32px)',
});
dialogRef.afterClosed().subscribe((task) => {
if (!task) return;
this.tasks.update((tasks) => [...tasks, task]);
this.snackBar.open(`„${task.name}“ wurde angelegt.`, 'OK', {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
this.refreshTasks();
});
}
protected openEditDialog(task: BackgroundJobTask): void {
if (['running', 'stopping'].includes(task.status)) return;
this.notifyIfRegistryDown();
const dialogRef = this.dialog.open<
TaskEditDialogComponent,
TaskEditDialogData,
BackgroundJobTask | undefined
>(TaskEditDialogComponent, {
width: '560px',
maxWidth: 'calc(100vw - 32px)',
data: { task },
});
dialogRef.afterClosed().subscribe((updatedTask) => {
if (!updatedTask) return;
this.updateTask(updatedTask.id, () => updatedTask);
this.snackBar.open(`„${updatedTask.name}“ wurde gespeichert.`, 'OK', {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
});
}
protected openScheduleDialog(task: BackgroundJobTask): void {
const dialogRef = this.dialog.open<
TaskScheduleDialogComponent,
TaskScheduleDialogData,
TaskScheduleDialogResult | undefined
>(TaskScheduleDialogComponent, {
width: '520px',
maxWidth: 'calc(100vw - 32px)',
data: { task },
});
dialogRef.afterClosed().subscribe((result) => {
if (!result) return;
this.backgroundJobsService
.updateBackgroundJobTask(result.taskId, {
enabled: result.enabled,
schedule: result.schedule,
})
.subscribe({
next: (updatedTask) => {
this.updateTask(result.taskId, () => updatedTask);
this.snackBar.open('Zeitplan wurde gespeichert.', 'OK', {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
},
error: (error) =>
this.showError(
error?.error?.detail ??
'Zeitplan konnte nicht gespeichert werden.',
),
});
});
}
protected confirmDeleteTask(task: BackgroundJobTask): void {
if (
['running', 'stopping'].includes(task.status) ||
this.deletingTaskIds().has(task.id)
) {
return;
}
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
({ ConfirmationDialogComponent }) => {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
width: '520px',
maxWidth: 'calc(100vw - 32px)',
data: {
title: 'Job löschen',
message: `Möchtest Du „${task.name}“ wirklich löschen? Alle Laufdaten und gespeicherten Logs werden dauerhaft gelöscht.`,
confirmText: 'Löschen',
cancelText: 'Abbrechen',
},
});
dialogRef.afterClosed().subscribe((confirmed) => {
if (confirmed) this.deleteTask(task);
});
},
);
}
private updateTask(
id: number,
updater: (task: BackgroundJobTask) => BackgroundJobTask,
): void {
this.tasks.update((current) =>
current.map((task) => (task.id === id ? updater(task) : task)),
);
this.syncBackgroundWork();
}
private deleteTask(task: BackgroundJobTask): void {
this.deletingTaskIds.update((ids) => new Set(ids).add(task.id));
this.backgroundJobsService.deleteBackgroundJobTask(task.id).subscribe({
next: () => {
this.finishDeletingTask(task.id);
this.tasks.update((tasks) =>
tasks.filter((current) => current.id !== task.id),
);
this.snackBar.open(`„${task.name}“ wurde gelöscht.`, 'OK', {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
this.refreshTasks();
},
error: (error) => {
this.finishDeletingTask(task.id);
this.showError(
error.status === 409
? `„${task.name}“ läuft noch und kann nicht gelöscht werden.`
: `„${task.name}“ konnte nicht gelöscht werden.`,
);
this.refreshTasks();
},
});
}
private finishDeletingTask(taskId: number): void {
this.deletingTaskIds.update((ids) => {
const updated = new Set(ids);
updated.delete(taskId);
return updated;
});
}
private setTasksPreservingPendingStops(tasks: BackgroundJobTask[]): void {
this.tasks.set(
tasks.map((task) =>
this.pendingStopTaskIds.has(task.id)
? { ...task, status: 'stopping' }
: task,
),
);
}
private showError(message: string): void {
this.snackBar.open(message, 'OK', {
duration: 5000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
}
}
+84
View File
@@ -0,0 +1,84 @@
import { JobRun } from '../../api';
export interface StatusMeta {
label: string;
icon: string;
cssClass: string;
}
const STATUS_META: Record<string, StatusMeta> = {
running: { label: 'Läuft', icon: 'sync', cssClass: 'task-status--running' },
stopping: {
label: 'Wird gestoppt',
icon: 'stop_circle',
cssClass: 'task-status--running',
},
succeeded: {
label: 'Erfolgreich',
icon: 'check_circle',
cssClass: 'task-status--success',
},
failed: {
label: 'Fehlgeschlagen',
icon: 'error',
cssClass: 'task-status--failed',
},
stopped: {
label: 'Gestoppt',
icon: 'stop_circle',
cssClass: 'task-status--stopped',
},
idle: { label: 'Bereit', icon: 'schedule', cssClass: 'task-status--idle' },
};
export function statusMeta(status: string): StatusMeta {
return STATUS_META[status] ?? STATUS_META['idle'];
}
export function formatScheduleCron(schedule: string | null): string {
return schedule ? `Cron: ${schedule}` : 'Nur manuell';
}
function appendUtcZ(value: string): string {
return /(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? value : `${value}Z`;
}
export function toUtcMs(value: string): number {
return new Date(appendUtcZ(value)).getTime();
}
export function formatUtcDateAsLocal(value: string | null | undefined): string {
if (!value) return '';
return new Intl.DateTimeFormat('de-DE', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(new Date(appendUtcZ(value)));
}
export function formatDurationSeconds(totalSeconds: number): string {
const s = Math.max(0, Math.round(totalSeconds));
const pad = (n: number) => n.toString().padStart(2, '0');
const hours = Math.floor(s / 3600);
const minutes = Math.floor((s % 3600) / 60);
const seconds = s % 60;
if (hours > 0) {
return `${hours}:${pad(minutes)}:${pad(seconds)} h`;
}
return `${pad(minutes)}:${pad(seconds)} min`;
}
export function formatRunDuration(run: JobRun): string | null {
if (!run.started_at || !run.finished_at) return null;
return formatDurationSeconds(
(toUtcMs(run.finished_at) - toUtcMs(run.started_at)) / 1000,
);
}
export function formatRunElapsed(run: JobRun, nowMs: number): string | null {
if (!run.started_at) return null;
return formatDurationSeconds((nowMs - toUtcMs(run.started_at)) / 1000);
}
@@ -0,0 +1,117 @@
<h2 mat-dialog-title>Neuer Job</h2>
<mat-dialog-content>
<form class="create-form" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Name</mat-label>
<input matInput formControlName="name" />
<mat-icon
matSuffix
class="field-info"
matTooltip="Eindeutiger Anzeigename des Jobs, z.B. „News-Themen-Mapping (Testlauf)“."
>info_outline</mat-icon
>
@if (form.controls.name.invalid) {
<mat-error>Bitte einen Namen eingeben.</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Befehl</mat-label>
<textarea
matInput
class="command-input"
rows="2"
formControlName="command"
placeholder="python sync.py --stats"></textarea>
<mat-icon
matSuffix
class="field-info"
matTooltip="Wird beim Start direkt im Container ausgeführt — wie in einem Terminal, z.B. „python sync.py --update-keywords --target-index docker-job_test“. Leer = Standard-Befehl des Images."
>info_outline</mat-icon
>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Image</mat-label>
<input
matInput
class="image-input"
formControlName="image"
[matAutocomplete]="imageAuto" />
<mat-autocomplete #imageAuto="matAutocomplete">
@for (image of filteredImages(); track image) {
<mat-option [value]="image">{{ image }}</mat-option>
}
</mat-autocomplete>
<mat-icon
matSuffix
class="field-info"
matTooltip="Docker-Image für den Job. Tippen filtert die aus Nexus verfügbaren Images; du kannst auch einen eigenen Wert eingeben. Images aus unserer Registry (docker.nes.uni-due.de) erhalten die INSE-Zugangsdaten (Elasticsearch/LLM) automatisch, fremde Images nicht."
>info_outline</mat-icon
>
@if (form.controls.image.invalid && form.controls.image.touched) {
<mat-error>Bitte ein Image auswählen oder eingeben.</mat-error>
}
<mat-hint>Aus Nexus wählen oder eigenes Image eingeben.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Beschreibung (optional)</mat-label>
<textarea matInput rows="2" formControlName="description"></textarea>
<mat-icon
matSuffix
class="field-info"
matTooltip="Freitext für die Job-Tabelle: Was macht der Job, was sollte man vor dem Start wissen?"
>info_outline</mat-icon
>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Ziel-Index (optional)</mat-label>
<input matInput formControlName="targetIndex" />
<mat-icon
matSuffix
class="field-info"
matTooltip="Reine Anzeige-Info in der Tabelle. In welchen Index der Job wirklich schreibt, bestimmt allein der Befehl (z.B. --target-index / --output-index)."
>info_outline</mat-icon
>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Umgebungsvariablen (optional)</mat-label>
<textarea
matInput
rows="3"
formControlName="env"
placeholder="KEY=value"></textarea>
<mat-icon
matSuffix
class="field-info"
matTooltip="Zusätzliche Umgebungsvariablen für den Container, eine pro Zeile im Format KEY=value. Das Standard-Image bekommt die INSE-Zugangsdaten (Elasticsearch/LLM) automatisch — hier ist nur Spezielles nötig."
>info_outline</mat-icon
>
<mat-hint>Eine Variable pro Zeile im Format KEY=value.</mat-hint>
@if (form.controls.env.hasError('invalidEnv')) {
<mat-error>Ungültige Zeile — Format: KEY=value.</mat-error>
}
</mat-form-field>
</form>
@if (serverError()) {
<p class="server-error">{{ serverError() }}</p>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button
mat-flat-button
color="primary"
type="button"
[disabled]="creating()"
(click)="submit()">
<mat-icon>add</mat-icon>
Anlegen
</button>
</mat-dialog-actions>
@@ -0,0 +1,50 @@
.create-form {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 400px;
padding-top: 6px;
}
.command-input,
.image-input {
resize: vertical;
font-family:
ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, monospace;
font-size: 13px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-all;
}
.commands-loading {
display: flex;
align-items: center;
gap: 8px;
color: #64748b;
font-size: 14px;
}
.field-hint {
margin: -6px 0 0;
color: #64748b;
font-size: 12px;
}
.field-info {
color: #94a3b8;
cursor: help;
}
.server-error {
margin: 8px 0 0;
color: #b3261e;
font-size: 14px;
}
@media (max-width: 640px) {
.create-form {
min-width: 0;
}
}
@@ -0,0 +1,147 @@
import { CommonModule } from '@angular/common';
import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatTooltipModule } from '@angular/material/tooltip';
import { BackgroundJobTask, BackgroundJobsService } from '../../../api';
const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/;
@Component({
selector: 'app-task-create-dialog',
imports: [
CommonModule,
ReactiveFormsModule,
MatAutocompleteModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatTooltipModule,
],
templateUrl: './task-create-dialog.component.html',
styleUrl: './task-create-dialog.component.scss',
standalone: true,
})
export class TaskCreateDialogComponent implements OnInit {
private readonly dialogRef =
inject<
MatDialogRef<TaskCreateDialogComponent, BackgroundJobTask | undefined>
>(MatDialogRef);
private readonly backgroundJobsService = inject(BackgroundJobsService);
protected readonly creating = signal(false);
protected readonly serverError = signal('');
protected readonly images = signal<string[]>([]);
protected readonly form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
}),
description: new FormControl('', { nonNullable: true }),
targetIndex: new FormControl('', { nonNullable: true }),
command: new FormControl('', { nonNullable: true }),
image: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
}),
env: new FormControl('', { nonNullable: true }),
});
private readonly imageQuery = toSignal(
this.form.controls.image.valueChanges,
{
initialValue: this.form.controls.image.value,
},
);
protected readonly filteredImages = computed(() => {
const query = (this.imageQuery() ?? '').toLowerCase().trim();
const all = this.images();
if (!query) return all;
return all.filter((image) => image.toLowerCase().includes(query));
});
ngOnInit(): void {
this.backgroundJobsService
.getBackgroundJobAvailableImages()
.subscribe({ next: (result) => this.images.set(result.images ?? []) });
}
protected submit(): void {
this.serverError.set('');
const value = this.form.getRawValue();
const name = value.name.trim();
if (!name) {
this.form.controls.name.markAsTouched();
return;
}
const image = value.image.trim();
if (!image) {
this.form.controls.image.markAsTouched();
return;
}
const command = value.command.trim() || null;
const env = this.parseEnv(value.env);
if (env === undefined) return;
this.creating.set(true);
this.backgroundJobsService
.createBackgroundJobTask({
name,
description: value.description.trim(),
target_index: value.targetIndex.trim(),
image,
command,
env,
})
.subscribe({
next: (task) => this.dialogRef.close(task),
error: (error) => {
this.creating.set(false);
const detail = error?.error?.detail;
this.serverError.set(
typeof detail === 'string'
? detail
: 'Der Job konnte nicht angelegt werden.',
);
},
});
}
protected close(): void {
this.dialogRef.close();
}
private parseEnv(text: string): { [key: string]: string } | undefined {
const env: { [key: string]: string } = {};
for (const line of text.split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
if (!ENV_LINE_PATTERN.test(trimmed)) {
this.form.controls.env.setErrors({ invalidEnv: true });
this.form.controls.env.markAsTouched();
return undefined;
}
const separatorIndex = trimmed.indexOf('=');
env[trimmed.slice(0, separatorIndex)] = trimmed.slice(separatorIndex + 1);
}
return env;
}
}
@@ -0,0 +1,117 @@
<h2 mat-dialog-title>Job bearbeiten</h2>
<mat-dialog-content>
<form class="edit-form" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Name</mat-label>
<input matInput formControlName="name" />
<mat-icon
matSuffix
class="field-info"
matTooltip="Eindeutiger Anzeigename des Jobs, z.B. „News-Themen-Mapping (Testlauf)“."
>info_outline</mat-icon
>
@if (form.controls.name.invalid) {
<mat-error>Bitte einen Namen eingeben.</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Befehl</mat-label>
<textarea
matInput
class="command-input"
rows="2"
formControlName="command"
placeholder="python sync.py --stats"></textarea>
<mat-icon
matSuffix
class="field-info"
matTooltip="Wird beim Start direkt im Container ausgeführt — wie in einem Terminal, z.B. „python sync.py --update-keywords --target-index docker-job_test“. Leer = Standard-Befehl des Images."
>info_outline</mat-icon
>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Image</mat-label>
<input
matInput
class="image-input"
formControlName="image"
[matAutocomplete]="imageAuto" />
<mat-autocomplete #imageAuto="matAutocomplete">
@for (image of filteredImages(); track image) {
<mat-option [value]="image">{{ image }}</mat-option>
}
</mat-autocomplete>
<mat-icon
matSuffix
class="field-info"
matTooltip="Docker-Image für den Job. Tippen filtert die aus Nexus verfügbaren Images; du kannst auch einen eigenen Wert eingeben. Images aus unserer Registry (docker.nes.uni-due.de) erhalten die INSE-Zugangsdaten (Elasticsearch/LLM) automatisch, fremde Images nicht."
>info_outline</mat-icon
>
@if (form.controls.image.invalid && form.controls.image.touched) {
<mat-error>Bitte ein Image auswählen oder eingeben.</mat-error>
}
<mat-hint>Aus Nexus wählen oder eigenes Image eingeben.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Beschreibung (optional)</mat-label>
<textarea matInput rows="2" formControlName="description"></textarea>
<mat-icon
matSuffix
class="field-info"
matTooltip="Freitext für die Job-Tabelle: Was macht der Job, was sollte man vor dem Start wissen?"
>info_outline</mat-icon
>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Ziel-Index (optional)</mat-label>
<input matInput formControlName="targetIndex" />
<mat-icon
matSuffix
class="field-info"
matTooltip="Reine Anzeige-Info in der Tabelle. In welchen Index der Job wirklich schreibt, bestimmt allein der Befehl (z.B. --target-index / --output-index)."
>info_outline</mat-icon
>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Umgebungsvariablen (optional)</mat-label>
<textarea
matInput
rows="3"
formControlName="env"
placeholder="KEY=value"></textarea>
<mat-icon
matSuffix
class="field-info"
matTooltip="Zusätzliche Umgebungsvariablen für den Container, eine pro Zeile im Format KEY=value. Das Standard-Image bekommt die INSE-Zugangsdaten (Elasticsearch/LLM) automatisch — hier ist nur Spezielles nötig."
>info_outline</mat-icon
>
<mat-hint>Eine Variable pro Zeile im Format KEY=value.</mat-hint>
@if (form.controls.env.hasError('invalidEnv')) {
<mat-error>Ungültige Zeile — Format: KEY=value.</mat-error>
}
</mat-form-field>
</form>
@if (serverError()) {
<p class="server-error">{{ serverError() }}</p>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button
mat-flat-button
color="primary"
type="button"
[disabled]="saving()"
(click)="submit()">
<mat-icon>save</mat-icon>
Speichern
</button>
</mat-dialog-actions>
@@ -0,0 +1,36 @@
.edit-form {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 400px;
padding-top: 6px;
}
.command-input,
.image-input {
resize: vertical;
font-family:
ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, monospace;
font-size: 13px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-all;
}
.field-info {
color: #94a3b8;
cursor: help;
}
.server-error {
margin: 8px 0 0;
color: #b3261e;
font-size: 14px;
}
@media (max-width: 640px) {
.edit-form {
min-width: 0;
}
}
@@ -0,0 +1,169 @@
import { CommonModule } from '@angular/common';
import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatTooltipModule } from '@angular/material/tooltip';
import { BackgroundJobTask, BackgroundJobsService } from '../../../api';
const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/;
export interface TaskEditDialogData {
task: BackgroundJobTask;
}
@Component({
selector: 'app-task-edit-dialog',
imports: [
CommonModule,
ReactiveFormsModule,
MatAutocompleteModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatTooltipModule,
],
templateUrl: './task-edit-dialog.component.html',
styleUrl: './task-edit-dialog.component.scss',
standalone: true,
})
export class TaskEditDialogComponent implements OnInit {
private readonly dialogRef =
inject<
MatDialogRef<TaskEditDialogComponent, BackgroundJobTask | undefined>
>(MatDialogRef);
private readonly backgroundJobsService = inject(BackgroundJobsService);
protected readonly data = inject<TaskEditDialogData>(MAT_DIALOG_DATA);
protected readonly saving = signal(false);
protected readonly serverError = signal('');
protected readonly images = signal<string[]>([]);
protected readonly form = new FormGroup({
name: new FormControl(this.data.task.name, {
nonNullable: true,
validators: [Validators.required],
}),
description: new FormControl(this.data.task.description, {
nonNullable: true,
}),
targetIndex: new FormControl(this.data.task.target_index, {
nonNullable: true,
}),
command: new FormControl(this.data.task.command ?? '', {
nonNullable: true,
}),
image: new FormControl(this.data.task.image ?? '', {
nonNullable: true,
validators: [Validators.required],
}),
env: new FormControl(this.envToText(this.data.task.env), {
nonNullable: true,
}),
});
private readonly imageQuery = toSignal(
this.form.controls.image.valueChanges,
{
initialValue: this.form.controls.image.value,
},
);
protected readonly filteredImages = computed(() => {
const query = (this.imageQuery() ?? '').toLowerCase().trim();
const all = this.images();
if (!query) return all;
return all.filter((image) => image.toLowerCase().includes(query));
});
ngOnInit(): void {
this.backgroundJobsService
.getBackgroundJobAvailableImages()
.subscribe({ next: (result) => this.images.set(result.images ?? []) });
}
protected submit(): void {
this.serverError.set('');
const value = this.form.getRawValue();
const name = value.name.trim();
if (!name) {
this.form.controls.name.markAsTouched();
return;
}
const image = value.image.trim();
if (!image) {
this.form.controls.image.markAsTouched();
return;
}
const env = this.parseEnv(value.env);
if (env === undefined) return;
this.saving.set(true);
this.backgroundJobsService
.updateBackgroundJobTask(this.data.task.id, {
name,
description: value.description.trim(),
target_index: value.targetIndex.trim(),
image,
command: value.command.trim() || null,
env,
})
.subscribe({
next: (task) => this.dialogRef.close(task),
error: (error) => {
this.saving.set(false);
const detail = error?.error?.detail;
this.serverError.set(
typeof detail === 'string'
? detail
: 'Der Job konnte nicht gespeichert werden.',
);
},
});
}
protected close(): void {
this.dialogRef.close();
}
private envToText(env: { [key: string]: string }): string {
return Object.entries(env)
.map(([key, value]) => `${key}=${value}`)
.join('\n');
}
private parseEnv(text: string): { [key: string]: string } | undefined {
const env: { [key: string]: string } = {};
for (const line of text.split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
if (!ENV_LINE_PATTERN.test(trimmed)) {
this.form.controls.env.setErrors({ invalidEnv: true });
this.form.controls.env.markAsTouched();
return undefined;
}
const separatorIndex = trimmed.indexOf('=');
env[trimmed.slice(0, separatorIndex)] = trimmed.slice(separatorIndex + 1);
}
return env;
}
}
@@ -0,0 +1,129 @@
<h2 mat-dialog-title>{{ data.task.name }}</h2>
<mat-dialog-content>
<p class="task-description">{{ data.task.description }}</p>
<form class="schedule-form" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Ausführung</mat-label>
<mat-select formControlName="mode" panelClass="schedule-mode-panel">
<mat-option value="manual">Nur manuell</mat-option>
<mat-option value="hourly">Stündlich</mat-option>
<mat-option value="daily">Täglich</mat-option>
<mat-option value="weekly">Wöchentlich</mat-option>
<mat-option value="monthly">Monatlich</mat-option>
<mat-option value="advanced">Erweiterter Cron-Ausdruck</mat-option>
</mat-select>
</mat-form-field>
@switch (form.controls.mode.value) {
@case ('hourly') {
<mat-form-field appearance="outline">
<mat-label>Minute der Stunde</mat-label>
<input
matInput
type="number"
min="0"
max="59"
formControlName="minute" />
<mat-hint>Angabe in UTC, zwischen 0 und 59.</mat-hint>
@if (form.controls.minute.invalid) {
<mat-error>Bitte eine Minute zwischen 0 und 59 eingeben.</mat-error>
}
</mat-form-field>
}
@case ('daily') {
<ng-container *ngTemplateOutlet="timeField"></ng-container>
}
@case ('weekly') {
<div class="schedule-fields">
<mat-form-field appearance="outline">
<mat-label>Wochentag</mat-label>
<mat-select formControlName="weekday">
@for (weekday of weekdays; track weekday.value) {
<mat-option [value]="weekday.value">
{{ weekday.label }}
</mat-option>
}
</mat-select>
</mat-form-field>
<ng-container *ngTemplateOutlet="timeField"></ng-container>
</div>
}
@case ('monthly') {
<div class="schedule-fields">
<mat-form-field appearance="outline">
<mat-label>Tag des Monats</mat-label>
<input
matInput
type="number"
min="1"
max="31"
formControlName="monthDay" />
@if (form.controls.monthDay.invalid) {
<mat-error>Bitte einen Tag zwischen 1 und 31 eingeben.</mat-error>
}
</mat-form-field>
<ng-container *ngTemplateOutlet="timeField"></ng-container>
</div>
<p class="field-hint">
In kürzeren Monaten wird ein nicht vorhandener Tag übersprungen.
</p>
}
@case ('advanced') {
<mat-form-field appearance="outline">
<mat-label>Cron-Ausdruck (UTC)</mat-label>
<input
matInput
formControlName="cronExpression"
placeholder="0 3 * * *" />
<mat-hint>Minute · Stunde · Tag · Monat · Wochentag</mat-hint>
@if (form.controls.cronExpression.hasError('invalidCron')) {
<mat-error>Ungültiger Cron-Ausdruck, z. B. „0 3 * * *“.</mat-error>
}
</mat-form-field>
}
}
@if (form.controls.mode.value !== 'manual') {
<button
type="button"
role="switch"
class="enabled-toggle"
[class.enabled-toggle--on]="form.controls.enabled.value"
[attr.aria-checked]="form.controls.enabled.value"
aria-label="Automatische Ausführung"
(click)="form.controls.enabled.setValue(!form.controls.enabled.value)">
<span class="enabled-toggle__track">
<span class="enabled-toggle__thumb"></span>
</span>
<span class="enabled-toggle__label">Automatische Ausführung aktiv</span>
</button>
}
@if (data.task.next_run_at && form.controls.mode.value !== 'manual') {
<p class="next-run-hint">
Nächster geplanter Lauf:
{{ formatUtcDateAsLocal(data.task.next_run_at) }} Uhr
</p>
}
<ng-template #timeField>
<mat-form-field appearance="outline">
<mat-label>Uhrzeit (UTC)</mat-label>
<input matInput type="time" formControlName="time" />
@if (form.controls.time.invalid) {
<mat-error>Bitte eine gültige Uhrzeit eingeben.</mat-error>
}
</mat-form-field>
</ng-template>
</form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button mat-flat-button color="primary" type="button" (click)="submit()">
<mat-icon>save</mat-icon>
Speichern
</button>
</mat-dialog-actions>
@@ -0,0 +1,97 @@
.task-description {
margin: 0 0 16px;
color: #64748b;
}
.schedule-form {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 360px;
}
.schedule-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.field-hint {
margin: -6px 0 0;
color: #64748b;
font-size: 12px;
}
::ng-deep .schedule-mode-panel.mat-mdc-select-panel {
max-height: 360px;
}
.enabled-toggle {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 0;
border: none;
background: none;
cursor: pointer;
font: inherit;
align-self: flex-start;
}
.enabled-toggle__track {
position: relative;
flex: 0 0 auto;
width: 36px;
height: 20px;
border-radius: 999px;
background: #cbd5e1;
transition: background 0.15s ease;
}
.enabled-toggle__thumb {
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #ffffff;
box-shadow: 0 1px 2px rgba(16, 26, 61, 0.3);
transition: transform 0.15s ease;
}
.enabled-toggle--on .enabled-toggle__track {
background: #2259a8;
}
.enabled-toggle--on .enabled-toggle__thumb {
transform: translateX(16px);
}
.enabled-toggle__label {
font-size: 14px;
color: var(--sg-text, #101a3d);
}
.enabled-toggle:focus-visible {
outline: 2px solid #2259a8;
outline-offset: 2px;
border-radius: 4px;
}
.next-run-hint {
margin: 0;
font-size: 12px;
color: #64748b;
}
@media (max-width: 640px) {
.schedule-form {
min-width: 0;
}
.schedule-fields {
grid-template-columns: 1fr;
gap: 0;
}
}
@@ -0,0 +1,223 @@
import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { BackgroundJobTask } from '../../../api';
import { formatUtcDateAsLocal } from '../jobs.utils';
export interface TaskScheduleDialogData {
task: BackgroundJobTask;
}
export interface TaskScheduleDialogResult {
taskId: number;
enabled: boolean;
schedule: string | null;
}
type ScheduleMode =
| 'manual'
| 'hourly'
| 'daily'
| 'weekly'
| 'monthly'
| 'advanced';
interface ScheduleValues {
mode: ScheduleMode;
minute: number;
time: string;
weekday: number;
monthDay: number;
}
const CRON_PATTERN = /^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/;
const TIME_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/;
const WEEKDAYS = [
{ value: 1, label: 'Montag' },
{ value: 2, label: 'Dienstag' },
{ value: 3, label: 'Mittwoch' },
{ value: 4, label: 'Donnerstag' },
{ value: 5, label: 'Freitag' },
{ value: 6, label: 'Samstag' },
{ value: 0, label: 'Sonntag' },
];
function parseSchedule(schedule: string | null): ScheduleValues {
const defaults: ScheduleValues = {
mode: 'manual',
minute: 0,
time: '03:00',
weekday: 1,
monthDay: 1,
};
if (!schedule) return defaults;
let match = schedule.match(/^(\d{1,2}) \* \* \* \*$/);
if (match && Number(match[1]) <= 59) {
return { ...defaults, mode: 'hourly', minute: Number(match[1]) };
}
match = schedule.match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/);
if (match && Number(match[1]) <= 59 && Number(match[2]) <= 23) {
return {
...defaults,
mode: 'daily',
time: toTime(match[2], match[1]),
};
}
match = schedule.match(/^(\d{1,2}) (\d{1,2}) \* \* ([0-6])$/);
if (match && Number(match[1]) <= 59 && Number(match[2]) <= 23) {
return {
...defaults,
mode: 'weekly',
time: toTime(match[2], match[1]),
weekday: Number(match[3]),
};
}
match = schedule.match(/^(\d{1,2}) (\d{1,2}) ([1-9]|[12]\d|3[01]) \* \*$/);
if (match && Number(match[1]) <= 59 && Number(match[2]) <= 23) {
return {
...defaults,
mode: 'monthly',
time: toTime(match[2], match[1]),
monthDay: Number(match[3]),
};
}
return { ...defaults, mode: 'advanced' };
}
function toTime(hour: string, minute: string): string {
return `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
}
@Component({
selector: 'app-task-schedule-dialog',
imports: [
CommonModule,
ReactiveFormsModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatSelectModule,
],
templateUrl: './task-schedule-dialog.component.html',
styleUrl: './task-schedule-dialog.component.scss',
standalone: true,
})
export class TaskScheduleDialogComponent {
private readonly dialogRef =
inject<
MatDialogRef<
TaskScheduleDialogComponent,
TaskScheduleDialogResult | undefined
>
>(MatDialogRef);
protected readonly data = inject<TaskScheduleDialogData>(MAT_DIALOG_DATA);
protected readonly weekdays = WEEKDAYS;
protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal;
private readonly initialSchedule = parseSchedule(this.data.task.schedule);
protected readonly form = new FormGroup({
enabled: new FormControl(this.data.task.enabled, { nonNullable: true }),
mode: new FormControl<ScheduleMode>(this.initialSchedule.mode, {
nonNullable: true,
}),
minute: new FormControl(this.initialSchedule.minute, {
nonNullable: true,
validators: [Validators.min(0), Validators.max(59)],
}),
time: new FormControl(this.initialSchedule.time, {
nonNullable: true,
validators: [Validators.pattern(TIME_PATTERN)],
}),
weekday: new FormControl(this.initialSchedule.weekday, {
nonNullable: true,
}),
monthDay: new FormControl(this.initialSchedule.monthDay, {
nonNullable: true,
validators: [Validators.min(1), Validators.max(31)],
}),
cronExpression: new FormControl(this.data.task.schedule ?? '', {
nonNullable: true,
}),
});
protected submit(): void {
const value = this.form.getRawValue();
const schedule = this.buildSchedule(value);
if (schedule === undefined) return;
this.dialogRef.close({
taskId: this.data.task.id,
enabled: value.enabled,
schedule,
});
}
protected close(): void {
this.dialogRef.close();
}
private buildSchedule(
value: ReturnType<typeof this.form.getRawValue>,
): string | null | undefined {
if (value.mode === 'manual') return null;
if (value.mode === 'hourly') {
if (this.form.controls.minute.invalid) {
this.form.controls.minute.markAsTouched();
return undefined;
}
return `${value.minute} * * * *`;
}
if (['daily', 'weekly', 'monthly'].includes(value.mode)) {
if (this.form.controls.time.invalid) {
this.form.controls.time.markAsTouched();
return undefined;
}
const [hour, minute] = value.time.split(':').map(Number);
if (value.mode === 'daily') return `${minute} ${hour} * * *`;
if (value.mode === 'weekly') {
return `${minute} ${hour} * * ${value.weekday}`;
}
if (this.form.controls.monthDay.invalid) {
this.form.controls.monthDay.markAsTouched();
return undefined;
}
return `${minute} ${hour} ${value.monthDay} * *`;
}
const cron = value.cronExpression.trim();
if (!CRON_PATTERN.test(cron)) {
this.form.controls.cronExpression.setErrors({ invalidCron: true });
this.form.controls.cronExpression.markAsTouched();
return undefined;
}
return cron;
}
}
@@ -424,16 +424,6 @@
<mat-icon>search</mat-icon>
Suchen
</button>
<button
mat-flat-button
color="accent"
class="visualize-btn"
[disabled]="isSearchDisabled()"
(click)="visualize()">
<mat-icon>show_chart</mat-icon>
Visualisierung
</button>
</div>
</div>
}
@@ -962,8 +962,8 @@ export class KeywordsSearchComponent {
const selected = this.parseKeywordList(queryParams.get('selected'));
const source = queryParams.get('source') ?? '';
const view = queryParams.get('view') ?? 'llm';
const legend = queryParams.get('legend') ?? 'on';
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
const legend = queryParams.get('legend') === 'true';
const legendExpanded = queryParams.get('legendExpanded') === 'true';
const fuzzy = queryParams.get('fuzzy') === 'true';
this.isRestoringState = true;
this.form.patchValue(
@@ -975,8 +975,8 @@ export class KeywordsSearchComponent {
{ emitEvent: false },
);
this.keywordView.set(view as KeywordView);
this.subfieldLegendVisible.set(legend === 'on');
this.subfieldLegendExpanded.set(legendExpanded === 'on');
this.subfieldLegendVisible.set(legend);
this.subfieldLegendExpanded.set(legendExpanded);
this.extractionSource.set(source as InputMode);
this.topicMappingSearch.set(fuzzy);
this.restoreStateFromSession();
@@ -1036,8 +1036,8 @@ export class KeywordsSearchComponent {
url: this.toNullableParam(this.form.controls.urlInput.value),
text: this.toNullableParam(this.form.controls.textInput.value),
view: this.keywordView(),
legend: this.subfieldLegendVisible() ? 'on' : 'off',
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
legend: this.subfieldLegendVisible() ? 'true' : 'false',
legendExpanded: this.subfieldLegendExpanded() ? 'true' : 'false',
broad: this.serializeKeywords(
this.getKeywordLabels(this.broadKeywords()),
),
@@ -1,31 +1,205 @@
<div class="result-layout">
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Personenliste</h2>
<p>
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
</p>
<mat-card-content>
@if (loading()) {
<p class="results-hint">Lädt…</p>
} @else if (authors().length === 0) {
<div class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Keine Autoren gefunden</h2>
<p>Passe die Keywords oder die Gewichtung an.</p>
</div>
} @else {
<div class="results-toolbar">
<span class="selected-hint">
{{ selectedIds().length }} / {{ MAX_SELECTED }} ausgewählt
</span>
<button
mat-flat-button
color="primary"
[disabled]="!canCompare()"
(click)="compare()">
<mat-icon>insights</mat-icon>
Vergleichen
</button>
</div>
<ul class="author-list">
@for (author of paginatedAuthors(); track author.author_id) {
<li class="author-item">
<mat-checkbox
class="author-select"
[checked]="isSelected(author)"
(change)="toggleSelect(author)" />
<a
class="author-name"
[routerLink]="['/person', authorProfileId(author), 'overview']">
{{ author.display_name }}
</a>
<span class="author-score">
Score: {{ author.score | number: '1.3-3' }}
</span>
</li>
}
</ul>
<app-query-param-paginator [total]="authors().length" />
}
</mat-card-content>
</mat-card>
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="Personen-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="personW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
<div class="controls-column">
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="Personen-Gewichtung"
description="Bestimme die Relevanz der einzelnen Faktoren."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="personW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)">
<section class="filter-section">
<div class="filter-section-header">
<h3>Filter</h3>
<button mat-stroked-button color="primary" (click)="resetFilters()">
<mat-icon>restart_alt</mat-icon>
Zurücksetzen
</button>
</div>
<div class="weight-row filter-row pub-type-row" style="display: block">
<mat-form-field
appearance="outline"
style="width: 100%; margin-bottom: -1.25em">
<mat-label>Art der Work</mat-label>
<mat-select
multiple
[ngModel]="selectedPubTypes()"
(ngModelChange)="onPubTypesChange($event)">
<div class="pub-type-search">
<mat-icon
class="search-icon"
style="
margin-left: 16px;
margin-right: 8px;
color: rgba(0, 0, 0, 0.54);
"
>search</mat-icon
>
<input
matInput
placeholder="Suchen..."
style="flex: 1; outline: none; border: none; padding: 12px 0"
[ngModel]="pubTypeSearchTerm()"
(ngModelChange)="pubTypeSearchTerm.set($event)"
(keydown)="onPubTypeKeydown($event)"
autocomplete="off" />
@if (pubTypeSearchTerm()) {
<button
mat-icon-button
(click)="
pubTypeSearchTerm.set(''); $event.stopPropagation()
"
style="margin-right: 8px; transform: scale(0.8)">
<mat-icon>close</mat-icon>
</button>
}
</div>
@for (pt of filteredPubTypes(); track pt) {
<mat-option [value]="pt">{{ pt }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div
class="weight-row filter-row keyword-operator-row"
style="display: block">
<mat-form-field appearance="outline" style="width: 100%">
<mat-label>Keyword-Verknüpfung</mat-label>
<mat-select
[ngModel]="keywordOperator()"
(ngModelChange)="onKeywordOperatorChange($event)">
@for (option of KEYWORD_OPERATOR_OPTIONS; track option.value) {
<mat-option [value]="option.value">{{
option.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div
class="weight-row filter-row career-stage-row"
style="display: block">
<mat-form-field appearance="outline" style="width: 100%">
<mat-label>Karrierestufe</mat-label>
<mat-select
multiple
[ngModel]="careerStages()"
(ngModelChange)="onCareerStagesChange($event)">
@for (option of CAREER_STAGE_OPTIONS; track option.value) {
<mat-option [value]="option.value">{{
option.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div
class="weight-row filter-row company-filter-row"
style="display: block">
<mat-form-field appearance="outline" style="width: 100%">
<mat-label>Unternehmen</mat-label>
<mat-select
[ngModel]="companyStatus()"
(ngModelChange)="onCompanyStatusChange($event)">
@for (option of COMPANY_STATUS_OPTIONS; track option.value) {
<mat-option [value]="option.value">{{
option.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="weight-row filter-row timespan-row">
<div class="weight-label">
<mat-icon class="icon-small">date_range</mat-icon>
<span>Zeitraum</span>
</div>
<div class="slider-container">
<div class="slider-labels timespan-range-label">
<span>{{ timespanFrom() }} – {{ timespanTo() }}</span>
</div>
<mat-slider
class="timespan-slider"
[min]="minYear"
[max]="maxYear"
[step]="1"
discrete>
<input
matSliderStartThumb
[value]="timespanFrom()"
(valueChange)="timespanFrom.set($event)"
(dragEnd)="onTimespanChange()" />
<input
matSliderEndThumb
[value]="timespanTo()"
(valueChange)="timespanTo.set($event)"
(dragEnd)="onTimespanChange()" />
</mat-slider>
</div>
</div>
</section>
</app-weights-sliders>
</div>
</div>
@@ -7,12 +7,21 @@
grid-template-areas: 'summary results';
gap: 0.75rem;
align-items: start;
width: 100%;
}
.search-summary-card {
.search-summary-card,
.controls-column {
grid-area: summary;
}
.controls-column {
display: flex;
flex-direction: column;
gap: 0.75rem;
min-width: 0;
}
.results-card {
grid-area: results;
}
@@ -27,3 +36,123 @@
padding: 0.75rem;
}
}
/* ============================================================
AUTHOR LIST
============================================================ */
.author-list {
list-style: none;
margin: 0;
padding: 0;
}
.results-toolbar {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.75rem;
padding: 0.25rem;
margin-bottom: 0.25rem;
}
.selected-hint {
color: var(--sg-text-secondary, rgba(0, 0, 0, 0.6));
font-size: 0.85rem;
}
.author-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 0.25rem;
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
}
.author-name {
flex: 1;
font-weight: 500;
text-decoration: none;
color: var(--sg-primary, #1565c0);
&:hover {
text-decoration: underline;
}
}
.author-score {
font-variant-numeric: tabular-nums;
color: var(--sg-text-secondary, rgba(0, 0, 0, 0.6));
white-space: nowrap;
}
.results-hint {
padding: 0.5rem 0.25rem;
}
/* ============================================================
FILTER SECTION (closed, bordered block below the sliders)
============================================================ */
::ng-deep .filter-section {
margin-top: 0.75rem;
padding: 0.5rem 0.6rem 0.6rem;
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
border-radius: 6px;
background: var(--sg-surface-variant, rgba(0, 0, 0, 0.015));
}
.filter-section-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.4rem;
margin-bottom: 0.4rem;
h3 {
margin: 0;
font-size: 0.8rem;
font-weight: 650;
color: var(--sg-text-primary);
}
button {
min-height: 44px;
padding: 0.2rem 0.4rem;
font-size: 0.75rem;
line-height: 1.2;
}
}
/* divider between filter rows — not before the first one */
::ng-deep .filter-section .filter-row + .filter-row {
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
}
::ng-deep .company-filter-row {
font-size: 0.8rem;
}
/* ============================================================
TIMESPAN
============================================================ */
::ng-deep .timespan-range-label {
justify-content: center !important;
font-weight: 500;
color: var(--sg-text-primary) !important;
}
::ng-deep .timespan-slider {
width: 100%;
margin: 0;
}
::ng-deep .pub-type-search {
display: flex;
align-items: center;
position: sticky;
top: 0;
z-index: 10;
background: white;
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
}
@@ -1,7 +1,18 @@
import { Component, inject, signal } from '@angular/core';
import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { DecimalPipe } from '@angular/common';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatIconModule } from '@angular/material/icon';
import { MatSliderModule } from '@angular/material/slider';
import { MatSnackBar } from '@angular/material/snack-bar';
import { FormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import {
WeightMap,
@@ -9,37 +20,87 @@ import {
WeightsSlidersComponent,
WeightsSlidersValue,
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component';
import {
CareerStage,
KeywordToAuthorRequest,
RankedAuthor,
RankingService,
} from '../../../../api';
import { SearchResultsStateService } from '../search-results-state.service';
@Component({
selector: 'app-persons-results',
standalone: true,
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
imports: [
DecimalPipe,
RouterLink,
MatButtonModule,
MatCardModule,
MatCheckboxModule,
MatIconModule,
MatSliderModule,
FormsModule,
MatSelectModule,
MatInputModule,
MatFormFieldModule,
QueryParamPaginatorComponent,
WeightsSlidersComponent,
],
templateUrl: './persons-results.component.html',
styleUrl: './persons-results.component.scss',
})
export class KeywordsToPersonsResultsComponent {
export class KeywordsToPersonsResultsComponent implements OnInit {
// injects the state set by the parent route — no duplicate parsing here
private readonly state = inject(SearchResultsStateService);
private readonly rankingService = inject(RankingService);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly snackBar = inject(MatSnackBar);
private readonly queryParams = toSignal(this.route.queryParams);
readonly pageIndex = computed(() => {
const p = this.queryParams();
return p && p['page'] ? +p['page'] || 0 : 0;
});
readonly pageSize = computed(() => {
const p = this.queryParams();
return p && p['size'] ? +p['size'] || 10 : 10;
});
readonly paginatedAuthors = computed(() => {
const all = this.authors();
const start = this.pageIndex() * this.pageSize();
return all.slice(start, start + this.pageSize());
});
// author selection for the compare view (max 4)
readonly MAX_SELECTED = 4;
readonly selectedIds = signal<string[]>([]);
readonly canCompare = computed(() => this.selectedIds().length >= 1);
// works, citations and company foundations are used as metrics/weights
readonly defaultWeights: WeightMap = {
publications: 0.5,
works: 0.5,
citations: 0.5,
companies: 0.5,
news: 0.5,
patents: 0.5,
projects: 0.5,
mediaVisibility: 0.5,
};
readonly weightOptions: WeightSliderOption[] = [
{
key: 'publications',
label: 'Publikationen',
key: 'works',
label: 'Works',
icon: 'article',
description:
'Gewichtet die Anzahl und Relevanz wissenschaftlicher Arbeiten.',
defaultValue: 0.5,
queryParamName: 'wPublications',
queryParamName: 'wWorks',
},
{
key: 'citations',
@@ -49,87 +110,388 @@ export class KeywordsToPersonsResultsComponent {
defaultValue: 0.5,
queryParamName: 'wCitations',
},
{
key: 'companies',
label: 'Unternehmensgründungen',
icon: 'business',
description:
'Gewichtet die Anzahl der Unternehmensgründungen (Handelsregister-Verbindungen).',
defaultValue: 0.5,
queryParamName: 'wCompanies',
},
{
key: 'news',
label: 'Medien-Sichtbarkeit',
icon: 'visibility',
description:
'Gewichtet die öffentliche Sichtbarkeit über Nennungen in Nachrichtenartikeln.',
defaultValue: 0.5,
queryParamName: 'wNews',
},
{
key: 'patents',
label: 'Patente',
icon: 'workspace_premium',
description: 'Gewichtet Innovations- und Transferleistung.',
description: 'Gewichtet Innovations- und Transferleistung über Patente.',
defaultValue: 0.5,
queryParamName: 'wPatents',
},
{
/*{
key: 'projects',
label: 'Projekte',
icon: 'account_tree',
description: 'Gewichtet Beteiligung an relevanten Forschungsprojekten.',
defaultValue: 0.5,
queryParamName: 'wProjects',
},
{
key: 'mediaVisibility',
label: 'Medien-Sichtbarkeit',
icon: 'visibility',
description: 'Gewichtet öffentliche und mediale Sichtbarkeit.',
defaultValue: 0.5,
queryParamName: 'wMedia',
},
}, */
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: {
publications: 0.2,
citations: 0.2,
patents: 0.2,
projects: 0.2,
mediaVisibility: 0.2,
works: 1 / 5,
citations: 1 / 5,
companies: 1 / 5,
news: 1 / 5,
patents: 1 / 5,
},
rawSum: 2.5,
normalizedSum: 1,
valid: true,
});
readonly persons = signal<unknown[]>([]); // placeholder until the results service lands
// publication-year timespan filter (range slider)
readonly minYear = 1900;
readonly maxYear = 2026;
readonly timespanFrom = signal(this.minYear);
readonly timespanTo = signal(this.maxYear);
// which companies to count for the company-foundations metric
readonly COMPANY_STATUS_OPTIONS = [
{ value: 'all', label: 'Alle Unternehmen' },
{ value: 'active', label: 'Nur aktive Unternehmen' },
{ value: 'deleted', label: 'Nur gelöschte Unternehmen' },
];
readonly companyStatus = signal<'all' | 'active' | 'deleted'>('all');
// publication types
readonly ALL_PUBLICATION_TYPES = [
'article',
'other',
'dataset',
'book-chapter',
'book',
'dissertation',
'preprint',
'paratext',
'libguides',
'review',
'letter',
'reference-entry',
'editorial',
'peer-review',
'report',
'standard',
'erratum',
'retraction',
'supplementary-materials',
'book-section',
'database',
'software',
'report-component',
'grant',
];
readonly pubTypeSearchTerm = signal('');
readonly selectedPubTypes = computed(() => {
const p = this.queryParams();
const val = p?.['pubType'];
if (!val) return [];
return Array.isArray(val) ? val : val.split(',');
});
readonly filteredPubTypes = computed(() => {
const term = this.pubTypeSearchTerm().toLowerCase();
if (!term) return this.ALL_PUBLICATION_TYPES;
return this.ALL_PUBLICATION_TYPES.filter((pt) =>
pt.toLowerCase().includes(term),
);
});
onPubTypesChange(selected: string[]) {
const val = selected.length > 0 ? selected.join(',') : null;
this.router.navigate([], {
relativeTo: this.route,
queryParams: { pubType: val, page: null },
queryParamsHandling: 'merge',
});
}
onPubTypeKeydown(event: KeyboardEvent) {
if (event.key === ' ') {
event.stopPropagation();
}
}
readonly KEYWORD_OPERATOR_OPTIONS = [
{ value: 'and', label: 'UND' },
{ value: 'or', label: 'ODER' },
];
readonly keywordOperator = signal<'and' | 'or'>('or');
onKeywordOperatorChange(operator: 'and' | 'or'): void {
this.keywordOperator.set(operator);
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
operator: operator,
page: null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
this.loadAuthors();
}
readonly CAREER_STAGE_OPTIONS = [
{ value: 'Early', label: 'Early' },
{ value: 'Emerging', label: 'Emerging' },
{ value: 'Established', label: 'Established' },
{ value: 'Senior', label: 'Senior' },
];
readonly careerStages = signal<CareerStage[]>([]);
getCareerStage(str: string): CareerStage | null {
const normalized = str.trim().toLowerCase();
for (const option of this.CAREER_STAGE_OPTIONS) {
if (option.value.toLowerCase() === normalized) {
return option.value as CareerStage;
}
}
return null;
}
onCareerStagesChange(selected: string[]) {
this.careerStages.set(
selected
.map((s) => this.getCareerStage(s))
.filter((s): s is CareerStage => !!s),
);
const val = selected.length > 0 ? selected.join(',') : null;
this.router.navigate([], {
relativeTo: this.route,
queryParams: { careerStage: val, page: null },
queryParamsHandling: 'merge',
});
}
readonly authors = signal<RankedAuthor[]>([]);
readonly loading = signal(false);
private hasLoadedInitial = false;
ngOnInit(): void {
// restore the timespan from the URL so the range is shareable/bookmarkable
this.timespanFrom.set(this.readYearParam('tFrom', this.minYear));
this.timespanTo.set(this.readYearParam('tTo', this.maxYear));
const status = this.route.snapshot.queryParamMap.get('companyStatus');
if (status === 'active' || status === 'deleted') {
this.companyStatus.set(status);
}
const careerStage = this.route.snapshot.queryParamMap.get('careerStage');
if (careerStage) {
this.careerStages.set(
careerStage
.split(',')
.map((s) => this.getCareerStage(s))
.filter((s): s is CareerStage => !!s),
);
}
const operator = this.route.snapshot.queryParamMap.get('operator');
if (operator === 'and' || operator === 'or') {
this.keywordOperator.set(operator);
}
}
// reads a year query param, clamped to the valid range; falls back on invalid input
private readYearParam(name: string, fallback: number): number {
const rawValue = this.route.snapshot.queryParamMap.get(name);
if (rawValue === null) {
return fallback;
}
const year = Number(rawValue);
if (!Number.isFinite(year)) {
return fallback;
}
return Math.min(this.maxYear, Math.max(this.minYear, Math.round(year)));
}
private writeTimespanToUrl(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { tFrom: this.timespanFrom(), tTo: this.timespanTo() },
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
onWeightsChange(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
// fires once with the query-param-aware initial state — use it to load
if (!this.hasLoadedInitial) {
this.hasLoadedInitial = true;
this.loadPersons();
this.loadAuthors();
}
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
this.loadPersons();
this.loadAuthors();
}
private loadPersons(): void {
const weights = this.currentWeights();
const requestPayload = {
manualKeywords: this.state.manualKeywords(),
extractedKeywords: this.state.extractedKeywords(),
keywords: this.state.keywords(),
fuzzy: this.state.fuzzySearch(),
weights: {
raw: weights.raw,
normalized: weights.normalized,
// change the company-status filter — persist to the URL and reload
onCompanyStatusChange(status: 'all' | 'active' | 'deleted'): void {
this.companyStatus.set(status);
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
companyStatus: status === 'all' ? null : status,
page: null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
this.loadAuthors();
}
resetFilters(): void {
this.timespanFrom.set(this.minYear);
this.timespanTo.set(this.maxYear);
this.companyStatus.set('all');
this.careerStages.set([]);
this.keywordOperator.set('and');
this.pubTypeSearchTerm.set('');
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
pubType: null,
careerStage: null,
tFrom: null,
tTo: null,
companyStatus: null,
operator: null,
page: null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
// called when a timespan thumb is released — persist to the URL and reload
onTimespanChange(): void {
if (this.timespanFrom() > this.timespanTo()) {
return;
}
this.writeTimespanToUrl();
this.loadAuthors();
}
// the backend returns the full OpenAlex url; the profile route needs only the id
authorProfileId(author: RankedAuthor): string {
const parts = author.author_id.split('/');
return parts[parts.length - 1];
}
isSelected(author: RankedAuthor): boolean {
return this.selectedIds().includes(this.authorProfileId(author));
}
toggleSelect(author: RankedAuthor): void {
const id = this.authorProfileId(author);
const current = this.selectedIds();
if (current.includes(id)) {
this.selectedIds.set(current.filter((existing) => existing !== id));
return;
}
if (current.length >= this.MAX_SELECTED) {
this.snackBar.open(
`Es können maximal ${this.MAX_SELECTED} Autoren verglichen werden.`,
'OK',
{ duration: 3000 },
);
return;
}
this.selectedIds.set([...current, id]);
}
// opens the compare page; everything needed is encoded in the URL so the link is shareable
compare(): void {
if (!this.canCompare()) {
return;
}
this.router.navigate(['/compare'], {
queryParams: {
authors: this.selectedIds().join(','),
keywords: this.state.topicsList().join(','),
operator: this.keywordOperator(),
pubType:
this.selectedPubTypes().length > 0
? this.selectedPubTypes().join(',')
: null,
tFrom: this.timespanFrom(),
tTo: this.timespanTo(),
},
});
}
private loadAuthors(): void {
const rawWeights = this.currentWeights().raw;
const request: KeywordToAuthorRequest = {
keywords: this.state.topicsList(),
operator: this.keywordOperator(),
filter_type: 'topic',
publication_types:
this.selectedPubTypes().length > 0
? this.selectedPubTypes()
: undefined,
career_stages:
this.careerStages().length > 0 ? this.careerStages() : undefined,
weights: {
works: rawWeights['works'],
citation: rawWeights['citations'],
companies: rawWeights['companies'],
news: rawWeights['news'],
patents: rawWeights['patents'],
},
timespan: {
from: this.timespanFrom(),
to: this.timespanTo(),
},
company_status: this.companyStatus(),
};
console.log(requestPayload);
/**
* TODO:
* this.personsService.searchPersons(requestPayload).subscribe({
* next: results => this.persons.set(results),
* error: error => console.error(error),
* });
*/
this.loading.set(true);
this.rankingService.rankAuthorApiRankRankAuthorPost(request).subscribe({
next: (results) => {
this.authors.set(results);
this.loading.set(false);
},
error: (error) => {
console.error(error);
this.authors.set([]);
this.loading.set(false);
},
});
}
}
@@ -3,34 +3,22 @@
<h5 style="font-weight: bold">Projekte</h5>
<p>Übersicht der durchgeführten Projekte.</p>
</div>
<mat-card appearance="outlined">
<mat-card-content>
<mat-tab-group
[selectedIndex]="selectedTabIndex()"
(selectedIndexChange)="onTabChange($event)">
<mat-tab label="DFG">
<app-project-filters
[selectedInstitutionsPage]="selectedDfgInstitutionsPage()"
[selectedAuthorsPage]="selectedDfgAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="fuzzySearch()"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true" />
<app-dfg-project-table
[page]="dfgProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()"
[institutionFilterEnabled]="true" />
</mat-tab>
<mat-tab label="EU">
<!-- <app-project-filters
[selectedInstitutionsPage]="selectedEuInstitutionsPage()"
[selectedAuthorsPage]="selectedEuAuthorsPage()" /> -->
<app-eu-project-table [page]="personCordisEuProjectPage()" />
</mat-tab>
</mat-tab-group>
</mat-card-content>
</mat-card>
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
</div>
@@ -1,73 +1,45 @@
import { Component, computed, input, signal } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { DfgInstitutionSummaryPage } from '../../../../api/model/dfgInstitutionSummaryPage';
import {
CordisEuProjectPage,
DfgProjectPage,
AuthorPage,
InstitutionPageV2,
DfgPersonSummaryPage,
TopicPageV2,
} from '../../../../api';
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../../../../shared/ui/project-filters/project-filters.component';
import { DfgProjectTableComponent } from '../../../../shared/ui/dfg-project-table/dfg-project-table.component';
import { EuProjectTableComponent } from '../../../../shared/ui/eu-project-table/eu-project-table.component';
import { projectQueryParamKeys } from '../../../../resolvers/dfg-projects.resolver';
import { euProjectQueryParamKeys } from '../../../../resolvers/person-cordis-eu-project-page.resolver';
import { OnInit, computed } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type';
import { SearchResultsStateService } from '../search-results-state.service';
@Component({
selector: 'app-projects-results',
imports: [
MatCardModule,
MatTabsModule,
ProjectFilterComponent,
DfgProjectTableComponent,
EuProjectTableComponent,
RouterLink,
RouterLinkActive,
RouterOutlet,
],
templateUrl: './projects-results.component.html',
styleUrl: './projects-results.component.scss',
})
export class KeywordsToProjectsResultsComponent {
dfgProjectPage = input.required<DfgProjectPage>();
personCordisEuProjectPage = input.required<CordisEuProjectPage>();
selectedDfgInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedDfgAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedTopicsPage = input.required<TopicPageV2>();
selectedEuInstitutionsPage = input.required<InstitutionPageV2>();
selectedEuAuthorsPage = input.required<AuthorPage>();
readonly dfgQueryParamKeys = projectQueryParamKeys;
readonly euQueryParamKeys = euProjectQueryParamKeys;
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {}
loading = signal<boolean>(false);
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
);
selectedTabIndex = computed(() => {
const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY);
return type === 'eu' ? 1 : 0;
});
onTabChange(index: number): void {
const type = index === 1 ? 'eu' : 'dfg';
this.router.navigate([], {
queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type },
queryParamsHandling: 'merge',
});
}
readonly childRoutes = [
{
path: 'dfg',
label: 'DFG-Projekte',
},
{
path: 'eu',
label: 'EU-Projekte',
},
];
}
@@ -132,14 +132,24 @@ export class SearchResultsStateService {
// without a resolvable keyword are skipped when building the lookup map
// so they can never collide on an `undefined` key and shadow a real one.
readonly topicsList = computed(() => {
const list = this.keywords().map((kw) => {
const entry = this.selectedKeywordEntries().find(
(e) =>
e.llm_keyword?.keyword?.trim().toLowerCase() ===
kw.trim().toLowerCase(),
);
return entry?.topic_mapping?.topic?.display_name ?? kw;
});
const list = this.keywords()
.map((kw) => {
const normalized = kw.trim().toLowerCase();
const entry = this.selectedKeywordEntries().find(
(e) =>
e.llm_keyword?.keyword?.trim().toLowerCase() === normalized ||
e.topic_mapping?.topic?.id?.trim().toLowerCase() === normalized,
);
const displayName = entry?.topic_mapping?.topic?.display_name;
if (displayName && !displayName.startsWith('http')) {
return displayName;
}
if (kw.startsWith('http') || kw.includes('openalex.org/topics')) {
return '';
}
return kw;
})
.filter((t) => t.length > 0);
return Array.from(new Set(list));
});
@@ -22,9 +22,9 @@
<span class="mode-badge">
<mat-slide-toggle
labelPosition="before"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, man kann dann nach Themen filtern. Wenn deaktiviert, werden die Keywords direkt für die Suche verwendet."
(change)="onToggleFuzzySearch($event)"
[checked]="state.fuzzySearch()"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, was die Suchergebnisse vermehrt">
[checked]="state.fuzzySearch()">
Fuzzy Search
</mat-slide-toggle>
</span>
@@ -69,7 +69,8 @@
keywords: state.payload()?.keywords?.join(','),
fuzzy: state.payload()?.options?.fuzzy,
topics: state.payload()?.options?.fuzzy ? state.topicIds() : null,
}">
}"
queryParamsHandling="replace">
<mat-icon>{{ route.icon }}</mat-icon>
{{ route.label }}
</a>
@@ -7,7 +7,7 @@ import {
RouterLinkActive,
RouterOutlet,
} from '@angular/router';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
@@ -38,6 +38,7 @@ import {
TopicChipComponent,
MatTabsModule,
MatSlideToggleModule,
MatTooltipModule,
],
providers: [SearchResultsStateService],
templateUrl: './search-results.component.html',
@@ -217,6 +218,7 @@ export class KeywordsSearchResultsComponent {
const queryParams = {
fuzzy: fuzzy,
topics: fuzzy ? this.state.topicIds() : null,
topicId: null,
};
this.router.navigate([], {
@@ -19,9 +19,9 @@
<div class="filter-row">
<mat-chip-listbox
[value]="activeFilter"
(change)="setFilterFromChip($event)">
<mat-chip-option value="all">Alle</mat-chip-option>
[value]="selectedSources"
multiple
(change)="handleSourceChipChange($event)">
<mat-chip-option value="EPO">EPO</mat-chip-option>
<mat-chip-option value="USPTO">USPTO</mat-chip-option>
</mat-chip-listbox>
@@ -29,6 +29,11 @@
<div class="year-filter">
<div class="year-filter-top">
<span class="year-filter-label">Zeitraum</span>
<span class="year-filter-values">
{{ selectedStartYear }} bis {{ selectedEndYear }}
</span>
<button
type="button"
class="reset-range-button"
@@ -38,12 +43,6 @@
</button>
</div>
<div class="year-filter-values">
<span>{{ selectedStartYear }}</span>
<span>bis</span>
<span>{{ selectedEndYear }}</span>
</div>
<div
class="year-range-slider"
[style.--range-start]="rangeStartPercent"
@@ -27,9 +27,13 @@ h1 {
gap: 1rem;
}
.mat-mdc-standard-chip {
border-radius: var(--sg-radius-sm);
}
.year-filter {
width: min(285px, 100%);
padding: 8px 10px;
padding: 5px 10px;
border: 1px solid #dbe5f6;
border-radius: 10px;
background: #fbfdff;
@@ -66,20 +70,16 @@ h1 {
}
.year-filter-values {
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
margin-bottom: 5px;
color: #40506f;
font-size: 12px;
font-weight: 600;
white-space: nowrap;
}
.year-filter-bounds {
display: flex;
justify-content: space-between;
margin-top: 1px;
margin-top: 0;
color: #7c88a3;
font-size: 10px;
}
@@ -90,7 +90,7 @@ h1 {
--accent: #0057ff;
position: relative;
height: 22px;
height: 16px;
}
.range-track {
@@ -7,7 +7,7 @@ import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatChipsModule } from '@angular/material/chips';
import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
@@ -22,7 +22,7 @@ import {
topicHierarchyColor,
} from '../../resolvers/utils/topic-colors';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type PatentSource = 'EPO' | 'USPTO';
type ClassificationSystem = 'IPC' | 'CPC';
@@ -72,7 +72,7 @@ export class PatentsComponent implements OnInit {
error = false;
searchTerm = '';
activeFilter: SourceFilter = 'all';
selectedSources: PatentSource[] = ['EPO', 'USPTO'];
sortDirection: string = 'asc';
// Jahr-Slider
@@ -103,8 +103,10 @@ export class PatentsComponent implements OnInit {
this.searchTerm = qp.get('search') ?? '';
this.page = parseInt(qp.get('page') ?? '0', 10);
this.pageSize = parseInt(qp.get('size') ?? '10', 10);
const f = qp.get('source');
if (f === 'EPO' || f === 'USPTO') this.activeFilter = f;
const sourcesParam = qp.get('sources');
this.selectedSources = (sourcesParam ?? 'EPO,USPTO')
.split(',')
.filter((s): s is PatentSource => s === 'EPO' || s === 'USPTO');
const d = qp.get('sort_direction');
if (d === 'asc' || d === 'desc') this.sortDirection = d;
const sy = parseInt(qp.get('year_from') ?? '', 10);
@@ -184,9 +186,18 @@ export class PatentsComponent implements OnInit {
}
private loadPatents(): void {
if (this.selectedSources.length === 0) {
this.patents = [];
this.total = 0;
this.loading = false;
this.error = false;
return;
}
this.loading = true;
this.error = false;
const source = this.activeFilter === 'all' ? undefined : this.activeFilter;
const source =
this.selectedSources.length === 1 ? this.selectedSources[0] : undefined;
this.patentsApi
.getAllPatents(
@@ -223,9 +234,11 @@ export class PatentsComponent implements OnInit {
this.updateQueryParams();
}
setFilterFromChip(event: any): void {
const val = event.value;
this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all';
handleSourceChipChange(change: MatChipListboxChange): void {
const selected = change.value as PatentSource[];
// Deselecting every chip resets back to "all sources", mirroring the
// project-type filter's behavior instead of showing an empty state.
this.selectedSources = selected.length ? selected : ['EPO', 'USPTO'];
this.page = 0;
this.loadPatents();
this.updateQueryParams();
@@ -267,7 +280,9 @@ export class PatentsComponent implements OnInit {
search: this.searchTerm || null,
page: this.page,
size: this.pageSize,
source: this.activeFilter === 'all' ? null : this.activeFilter,
sources: this.selectedSources.length
? this.selectedSources.join(',')
: null,
sort_direction: this.sortDirection,
year_from:
this.selectedStartYear !== this.minYear
@@ -68,10 +68,7 @@
[matTooltip]="inst.display_name || ''"
[matTooltipDisabled]="loading()"
matTooltipPosition="above"
(click)="
institutionClick.emit(inst.display_name || '');
$event.stopPropagation()
">
(click)="institutionClick.emit(inst); $event.stopPropagation()">
<mat-icon
style="
font-size: 12px;
@@ -29,11 +29,11 @@ export class PersonCardComponent {
isBookmarked = input<boolean>(false);
loading = input<boolean>(false);
selectedTopics = input<Set<string>>(new Set<string>());
activeInstitutionName = input<string>('');
activeInstitutionId = input<string>('');
bookmarkToggle = output<CustomAuthor>();
topicClick = output<string>();
institutionClick = output<string>();
institutionClick = output<DehydratedInstitution>();
initials = computed<string>(() => {
const name = this.person().display_name;
@@ -83,11 +83,9 @@ export class PersonCardComponent {
}
isInstitutionActive = computed<boolean>(() => {
const active = this.activeInstitutionName().trim().toLowerCase();
const active = this.normalizeInstitutionId(this.activeInstitutionId());
if (!active) return false;
return (
(this.institution()?.display_name ?? '').trim().toLowerCase() === active
);
return this.normalizeInstitutionId(this.institution()?.id ?? '') === active;
});
topics = computed<WorkTopic[]>(() => {
@@ -170,6 +168,10 @@ export class PersonCardComponent {
this.topicClick.emit(topicName);
}
private normalizeInstitutionId(id: string): string {
return id.replace('https://openalex.org/', '').trim().toUpperCase();
}
getCareerStageTooltip(careerStage: string): string {
const activeYears = this.person().career_metrics?.active_years ?? '-';
@@ -7,11 +7,6 @@
<div class="state state-error">
Verbindungen zu Unternehmen konnten nicht geladen werden.
</div>
} @else if (data && !data.is_ude_author) {
<section class="empty-state">
<h2>Keine Unternehmenssuche verfügbar</h2>
<p>Für diese Person wird aktuell keine Suche nach Unternehmen angezeigt.</p>
</section>
} @else if (data && connections.length === 0) {
<section class="empty-state">
<h2>Keine Treffer im Handelsregister</h2>
@@ -1,12 +1,14 @@
import { CommonModule, LocationStrategy } from '@angular/common';
import {
Component,
DestroyRef,
ElementRef,
OnInit,
QueryList,
ViewChildren,
inject,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
@@ -22,6 +24,7 @@ import {
CompanyConnectionsService,
MatchedOfficer,
} from '../../api';
import { PersonDataResolved } from '../../resolvers/person.resolver';
interface RoleLegendItem {
role: string;
@@ -47,6 +50,7 @@ interface RoleLegendItem {
export class PersonCompanyConnectionsComponent implements OnInit {
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
private readonly locationStrategy = inject(LocationStrategy);
private readonly companyConnectionsApi = inject(CompanyConnectionsService);
@@ -115,17 +119,31 @@ export class PersonCompanyConnectionsComponent implements OnInit {
}
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
const authorId = params.get('id');
const parentRoute = this.route.parent;
const authorId = parentRoute?.snapshot.paramMap.get('id');
const resolved = parentRoute?.snapshot.data['personData'] as
| PersonDataResolved
| undefined;
if (!authorId) {
this.loading = false;
this.error = true;
return;
}
if (!authorId || !resolved) {
this.loading = false;
this.error = true;
return;
}
this.loadCompanyConnections(authorId);
});
resolved.companyConnectionsAvailable$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((available) => {
if (!available) {
void this.router.navigate(['overview'], {
relativeTo: parentRoute,
replaceUrl: true,
});
return;
}
this.loadCompanyConnections(authorId);
});
}
getPrimaryOfficer(connection: CompanyConnection): MatchedOfficer | null {
@@ -329,7 +347,7 @@ export class PersonCompanyConnectionsComponent implements OnInit {
): EChartsOption | null {
const connections = response.connections ?? [];
if (!response.is_ude_author || connections.length === 0) {
if (connections.length === 0) {
return null;
}
@@ -307,26 +307,32 @@
<!-- Linke Seite: Tabelle -->
<div class="funding-list">
<div class="funding-list-toolbar">
<label class="sort-control">
<span>Filter nach Position:</span>
<select
<mat-form-field
class="funding-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="filter_alt"></mat-icon>
<mat-select
[value]="activeFilter"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="first">Erstautor</option>
<option value="middle">Mitautor</option>
<option value="last">Letztautor</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select
(selectionChange)="setFilter($event.value)">
<mat-select-trigger>Filter nach Position</mat-select-trigger>
<mat-option value="all">Alle</mat-option>
<mat-option value="first">Erstautor</mat-option>
<mat-option value="middle">Mitautor</mat-option>
<mat-option value="last">Letztautor</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="funding-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortMode"
(change)="setSortMode($any($event.target).value)">
<option value="name">Name</option>
<option value="top">Top Förderer</option>
</select>
</label>
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="name">Name</mat-option>
<mat-option value="top">Top Förderer</mat-option>
</mat-select>
</mat-form-field>
</div>
<table>
<thead>
@@ -445,7 +451,9 @@
<div class="funding-detail empty">
<div class="empty-overview">
@if (activeFilter !== 'all') {
<span class="empty-overview__filter">
<span
class="empty-overview__filter"
[ngClass]="getPositionBadgeClass(activeFilter)">
Filter: {{ getPositionLabel(activeFilter) }}
</span>
}
@@ -458,7 +466,8 @@
}
</p>
<div class="empty-overview__stats">
<div class="empty-overview__stat">
<div
class="empty-overview__stat empty-overview__stat--publications">
<span class="empty-overview__stat-value">{{
getUniquePublicationCount()
}}</span>
@@ -466,7 +475,7 @@
>Einzigartige Publikationen</span
>
</div>
<div class="empty-overview__stat">
<div class="empty-overview__stat empty-overview__stat--funders">
<span class="empty-overview__stat-value">{{
filteredFunders.length
}}</span>
@@ -474,7 +483,6 @@
</div>
</div>
<div class="empty-overview__hint">
<span class="material-icons" aria-hidden="true">touch_app</span>
<p>
Wähle links einen Förderer aus, um die zugehörigen Publikationen
anzuzeigen.
@@ -10,29 +10,9 @@
gap: 16px;
}
.sort-control {
display: inline-flex;
align-items: center;
gap: 6px;
.funding-toolbar-field {
width: fit-content;
padding: 10px 14px;
border-radius: 20px;
background: #f2f2f2;
color: #333;
font-size: 14px;
span {
color: #555;
}
select {
border: 0;
background: transparent;
color: #111827;
font: inherit;
cursor: pointer;
outline: none;
}
min-width: 180px;
}
.funding-content {
@@ -91,22 +71,6 @@
padding: 20px;
background: #fafafa;
&.empty {
display: flex;
align-items: center;
justify-content: center;
min-height: 280px;
padding: 24px;
background:
radial-gradient(
circle at 100% 0%,
rgba(200, 217, 255, 0.35),
transparent 45%
),
linear-gradient(160deg, #fff 0%, #f8faff 100%);
border-color: #dbe3f2;
}
h3 {
margin: 0 0 16px;
font-size: 16px;
@@ -147,51 +111,64 @@
font-weight: bold;
color: #333;
}
&.stat-first {
background: #effaf3;
border-color: #bdebcf;
.stat-label,
.stat-value {
color: #24834f;
}
}
&.stat-middle {
background: #f6f0ff;
border-color: #d8cafe;
.stat-label,
.stat-value {
color: #7255d9;
}
}
&.stat-last {
background: #fff1f2;
border-color: #fda4af;
.stat-label,
.stat-value {
color: #be123c;
}
}
}
}
.stat-first,
.position-badge--first,
.hero-highlight--open,
.publication-detail-grid .access-badge--open {
background: #effaf3;
}
.stat-first {
border-color: #bdebcf;
}
.position-badge--first {
color: #24834f;
border: 1px solid #bdebcf;
}
.hero-highlight--open,
.publication-detail-grid .access-badge--open {
border-color: #bdebcf;
color: #24834f;
}
.stat-middle,
.position-badge--middle {
background: #f6f0ff;
border-color: #d8cafe;
}
.position-badge--middle {
color: #7255d9;
border: 1px solid #d8cafe;
}
.stat-last,
.position-badge--last {
background: #fff1f2;
border-color: #fda4af;
color: #be123c;
}
.position-badge--first,
.position-badge--middle,
.position-badge--last {
color: #be123c;
border: 1px solid #fda4af;
border-width: 1px;
border-style: solid;
}
.publication-list {
@@ -237,7 +214,6 @@
.empty-overview {
width: 100%;
text-align: center;
&__filter {
display: inline-block;
@@ -250,71 +226,87 @@
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
&.position-badge--first {
background: #effaf3;
border-color: #bdebcf;
color: #24834f;
}
&.position-badge--middle {
background: #f6f0ff;
border-color: #d8cafe;
color: #7255d9;
}
&.position-badge--last {
background: #fff1f2;
border-color: #fda4af;
color: #be123c;
}
}
&__title {
margin: 0 0 8px;
font-size: 1.125rem;
color: #1e3a5f;
font-size: 15px;
font-weight: 600;
color: #333;
}
&__subtitle {
margin: 0 0 20px;
color: #64748b;
font-size: 0.875rem;
line-height: 1.5;
color: #888;
font-size: 13px;
}
&__stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
gap: 10px;
margin-bottom: 20px;
}
&__stat {
display: flex;
flex-direction: column;
gap: 6px;
padding: 16px 12px;
border: 1px solid #e0e6f0;
border-radius: 10px;
background: rgba(255, 255, 255, 0.85);
text-align: center;
padding: 12px 8px;
border: 1px solid #e0e0e0;
border-radius: 8px;
background: #fff;
}
&__stat-value {
font-size: 1.75rem;
display: block;
font-size: 22px;
font-weight: 700;
line-height: 1.1;
color: #1e3a5f;
color: #333;
}
&__stat-label {
font-size: 0.8rem;
line-height: 1.35;
color: #64748b;
display: block;
font-size: 12px;
color: #888;
margin-top: 4px;
}
&__stat--publications {
.empty-overview__stat-value,
.empty-overview__stat-label {
color: #0b63ce;
}
}
&__stat--funders {
.empty-overview__stat-value,
.empty-overview__stat-label {
color: #b45309;
}
}
&__hint {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 12px 14px;
border: 1px dashed #c7d5ea;
border-radius: 10px;
background: rgba(255, 255, 255, 0.7);
text-align: left;
.material-icons {
font-size: 20px;
color: #3b82c4;
}
p {
margin: 0;
color: #475569;
font-size: 0.875rem;
line-height: 1.45;
color: #aaa;
font-size: 12px;
}
}
}
@@ -3,6 +3,9 @@ import { CommonModule } from '@angular/common';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { FundingService } from '../../api';
type SortMode = 'name' | 'top';
@@ -52,7 +55,7 @@ type FundingPublicationDetail = {
@Component({
selector: 'app-person-funding',
imports: [CommonModule],
imports: [CommonModule, MatFormFieldModule, MatSelectModule, MatIconModule],
templateUrl: './person-funding.component.html',
styleUrl: './person-funding.component.scss',
})
@@ -59,7 +59,7 @@
<mat-icon>close</mat-icon>
</button>
</span>
} @else if (filter.category === 'institutionName') {
} @else if (filter.category === 'institutionId') {
<span [skText]="loading" class="active-institution-filter">
<span class="filter-institution-chip">
<mat-icon class="filter-institution-chip__icon"
@@ -82,7 +82,7 @@
filter.countryCode.toUpperCase()
}}</span>
}
@if (findInstitutionPageIdByName(filter.value)) {
@if (filter.value) {
<mat-icon
class="institution-open-icon"
(click)="openInstitutionPage(filter.value, $event)"
@@ -165,7 +165,7 @@
[person]="person"
[isBookmarked]="isBookmarked(person)"
[selectedTopics]="selectedTopics()"
[activeInstitutionName]="appliedInstitutionName"
[activeInstitutionId]="appliedInstitutionId"
(bookmarkToggle)="toggleBookmark($event)"
(topicClick)="onCardTopicClick($event)"
(institutionClick)="onCardInstitutionClick($event)">
@@ -246,9 +246,10 @@
(keyup.enter)="applySidebarFilters()" />
<mat-autocomplete
#auto="matAutocomplete"
[displayWith]="displayInstitution"
(optionSelected)="onInstitutionSelected($event)">
@for (institution of institutionOptions(); track institution.id) {
<mat-option [value]="institution.display_name">
<mat-option [value]="institution">
<span>{{ institution.display_name }}</span>
@if (institution.hint) {
<small>{{ institution.hint }}</small>
@@ -259,7 +260,7 @@
!institutionLookupLoading() &&
institutionOptions().length === 0 &&
institutionControl.value &&
institutionControl.value.trim().length >= 2
displayInstitution(institutionControl.value).trim().length >= 2
) {
<mat-option disabled>Keine Institution gefunden</mat-option>
}
@@ -284,11 +285,11 @@
<mat-checkbox
[formControl]="yearFilterEnabledControl"
(change)="applySidebarFilters()"
aria-label="Zusammenarbeit nach Jahr filtern">
aria-label="Institutionszugehörigkeit nach Jahr filtern">
<span
style="font-size: 12px; font-weight: 500; color: var(--sg-text)"
>Zusammenarbeit nach Jahr filtern</span
>
style="font-size: 12px; font-weight: 500; color: var(--sg-text)">
Institutionszugehörigkeit nach Jahr filtern
</span>
</mat-checkbox>
@if (yearFilterEnabledControl.value) {
@@ -305,16 +306,16 @@
(change)="applySidebarFilters()"
style="display: flex; gap: 16px"
aria-label="Modus für Jahresfilter">
<mat-radio-button value="in"
><span style="font-size: 12px; color: var(--sg-text)"
>Genau in</span
></mat-radio-button
>
<mat-radio-button value="from"
><span style="font-size: 12px; color: var(--sg-text)"
>Seit</span
></mat-radio-button
>
<mat-radio-button value="in">
<span style="font-size: 12px; color: var(--sg-text)">
Genau im Jahr
</span>
</mat-radio-button>
<mat-radio-button value="from">
<span style="font-size: 12px; color: var(--sg-text)">
Seit
</span>
</mat-radio-button>
</mat-radio-group>
<mat-form-field
@@ -86,6 +86,8 @@ export class PersonListComponent {
currentPage = 1;
readonly institutionOptions = signal<any[]>([]);
readonly institutionLookupLoading = signal<boolean>(false);
readonly selectedInstitution = signal<DehydratedInstitution | null>(null);
readonly defaultMembershipYear = new Date().getUTCFullYear() - 2;
defaultOrderValue = 'desc';
@@ -95,10 +97,11 @@ export class PersonListComponent {
readonly topicSearchType = signal<'hybrid' | 'semantic'>('hybrid');
// Applied filter states (reflecting actual URL query params)
appliedInstitutionName = '';
appliedYearFilterEnabled = false;
appliedFilterMode: 'in' | 'from' = 'from';
appliedFilterYear = new Date().getFullYear() - 1;
public appliedInstitutionId = '';
public appliedInstitutionName = '';
public appliedYearFilterEnabled = false;
public appliedFilterMode: 'in' | 'from' = 'from';
public appliedFilterYear = this.defaultMembershipYear;
// Forms
sortValueControl = new FormControl(null, {
@@ -109,12 +112,14 @@ export class PersonListComponent {
{ nonNullable: true },
);
topicSearchControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl<string | DehydratedInstitution>('', {
nonNullable: true,
});
yearFilterEnabledControl = new FormControl(false, { nonNullable: true });
filterModeControl = new FormControl<'in' | 'from'>('from', {
nonNullable: true,
});
filterYearControl = new FormControl<number>(new Date().getFullYear() - 1, {
filterYearControl = new FormControl<number>(this.defaultMembershipYear, {
nonNullable: true,
validators: [
Validators.min(1900),
@@ -134,11 +139,14 @@ export class PersonListComponent {
this.setupInstitutionAutocomplete();
// Enable/disable the year filter checkbox based on the presence of an institution value
this.updateYearFilterState(this.institutionControl.value);
this.updateYearFilterState(this.selectedInstitution());
this.institutionControl.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((val) => {
this.updateYearFilterState(val);
if (typeof val === 'string') {
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
}
});
this.route.queryParams
@@ -149,17 +157,19 @@ export class PersonListComponent {
const pageSize = params['pageSize']
? Number.parseInt(params['pageSize'], 10)
: 10;
const institutionId = params['institutionId'] || '';
const institutionName = params['institutionName'] || '';
const sortBy = params['sortBy'] || null;
const sortOrder = params['sortOrder'] || this.defaultOrderValue;
const yearFilterEnabled = params['yearFilterEnabled'] === 'true';
const yearFilterEnabled =
!!institutionId && params['yearFilterEnabled'] !== 'false';
const filterMode =
params['filterMode'] === 'in' || params['filterMode'] === 'from'
? params['filterMode']
: 'from';
const filterYear = params['filterYear']
? Number.parseInt(params['filterYear'], 10)
: new Date().getFullYear() - 1;
: this.defaultMembershipYear;
const topicSearch = params['topicSearch'] || '';
const topicSearchType =
params['topicSearchType'] === 'semantic' ? 'semantic' : 'hybrid';
@@ -181,12 +191,23 @@ export class PersonListComponent {
if (this.searchValue() !== query) {
this.searchValue.set(query || null);
}
if (this.institutionControl.value !== institutionName) {
this.institutionControl.setValue(institutionName, {
const institution =
institutionId && institutionName
? ({
id: institutionId,
display_name: institutionName,
} satisfies DehydratedInstitution)
: null;
this.selectedInstitution.set(institution);
if (
this.displayInstitution(this.institutionControl.value) !==
institutionName
) {
this.institutionControl.setValue(institution ?? '', {
emitEvent: false,
});
this.updateYearFilterState(institutionName);
}
this.updateYearFilterState(institution);
if (this.yearFilterEnabledControl.value !== yearFilterEnabled) {
this.yearFilterEnabledControl.setValue(yearFilterEnabled);
}
@@ -202,6 +223,7 @@ export class PersonListComponent {
this.topicSearchType.set(topicSearchType);
// Update applied filter states
this.appliedInstitutionId = institutionId;
this.appliedInstitutionName = institutionName;
this.appliedYearFilterEnabled = yearFilterEnabled;
this.appliedFilterMode = filterMode;
@@ -311,15 +333,18 @@ export class PersonListComponent {
this.selectedTopics().forEach((t) => {
list.push({ category: 'topic', value: t, label: `Thema: ${t}` });
});
if (this.appliedInstitutionName) {
if (this.appliedInstitutionId && this.appliedInstitutionName) {
let label = `Institution: ${this.appliedInstitutionName}`;
if (this.appliedYearFilterEnabled) {
const modeLabel = this.appliedFilterMode === 'in' ? 'in' : 'from';
label += ` (${modeLabel} ${this.appliedFilterYear})`;
const periodLabel =
this.appliedFilterMode === 'in'
? `im Jahr ${this.appliedFilterYear}`
: `seit ${this.appliedFilterYear}`;
label += ` (${periodLabel})`;
}
list.push({
category: 'institutionName',
value: this.appliedInstitutionName,
category: 'institutionId',
value: this.appliedInstitutionId,
label: label,
countryCode: this.findInstitutionCountryCode(
this.appliedInstitutionName,
@@ -333,36 +358,11 @@ export class PersonListComponent {
return filter.label.replace(/^Institution:\s*/, '');
}
findInstitutionPageIdByName(institutionName: string): string | null {
const normalized = institutionName.trim().toLowerCase();
if (!normalized) {
return null;
}
for (const person of this.persons) {
const candidates: Array<DehydratedInstitution | undefined> = [
...(person.last_known_institutions ?? []),
...(person.affiliations ?? []).map((a) => a.institution ?? undefined),
];
for (const inst of candidates) {
if (
inst?.id &&
(inst.display_name ?? '').trim().toLowerCase() === normalized
) {
return inst.id.split('/').pop() ?? null;
}
}
}
return null;
}
openInstitutionPage(institutionName: string, event: Event): void {
openInstitutionPage(institutionId: string, event: Event): void {
event.stopPropagation();
event.preventDefault();
const id = this.findInstitutionPageIdByName(institutionName);
const id = institutionId.split('/').pop();
if (!id) return;
void this.router.navigate(['/institution', id]);
@@ -400,13 +400,14 @@ export class PersonListComponent {
next.delete(filter.value);
return next;
});
} else if (filter.category === 'institutionName') {
} else if (filter.category === 'institutionId') {
this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState('');
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
this.institutionOptions.set([]);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
this.filterYearControl.setValue(this.defaultMembershipYear);
}
this.applySidebarFilters();
}
@@ -453,11 +454,12 @@ export class PersonListComponent {
clearAllFilters(): void {
this.selectedTopics.set(new Set<string>());
this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState('');
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
this.institutionOptions.set([]);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
this.filterYearControl.setValue(this.defaultMembershipYear);
this.applySidebarFilters();
}
@@ -465,6 +467,7 @@ export class PersonListComponent {
if (this.yearFilterEnabledControl.value && this.filterYearControl.invalid) {
return;
}
const institution = this.selectedInstitution();
this.router.navigate([], {
queryParams: {
topic: this.selectedTopics().size
@@ -473,22 +476,23 @@ export class PersonListComponent {
topicSearch: this.topicSearchControl.value || null,
topicSearchType:
this.topicSearchType() === 'semantic' ? 'semantic' : null,
institutionName: this.institutionControl.value || null,
institutionId: institution?.id || null,
institutionName: institution?.display_name || null,
sortBy: this.sortValueControl.value || null,
sortOrder: this.sortOrderControl.value || null,
yearFilterEnabled:
this.institutionControl.value && this.yearFilterEnabledControl.value
yearFilterEnabled: institution
? this.yearFilterEnabledControl.value
? 'true'
: null,
: 'false'
: null,
filterMode:
this.institutionControl.value && this.yearFilterEnabledControl.value
institution && this.yearFilterEnabledControl.value
? this.filterModeControl.value
: null,
filterYear:
this.institutionControl.value && this.yearFilterEnabledControl.value
institution && this.yearFilterEnabledControl.value
? this.filterYearControl.value
: null,
strict: null,
page: 1,
},
queryParamsHandling: 'merge',
@@ -535,9 +539,14 @@ export class PersonListComponent {
this.toggleTopic(topic);
}
onCardInstitutionClick(institutionName: string): void {
this.institutionControl.setValue(institutionName, { emitEvent: false });
this.updateYearFilterState(institutionName);
onCardInstitutionClick(institution: DehydratedInstitution): void {
if (!institution.id || !institution.display_name) {
return;
}
this.selectedInstitution.set(institution);
this.institutionControl.setValue(institution, { emitEvent: false });
this.resetActiveMembershipFilter();
this.updateYearFilterState(institution);
this.institutionOptions.set([]);
this.applySidebarFilters();
}
@@ -604,8 +613,8 @@ export class PersonListComponent {
.pipe(map((response) => response.results ?? []));
}
updateYearFilterState(val: string): void {
if (!val) {
updateYearFilterState(institution: DehydratedInstitution | null): void {
if (!institution?.id) {
this.yearFilterEnabledControl.disable();
this.yearFilterEnabledControl.setValue(false);
} else {
@@ -615,19 +624,40 @@ export class PersonListComponent {
clearInstitutionFilter(): void {
this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState('');
this.selectedInstitution.set(null);
this.updateYearFilterState(null);
this.institutionOptions.set([]);
this.applySidebarFilters();
}
onInstitutionSelected(event: MatAutocompleteSelectedEvent): void {
const val = event.option.value;
this.institutionControl.setValue(val, { emitEvent: false });
this.updateYearFilterState(val);
const institution = event.option.value as DehydratedInstitution;
if (!institution.id || !institution.display_name) {
return;
}
this.selectedInstitution.set(institution);
this.institutionControl.setValue(institution, { emitEvent: false });
this.resetActiveMembershipFilter();
this.updateYearFilterState(institution);
this.institutionOptions.set([]);
this.applySidebarFilters();
}
public readonly displayInstitution = (
institution: string | DehydratedInstitution | null,
): string =>
typeof institution === 'string'
? institution
: (institution?.display_name ?? '');
private resetActiveMembershipFilter(): void {
this.yearFilterEnabledControl.setValue(true, { emitEvent: false });
this.filterModeControl.setValue('from', { emitEvent: false });
this.filterYearControl.setValue(this.defaultMembershipYear, {
emitEvent: false,
});
}
private parseQueryParamArray(val: any): string[] {
if (!val) return [];
if (Array.isArray(val)) return val;
@@ -1,104 +1,50 @@
<h2 mat-dialog-title>Netzwerkfilter</h2>
<mat-dialog-content>
<mat-tab-group
(selectedTabChange)="onTabChange($event)"
[selectedIndex]="selectedTabIndex()">
<mat-tab label="Publikationen">
<form [formGroup]="worksFilterForm">
<div class="pair-field">
<mat-form-field>
<mat-label>Startjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="startYear" />
</mat-form-field>
<mat-form-field>
<mat-label>Endjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="endYear" />
</mat-form-field>
</div>
<mat-form-field>
<mat-label>Minimale Anzahl von Kollaborierenden (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="minContributors" />
</mat-form-field>
<mat-form-field>
<mat-label>Maximale Anzahl von Kollaborierenden (exklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="maxContributors" />
</mat-form-field>
<mat-form-field>
<mat-label>Themen</mat-label>
<mat-select
formControlName="topics"
multiple
appearance="outline"
placeholder="Alle Themen">
@for (
topic of collaborationNetwork.filter_information.topics;
track topic.raw_topic_id
) {
<mat-option [value]="topic.raw_topic_id">
{{ topic.display_name }}
</mat-option>
}
</mat-select>
</mat-form-field>
</form>
</mat-tab>
<mat-tab label="Kollaborierende">
<form [formGroup]="authorsFilterForm">
<mat-form-field>
<mat-label>Minimale Anzahl von Kollaborationen (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="minCollaborations" />
</mat-form-field>
<mat-form-field>
<mat-label>Maximale Anzahl von Kollaborationen (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="maxCollaborations" />
</mat-form-field>
<mat-form-field>
<mat-label>Institutionen</mat-label>
<mat-select
formControlName="institutions"
multiple
appearance="outline"
placeholder="Alle Institutionen">
@for (
institution of collaborationNetwork.filter_information
.institutions;
track institution.raw_id
) {
<mat-option [value]="institution.raw_id">
{{ institution.display_name }}
</mat-option>
}
</mat-select>
</mat-form-field>
</form>
</mat-tab>
</mat-tab-group>
<form>
<div class="pair-field">
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Startjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.startYear" />
</mat-form-field>
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Endjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.endYear" />
</mat-form-field>
</div>
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Minimale Anzahl von Kollaborierenden (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.minContributors" />
</mat-form-field>
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Maximale Anzahl von Kollaborierenden (exklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.maxContributors" />
</mat-form-field>
<app-searchable-topic-select
[selectedTopics]="this.data.selectedTopics"
(handleTopicSelectChange)="handleSelectedTopicsChange($event)" />
<app-searchable-institution-select
[selectedInstitutions]="this.data.selectedInstitutions"
(handleInstitutionSelectChange)="
handleSelectedInstitutionsChange($event)
" />
</form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="onCancel()">Abbrechen</button>
@@ -1,9 +1,10 @@
form {
padding-top: 20px;
padding: 0.5rem;
display: flex;
flex-direction: column;
min-width: 500px;
min-height: 350px;
gap: 1rem;
}
.form-field-full {
@@ -1,35 +1,36 @@
import { Component, inject, OnInit, signal } from '@angular/core';
import {
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { CollaborationNetwork } from '../../api';
import { Institution, Topic } from '../../api';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatTabsModule } from '@angular/material/tabs';
import { SearchableTopicSelectComponent } from '../../shared/ui/searchable-topic-select/searchable-topic-select.component';
import { SearchableInstitutionSelectComponent } from '../../shared/ui/searchable-institution-select/searchable-institution-select.component';
import { form, FormField } from '@angular/forms/signals';
export interface PersonNetworkFilterDialogData {
collaborationNetwork: CollaborationNetwork;
filterBy: 'works' | 'authors';
selectedInstitutions: Institution[];
selectedTopics: Topic[];
startYear: number;
endYear: number;
topics: string[];
minContributors: number;
maxContributors: number;
}
minCollaborations: number;
maxCollaborations: number;
institutions: string[];
interface FilterData {
startYear: number;
endYear: number;
minContributors: number;
maxContributors: number;
topics: Topic[];
institutions: Institution[];
}
@Component({
@@ -43,6 +44,9 @@ export interface PersonNetworkFilterDialogData {
MatInputModule,
MatButtonModule,
MatTabsModule,
SearchableTopicSelectComponent,
SearchableInstitutionSelectComponent,
FormField,
],
templateUrl: './person-network-filter-dialog.component.html',
styleUrl: './person-network-filter-dialog.component.scss',
@@ -51,45 +55,25 @@ export class PersonNetworkFilterDialogComponent implements OnInit {
readonly dialogRef = inject(MatDialogRef<PersonNetworkFilterDialogComponent>);
readonly data = inject<PersonNetworkFilterDialogData>(MAT_DIALOG_DATA);
readonly collaborationNetwork = this.data.collaborationNetwork;
worksFilterForm = new FormGroup({
startYear: new FormControl(this.data.startYear),
endYear: new FormControl(this.data.endYear),
topics: new FormControl<string[]>(this.data.topics),
minContributors: new FormControl(this.data.minContributors),
maxContributors: new FormControl(this.data.maxContributors),
filterModel = signal<FilterData>({
startYear: this.data.startYear,
endYear: this.data.endYear,
minContributors: this.data.minContributors,
maxContributors: this.data.maxContributors,
topics: this.data.selectedTopics,
institutions: this.data.selectedInstitutions,
});
authorsFilterForm = new FormGroup({
minCollaborations: new FormControl(this.data.minCollaborations),
maxCollaborations: new FormControl(this.data.maxCollaborations),
institutions: new FormControl<string[]>(this.data.institutions),
});
filterForm = form(this.filterModel);
selectedTabIndex = signal(0);
ngOnInit() {
console.log('Received data:', this.data);
if (this.data.filterBy === 'works') {
this.selectedTabIndex.set(0);
} else if (this.data.filterBy === 'authors') {
this.selectedTabIndex.set(1);
}
this.authorsFilterForm.patchValue({
minCollaborations: this.data.minCollaborations,
maxCollaborations: this.data.maxCollaborations,
institutions: this.data.institutions,
});
this.worksFilterForm.patchValue({
ngOnInit(): void {
this.filterModel.set({
startYear: this.data.startYear,
endYear: this.data.endYear,
topics: this.data.topics,
minContributors: this.data.minContributors,
maxContributors: this.data.maxContributors,
topics: this.data.selectedTopics,
institutions: this.data.selectedInstitutions,
});
}
@@ -98,24 +82,41 @@ export class PersonNetworkFilterDialogComponent implements OnInit {
}
onApply() {
const filterData = {
filterBy: this.filterBy(),
worksFilterProperties: this.worksFilterForm.value,
authorsFilterProperties: this.authorsFilterForm.value,
};
this.dialogRef.close(filterData);
this.dialogRef.close({
startYear: this.filterForm.startYear().value(),
endYear: this.filterForm.endYear().value(),
minContributors: this.filterForm.minContributors().value(),
maxContributors: this.filterForm.maxContributors().value(),
topics: this.filterForm.topics().value(),
institutions: this.filterForm.institutions().value(),
});
}
filterBy() {
return this.selectedTabIndex() === 0 ? 'works' : 'authors';
handleSelectedTopicsChange(selectedTopic: Topic) {
const value = this.filterForm.topics().value();
if (value.some((topic) => topic.id === selectedTopic.id)) {
this.filterForm
.topics()
.value.set(value.filter((topic) => topic.id !== selectedTopic.id));
} else {
this.filterForm.topics().value.set([...value, selectedTopic]);
}
}
onTabChange(event: any) {
this.selectedTabIndex.set(event.index);
if (event.index === 0) {
console.log('Switched to Works tab');
} else if (event.index === 1) {
console.log('Switched to Authors tab');
handleSelectedInstitutionsChange(selectedInstitution: Institution) {
const value = this.filterForm.institutions().value();
if (
value.some((institution) => institution.id === selectedInstitution.id)
) {
this.filterForm
.institutions()
.value.set(
value.filter(
(institution) => institution.id !== selectedInstitution.id,
),
);
} else {
this.filterForm.institutions().value.set([...value, selectedInstitution]);
}
}
}
@@ -1,73 +1,90 @@
<div class="content">
<div class="description-container">
<h5 style="font-weight: bold">Netzwerk</h5>
<p>Zusammenarbeit und Verbindungen im wissenschaftlichen Netzwerk.</p>
@if (this.isPending()) {
<app-loading
text="Das Netzwerk wird gebaut, kleinen Moment..."
icon="graph_3"
[size]="150"
[diameter]="150" />
} @else if (this.isFailed()) {
<div class="error">
<mat-icon>error</mat-icon>
<span class="error-message">{{
this.collaborationGraphError()
? this.collaborationGraphError()
: 'Fehler beim Laden des Netzwerks. Bitte versuchen Sie es später erneut.'
}}</span>
<app-selected-filters [observers]="observers" />
<button matButton="outlined" type="button" (click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
} @else {
<div class="grid">
<div class="cell">
<mat-card appearance="outlined" style="height: 100%">
<mat-card-content>
<app-collaboration-graph
[collaborationGraph]="collaborationGraph()!"
(handleNodeClick)="handleNodeClick($event)" />
</mat-card-content>
</mat-card>
</div>
<div class="cell">
<div class="toggle-group">
<mat-button-toggle-group
class="mat-button-toggle-group"
aria-label="Select view"
(change)="onToggleChange($event)"
[value]="displayedTable()"
style="width: 100%">
<mat-button-toggle value="collaborator">
Kollaborierende
</mat-button-toggle>
<mat-button-toggle value="publication"
>Publikationen</mat-button-toggle
>
<mat-button-toggle value="institution">
Institutionen
</mat-button-toggle>
</mat-button-toggle-group>
<button
class="filter-button"
mat-stroked-button
type="button"
(click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
<div class="cards">
<app-person-network-graph
[collaborationNetwork]="collaborationNetwork()"
(handleNodeClick)="handleNodeClick($event)"
style="width: 50%" />
<app-query-param-input
style="width: 100%"
queryParamKey="search_term"
[label]="this.searchTermLabel()" />
<div class="right-card">
<form [formGroup]="filterForm">
<div>
<mat-button-toggle-group
class="toggle-group"
aria-label="Select view"
(change)="onToggleChange($event)"
formControlName="displayedTable"
style="margin-top: 20px; width: 100%">
<mat-button-toggle value="collaborators">
Kollaborierende
</mat-button-toggle>
<mat-button-toggle value="publications"
>Publikationen</mat-button-toggle
>
<mat-button-toggle value="institutions">
Institutionen
</mat-button-toggle>
</mat-button-toggle-group>
<button mat-stroked-button type="button" (click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
<mat-form-field style="width: 100%">
<mat-label>{{ this.searchTermLabel() }}</mat-label>
<input
matInput
#input
appearance="outline"
formControlName="searchTerm" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearch()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
</form>
<app-selected-filters [observers]="observers" />
<mat-card appearance="outlined">
<mat-card-content class="scroll-viewport-container">
@if (this.displayedTable() === 'collaborators') {
@if (this.displayedTable() === 'collaborator') {
<app-data-table
[columns]="collaboratorsColumns"
[data]="collaboratorsData"
[data]="collaboratorsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="collaboratorsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'publications') {
} @else if (this.displayedTable() === 'publication') {
<app-data-table
[columns]="publicationsColumns"
[data]="publicationsData"
[data]="publicationsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="publicationsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'institutions') {
} @else if (this.displayedTable() === 'institution') {
<app-data-table
[columns]="institutionsColumns"
[data]="institutionsData"
[data]="institutionsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="institutionsDetailRow"
[maxHeight]="'100%'" />
@@ -75,20 +92,25 @@
</mat-card-content>
</mat-card>
</div>
</div>
<div class="summary-container">
@for (summary of this.summaryCards(); track $index) {
<app-info-card
[icon]="summary.icon"
[value]="summary.value.toString()"
[description]="summary.description" />
}
<div class="cell full-width">
<div class="summary-container">
@for (summary of this.summaryCards(); track $index) {
<app-info-card
[icon]="summary.icon"
[value]="summary.value.toString()"
[description]="summary.description" />
}
</div>
</div>
</div>
</div>
}
<ng-template #collaboratorsActionTmp let-element>
<a mat-icon-button color="primary" [routerLink]="['/person', element.id]">
<a
mat-icon-button
color="primary"
[routerLink]="['/person', this.stripOpenAlexIdPrefix(element.id)]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@@ -99,15 +121,36 @@
<ng-template #collaboratorsDetailRow let-element>
<div class="detail-row">
<ul>
@for (work of element.works; track $index) {
<li>
<a class="work-link" [routerLink]="['/publication', work.id]">
{{ work.title }}
@if (element.works.length > 0) {
<span style="font-weight: bold">Publikationen:</span>
<ul>
@for (work of element.works; track $index) {
<a
class="link"
[routerLink]="[
'/publication',
this.stripOpenAlexIdPrefix(work.id),
]">
<li>{{ work.display_name }}</li>
</a>
</li>
}
</ul>
}
</ul>
}
@if (element.institutions.length > 0) {
<span style="font-weight: bold">Institutionen:</span>
<ul>
@for (institution of element.institutions; track $index) {
<a
class="link"
[routerLink]="[
'/institution',
this.stripOpenAlexIdPrefix(institution.id),
]">
<li>{{ institution.display_name }}</li>
</a>
}
</ul>
}
</div>
</ng-template>
@@ -115,26 +158,34 @@
<a
mat-icon-button
color="primary"
[routerLink]="['/publication', element.id]">
[routerLink]="['/publication', this.stripOpenAlexIdPrefix(element.id)]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
<ng-template #publicationsCollaborationFrequencyTmp let-element>
{{ element.collaborators.length }}
{{ element.authors.length }}
</ng-template>
<ng-template #publicationsDetailRow let-element>
<div class="detail-row">
<ul>
@for (collaborator of element.collaborators; track $index) {
<li>
<a class="person-link" [routerLink]="['/person', collaborator.id]">
{{ collaborator.name }}
</a>
</li>
}
</ul>
@if (element.authors.length > 0) {
<span style="font-weight: bold">Mitwirkende:</span>
<ul>
@for (collaborator of element.authors; track $index) {
<li>
<a
class="person-link"
[routerLink]="[
'/person',
this.stripOpenAlexIdPrefix(collaborator.id),
]">
{{ collaborator.display_name }}
</a>
</li>
}
</ul>
}
</div>
</ng-template>
@@ -142,25 +193,33 @@
<a
mat-icon-button
color="primary"
[routerLink]="['/institution', element.id]">
[routerLink]="['/institution', this.stripOpenAlexIdPrefix(element.id)]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
<ng-template #institutionsFrequencyTmp let-element>
{{ element.collaborators.length }}
{{ element.authors.length }}
</ng-template>
<ng-template #institutionsDetailRow let-element>
<div class="detail-row">
<ul>
@for (collaborator of element.collaborators; track $index) {
<li>
<a class="person-link" [routerLink]="['/person', collaborator.id]">
{{ collaborator.name }}
</a>
</li>
}
</ul>
@if (element.authors.length > 0) {
<span style="font-weight: bold">Mitwirkende:</span>
<ul>
@for (collaborator of element.authors; track $index) {
<li>
<a
class="link"
[routerLink]="[
'/person',
this.stripOpenAlexIdPrefix(collaborator.id),
]">
{{ collaborator.display_name }}
</a>
</li>
}
</ul>
}
</div></ng-template
>
@@ -1,50 +1,31 @@
.content {
display: flex;
flex-direction: column;
padding: 30px;
gap: 20px;
padding: 2rem;
gap: 1rem;
}
.description-container {
display: flex;
flex-direction: column;
}
.cards {
.toggle-group {
display: flex;
flex-direction: row;
gap: 20px;
max-height: 80vh;
gap: 1rem;
}
form > div {
display: flex;
flex-direction: row;
gap: 20px;
}
form > div > button,
form > div > mat-button-toggle-group {
margin-top: 20px;
margin-bottom: 20px;
border-radius: var(--sg-radius-sm);
.mat-button-toggle-group {
width: 100%;
height: 100%;
color: var(--sg-text);
}
.content > app-person-network-graph,
.right-card {
flex: 1 1 0;
text-transform: none;
}
.toggle-group .mat-button-toggle {
text-transform: none;
width: 100%;
}
.summary-container {
display: flex;
flex-direction: row;
gap: 20px;
gap: 1rem;
}
.summary-container app-info-card {
@@ -56,16 +37,44 @@ form > div > mat-button-toggle-group {
max-height: 50vh;
}
mat-card {
background-color: var(--sg-background);
}
.person-link,
.work-link {
.link {
color: var(--sg-primary);
text-decoration: none;
}
.person-link:hover,
.work-link:hover {
.link:hover {
text-decoration: underline;
}
.error {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
color: var(--sg-error);
min-height: 25vh;
}
.error-message {
color: var(--sg-error);
font-weight: bold;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.cell {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
gap: 1rem;
}
.full-width {
grid-column: 1 / -1;
}
@@ -1,8 +1,14 @@
import { toSignal } from '@angular/core/rxjs-interop';
import { MatGridListModule } from '@angular/material/grid-list';
import {
takeUntilDestroyed,
toObservable,
toSignal,
} from '@angular/core/rxjs-interop';
import {
Component,
computed,
DestroyRef,
effect,
input,
OnInit,
@@ -14,69 +20,73 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { provideEchartsCore } from 'ngx-echarts';
import * as echarts from 'echarts/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import {
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { CollaborationNetwork } from '../../api';
import { debounceTime } from 'rxjs';
import {
NodeCategory,
NodeClickEvent,
PersonNetworkGraphComponent,
} from '../person-network-graph/person-network-graph.component';
AuthorNode,
AuthorsV2Service,
CollaborationGraph,
CollaborationGraphStatus,
Edge,
Institution,
InstitutionNode,
InstitutionPageV2,
StartCollaborationGraphResponse,
Topic,
TopicPageV2,
WorkNode,
} from '../../api';
import { MatSelectModule } from '@angular/material/select';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { PersonNetworkFilterDialogComponent } from '../person-network-filter-dialog/person-network-filter-dialog.component';
import {
PersonNetworkFilterDialogComponent,
PersonNetworkFilterDialogData,
} from '../person-network-filter-dialog/person-network-filter-dialog.component';
import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component';
import {
GenericColumn,
DataTableComponent,
} from '../../shared/ui/data-table/data-table.component';
import {
CollaborationGraphComponent,
NodeCategory,
NodeClickEvent,
} from '../collaboration-graph/collaboration-graph.component';
import { form } from '@angular/forms/signals';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import {
FilterObserver,
SelectedFiltersComponent,
} from '../../shared/ui/selected-filters/selected-filters.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
import { from, interval, startWith, switchMap, takeWhile, tap } from 'rxjs';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
type CWork = {
id: string;
title: string;
type DetailedWorkNode = WorkNode & {
authors: AuthorNode[];
};
type CCollaborator = {
id: string;
name: string;
category: string;
works: CWork[];
type DetailedAuthorNode = AuthorNode & {
works: WorkNode[];
institutions: InstitutionNode[];
};
type PCollaborator = {
id: string;
name: string;
category: string;
type DetailedInstitutionNode = InstitutionNode & {
authors: AuthorNode[];
};
type PWork = {
id: string;
title: string;
collaborators: PCollaborator[];
};
type ICollaborator = {
id: string;
name: string;
};
type IInstitution = {
id: string;
name: string;
collaborators: ICollaborator[];
};
interface FilterData {
startYear: number;
endYear: number;
minContributors: number;
maxContributors: number;
topics: Topic[];
institutions: Institution[];
}
@Component({
selector: 'app-person-network',
@@ -91,22 +101,143 @@ type IInstitution = {
RouterModule,
ReactiveFormsModule,
FormsModule,
PersonNetworkGraphComponent,
MatSelectModule,
MatExpansionModule,
MatDialogModule,
AppInfoCardComponent,
DataTableComponent,
CollaborationGraphComponent,
SelectedFiltersComponent,
QueryParamInputComponent,
LoadingComponent,
MatGridListModule,
],
templateUrl: './person-network.component.html',
styleUrl: './person-network.component.scss',
providers: [provideEchartsCore({ echarts })],
providers: [],
})
export class PersonNetworkComponent implements OnInit {
collaborationNetwork = input.required<CollaborationNetwork>();
startCollaborationGraphResponse =
input.required<StartCollaborationGraphResponse>();
collaboratorsColumns: GenericColumn<CCollaborator>[] = [];
collaboratorsData: CCollaborator[] = [];
collaborationGraph = signal<CollaborationGraph | undefined>(undefined);
collaborationGraphStatus = signal<CollaborationGraphStatus>(
CollaborationGraphStatus.Pending,
);
collaborationGraphError = signal<string | undefined>(undefined);
selectedTopics = input.required<TopicPageV2>();
selectedInstitutions = input.required<InstitutionPageV2>();
filterModel = signal<FilterData>({
startYear: 2020,
endYear: new Date().getFullYear(),
minContributors: 2,
maxContributors: 10,
topics: [],
institutions: [],
});
displayedTable = computed(
() => this.queryParamMap().get('table') || 'collaborator',
);
filterForm2 = form(this.filterModel);
isPending = computed(
() => this.collaborationGraphStatus() === CollaborationGraphStatus.Pending,
);
isCompleted = computed(
() =>
this.collaborationGraphStatus() === CollaborationGraphStatus.Completed,
);
isFailed = computed(
() => this.collaborationGraphStatus() === CollaborationGraphStatus.Failed,
);
observers: FilterObserver[] = [
{
id: 'searchTerm',
queryParamKey: 'search_term',
icon: 'search',
},
{
id: 'yearFrom',
queryParamKey: collaborationGraphQueryParamKeys.yearFrom,
icon: 'calendar_today',
valueFormatter: (value: string) => {
return value ? `Ab ${value}` : null;
},
},
{
id: 'yearTo',
queryParamKey: collaborationGraphQueryParamKeys.yearTo,
icon: 'calendar_today',
valueFormatter: (value: string) => {
return value ? `Bis ${value}` : null;
},
},
{
id: 'minContributors',
queryParamKey: collaborationGraphQueryParamKeys.minCollaborators,
icon: 'person',
valueFormatter: (value: string) => {
return value ? `Mindestens ${value} Autoren` : null;
},
},
{
id: 'maxContributors',
queryParamKey: collaborationGraphQueryParamKeys.maxCollaborators,
icon: 'group',
valueFormatter: (value: string) => {
return value ? `Höchstens ${value} Autoren` : null;
},
},
{
id: 'topics',
queryParamKey: collaborationGraphQueryParamKeys.topicId,
icon: 'label',
valueFormatter: (value: string) => {
const topic = this.selectedTopics().elements?.find(
(topic) => topic.id === value,
);
return topic ? topic.display_name : value;
},
removable: true,
},
{
id: 'institutions',
queryParamKey: collaborationGraphQueryParamKeys.institutionId,
icon: 'apartment',
valueFormatter: (value: string) => {
const institution = this.selectedInstitutions().elements?.find(
(inst) => inst.id === value,
);
return institution ? institution.display_name : value;
},
removable: true,
},
];
collaboratorsColumns: GenericColumn<DetailedAuthorNode>[] = [];
collaboratorsData = computed<DetailedAuthorNode[]>(
() =>
this.collaborationGraph()?.authors?.map((author) => ({
...author,
works: (this.collaborationGraph()?.works ?? []).filter((work) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) => edge.source === author.id && edge.target === work.id,
),
),
institutions: (this.collaborationGraph()?.institutions ?? []).filter(
(institution) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) =>
edge.source === author.id && edge.target === institution.id,
),
),
})) ?? [],
);
collaboratorsActionTmp = viewChild.required<TemplateRef<any>>(
'collaboratorsActionTmp',
);
@@ -117,8 +248,18 @@ export class PersonNetworkComponent implements OnInit {
'collaboratorsDetailRow',
);
publicationsColumns: GenericColumn<PWork>[] = [];
publicationsData: PWork[] = [];
publicationsColumns: GenericColumn<DetailedWorkNode>[] = [];
publicationsData = computed(
() =>
this.collaborationGraph()?.works?.map((work) => ({
...work,
authors: (this.collaborationGraph()?.authors ?? []).filter((author) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) => edge.source === author.id && edge.target === work.id,
),
),
})) ?? [],
);
publicationsActionTmp = viewChild.required<TemplateRef<any>>(
'publicationsActionTmp',
);
@@ -129,8 +270,19 @@ export class PersonNetworkComponent implements OnInit {
'publicationsDetailRow',
);
institutionsColumns: GenericColumn<IInstitution>[] = [];
institutionsData: IInstitution[] = [];
institutionsColumns: GenericColumn<DetailedInstitutionNode>[] = [];
institutionsData = computed(
() =>
this.collaborationGraph()?.institutions?.map((institution) => ({
...institution,
authors: (this.collaborationGraph()?.authors ?? []).filter((author) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) =>
edge.source === author.id && edge.target === institution.id,
),
),
})) ?? [],
);
institutionsActionTmp = viewChild.required<TemplateRef<any>>(
'institutionsActionTmp',
);
@@ -141,36 +293,21 @@ export class PersonNetworkComponent implements OnInit {
'institutionsDetailRow',
);
filterForm = new FormGroup({
searchTerm: new FormControl(''),
filterBy: new FormControl<'works' | 'authors'>('works'),
displayedTable: new FormControl('collaborators'),
startYear: new FormControl(2000),
endYear: new FormControl(2025),
topics: new FormControl([]),
minContributors: new FormControl(2),
maxContributors: new FormControl(10),
minCollaborations: new FormControl(1),
maxCollaborations: new FormControl(100),
institutions: new FormControl([]),
});
persons = signal(0);
institutions = signal(0);
publications = signal(0);
connections = signal(0);
persons = computed(() => this.collaborationGraph()?.authors?.length ?? 0);
institutions = computed(
() => this.collaborationGraph()?.institutions?.length ?? 0,
);
publications = computed(() => this.collaborationGraph()?.works?.length ?? 0);
connections = computed(() => this.collaborationGraph()?.edges?.length ?? 0);
searchTermLabel = computed(() => {
const displayedTable = this.displayedTable();
switch (displayedTable) {
case 'collaborators':
case 'collaborator':
return 'Suche Kollaborierende nach Name';
case 'publications':
case 'publication':
return 'Suche Publikationen nach Titel';
case 'institutions':
case 'institution':
return 'Suche Institutionen nach Name';
default:
return 'Suchbegriff';
@@ -178,15 +315,69 @@ export class PersonNetworkComponent implements OnInit {
});
private readonly categoryTableMap: Record<NodeCategory, string> = {
author: 'collaborators',
collaborator: 'collaborators',
work: 'publications',
institution: 'institutions',
author: 'collaborator',
collaborator: 'collaborator',
work: 'publication',
institution: 'institution',
};
latestNodeId = signal<string | null>(null);
rebuildCollaborationGraph(
collaborationGraph: CollaborationGraph,
): CollaborationGraph {
const rebuiltGraph = this.rebuildEdges(collaborationGraph);
return rebuiltGraph;
}
rebuildEdges(collaborationGraph: CollaborationGraph): CollaborationGraph {
const edges = collaborationGraph.edges ?? [];
const authors = collaborationGraph.authors ?? [];
const authorInstitutionEdges = authors.flatMap((author) =>
(author.institution_ids ?? []).map((institutionId) => ({
source: author.id,
target: institutionId,
weight: 1,
})),
);
const works = collaborationGraph.works ?? [];
const workAuthorEdges = works.flatMap((work) =>
(work.author_ids ?? []).map((authorId) => ({
source: authorId,
target: work.id,
weight: 1,
})),
);
return {
...collaborationGraph,
edges: this.reduceEdges([
...edges,
...authorInstitutionEdges,
...workAuthorEdges,
]),
};
}
reduceEdges(edges: Edge[]): Edge[] {
const reducedEdgesMap = new Map<string, Edge>();
for (const edge of edges) {
const key = `${edge.source}-${edge.target}`;
if (reducedEdgesMap.has(key)) {
reducedEdgesMap.get(key)!.weight += edge.weight;
} else {
reducedEdgesMap.set(key, edge);
}
}
return Array.from(reducedEdgesMap.values());
}
handleNodeClick = ({ id, name, category }: NodeClickEvent): void => {
console.log('Node clicked:', { id, name, category });
if (this.latestNodeId() === id) {
this.clearSearch();
return;
@@ -197,15 +388,25 @@ export class PersonNetworkComponent implements OnInit {
return;
}
this.filterForm.patchValue({
displayedTable: this.categoryTableMap[category],
searchTerm: name,
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
search_term: name,
table: this.categoryTableMap[category] || 'collaborator',
},
queryParamsHandling: 'merge',
});
};
clearSearch() {
this.latestNodeId.set(null);
this.filterForm.patchValue({ searchTerm: '' });
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
search_term: null,
},
queryParamsHandling: 'merge',
});
}
readonly summaryCards = computed(() => [
@@ -231,126 +432,137 @@ export class PersonNetworkComponent implements OnInit {
},
]);
readonly formValue = toSignal(this.filterForm.valueChanges);
readonly debouncedFormValue = toSignal(
this.filterForm.valueChanges.pipe(debounceTime(300)),
);
displayedTable = computed(() => {
return this.formValue()?.displayedTable;
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly searchTerm = computed(() => {
return this.debouncedFormValue()?.searchTerm || '';
});
searchTerm = computed(() => this.queryParamMap().get('search_term') || '');
readonly activatedRouteData = toSignal(this.activatedRoute.data);
private readonly POLL_INTERVAL_MS = 3000;
constructor(
private readonly activatedRoute: ActivatedRoute,
private readonly router: Router,
private readonly dialog: MatDialog,
private readonly authorsService: AuthorsV2Service,
private readonly destroyRef: DestroyRef,
) {
toObservable(this.startCollaborationGraphResponse)
.pipe(
switchMap((startResponse) =>
interval(this.POLL_INTERVAL_MS).pipe(
startWith(0),
switchMap(() =>
from(
this.authorsService.getCollaborationGraphStatus(
startResponse.graph_id,
),
),
),
tap((statusResponse) => {
this.collaborationGraphStatus.set(statusResponse.status);
this.collaborationGraphError.set(
statusResponse.error_message ?? undefined,
);
if (
statusResponse.result &&
statusResponse.status === CollaborationGraphStatus.Completed
) {
this.collaborationGraph.set(
this.rebuildCollaborationGraph(statusResponse.result),
);
}
}),
takeWhile((statusResponse) => {
return statusResponse.status === CollaborationGraphStatus.Pending;
}, true),
),
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe();
effect(() => {
this.collaboratorsData = this.buildCollaboratorsDataSource(
this.collaborationNetwork(),
);
this.publicationsData = this.buildWorksDataSource(
this.collaborationNetwork(),
);
this.institutionsData = this.buildInstitutionsDataSource(
this.collaborationNetwork(),
);
this.calculateSummary(this.collaborationNetwork());
const currentParams = this.activatedRoute.snapshot.queryParams;
this.filterForm.setValue({
searchTerm: currentParams['search_term'] || '',
filterBy: currentParams['filter_by'] || 'works',
displayedTable: currentParams['table'] || 'collaborators',
startYear:
Number(currentParams['start_year']) ||
this.collaborationNetwork().filter_information.min_possible_year,
endYear:
Number(currentParams['end_year']) ||
this.collaborationNetwork().filter_information.max_possible_year,
topics: currentParams['topics']
? currentParams['topics'].split(',')
: [],
minContributors: Number(currentParams['min_contributors']) || 2,
maxContributors: Number(currentParams['max_contributors']) || 10,
minCollaborations: Number(currentParams['min_collaborations']) || 1,
maxCollaborations: Number(currentParams['max_collaborations']) || 100,
institutions: currentParams['institutions']
? currentParams['institutions'].split(',')
: [],
const filters = this.filterModel();
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
[collaborationGraphQueryParamKeys.yearFrom]:
filters.startYear || null,
[collaborationGraphQueryParamKeys.yearTo]: filters.endYear || null,
[collaborationGraphQueryParamKeys.minCollaborators]:
filters.minContributors || null,
[collaborationGraphQueryParamKeys.maxCollaborators]:
filters.maxContributors || null,
[collaborationGraphQueryParamKeys.topicId]:
filters.topics.length > 0
? filters.topics.map((topic) => topic.id)
: null,
[collaborationGraphQueryParamKeys.institutionId]:
filters.institutions.length > 0
? filters.institutions.map((inst) => inst.id)
: null,
},
queryParamsHandling: 'merge',
});
});
}
openFilterDialog() {
console.log('Form value when opening dialog:', this.filterForm.value);
const data: PersonNetworkFilterDialogData = {
selectedTopics: this.selectedTopics().elements ?? [],
selectedInstitutions: this.selectedInstitutions().elements ?? [],
startYear: this.filterForm2.startYear().value(),
endYear: this.filterForm2.endYear().value(),
minContributors: this.filterForm2.minContributors().value(),
maxContributors: this.filterForm2.maxContributors().value(),
};
const dialogRef = this.dialog.open(PersonNetworkFilterDialogComponent, {
data: {
collaborationNetwork: this.collaborationNetwork(),
filterBy: this.filterForm.get('filterBy')?.value || 'works',
startYear: this.filterForm.get('startYear')?.value,
endYear: this.filterForm.get('endYear')?.value,
topics: this.filterForm.get('topics')?.value,
minContributors: this.filterForm.get('minContributors')!.value,
maxContributors: this.filterForm.get('maxContributors')?.value,
minCollaborations: this.filterForm.get('minCollaborations')?.value,
maxCollaborations: this.filterForm.get('maxCollaborations')?.value,
institutions: this.filterForm.get('institutions')?.value,
},
data: data,
});
dialogRef.afterClosed().subscribe((result) => {
console.log('Dialog closed with result:', result);
console.log(result.filterBy);
console.log(result.worksFilterProperties);
console.log(result.authorsFilterProperties);
if (result) {
this.filterForm.patchValue({
filterBy: result.filterBy,
startYear: result.worksFilterProperties.startYear,
endYear: result.worksFilterProperties.endYear,
topics: result.worksFilterProperties.topics,
minContributors: result.worksFilterProperties.minContributors,
maxContributors: result.worksFilterProperties.maxContributors,
minCollaborations: result.authorsFilterProperties.minCollaborations,
maxCollaborations: result.authorsFilterProperties.maxCollaborations,
institutions: result.authorsFilterProperties.institutions,
this.filterModel.set({
startYear: result.startYear,
endYear: result.endYear,
minContributors: result.minContributors,
maxContributors: result.maxContributors,
topics: result.topics,
institutions: result.institutions,
});
}
});
}
calculateSummary(collaborationNetwork: CollaborationNetwork) {
this.persons.set(collaborationNetwork.author_nodes.length);
this.institutions.set(collaborationNetwork.institution_nodes.length);
this.publications.set(collaborationNetwork.work_nodes.length);
this.connections.set(collaborationNetwork.collaboration_edges.length);
}
ngOnInit(): void {
const queryParamMap = this.queryParamMap();
this.filterModel.set({
startYear:
Number(queryParamMap.get(collaborationGraphQueryParamKeys.yearFrom)) ||
2020,
endYear:
Number(queryParamMap.get(collaborationGraphQueryParamKeys.yearTo)) ||
new Date().getFullYear(),
minContributors:
Number(
queryParamMap.get(collaborationGraphQueryParamKeys.minCollaborators),
) || 2,
maxContributors:
Number(
queryParamMap.get(collaborationGraphQueryParamKeys.maxCollaborators),
) || 10,
topics: this.selectedTopics().elements || [],
institutions: this.selectedInstitutions().elements || [],
});
this.collaboratorsColumns = [
{
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'name',
accessorKey: 'display_name',
},
{
id: 'works',
@@ -370,7 +582,7 @@ export class PersonNetworkComponent implements OnInit {
id: 'title',
header: 'Titel',
type: 'accessor',
accessorKey: 'title',
accessorKey: 'display_name',
},
{
id: 'collaborators',
@@ -390,7 +602,7 @@ export class PersonNetworkComponent implements OnInit {
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'name',
accessorKey: 'display_name',
},
{
id: 'collaborators',
@@ -405,38 +617,6 @@ export class PersonNetworkComponent implements OnInit {
cellTemplate: this.institutionsActionTmp(),
},
];
this.filterForm.valueChanges.pipe(debounceTime(300)).subscribe((value) => {
const queryParams = {
table: value.displayedTable ?? 'collaborators',
search_term: value.searchTerm ?? '',
filter_by: value.filterBy ?? 'works',
start_year: value.startYear ?? '',
end_year: value.endYear ?? '',
min_contributors: value.minContributors ?? 2,
max_contributors: value.maxContributors ?? 10,
min_collaborations: value.minCollaborations ?? 1,
max_collaborations: value.maxCollaborations ?? 100,
institutions: value.institutions?.join(',') ?? '',
topics: value.topics?.join(',') ?? '',
};
const currentQueryParams = this.activatedRoute.snapshot.queryParams;
const hasChanged = Object.entries(queryParams).some(([key, value]) => {
return String(currentQueryParams[key] ?? '') !== String(value ?? '');
});
if (!hasChanged) {
return;
}
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams,
replaceUrl: true,
});
});
}
onToggleChange(event: any) {
@@ -444,153 +624,19 @@ export class PersonNetworkComponent implements OnInit {
if (!value) {
return;
}
this.filterForm.get('displayedTable')?.setValue(value);
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
table: value,
},
queryParamsHandling: 'merge',
});
}
buildCollaboratorsDataSource(
collaborationNetwork: CollaborationNetwork,
): CCollaborator[] {
// key: collaborator id, value: set of work ids
const worksByCollaborator: Record<string, Set<string>> = {};
// key: work id, value: work
const works: Record<string, CWork> = {};
const allWorks: Record<string, CWork> = collaborationNetwork.work_nodes
.map((node) => ({
id: node.raw_id,
title: node.display_name,
}))
.reduce(
(acc, work) => {
acc[work.id] = work;
return acc;
},
{} as Record<string, CWork>,
);
const allAuthors: Record<string, CCollaborator> =
collaborationNetwork.author_nodes
.map((node) => ({
id: node.raw_id,
name: node.display_name,
category: node.category,
works: [],
}))
.reduce(
(acc, author) => {
acc[author.id] = author;
return acc;
},
{} as Record<string, CCollaborator>,
);
collaborationNetwork.collaboration_edges.forEach((edge) => {
if (
edge.raw_source_id.toUpperCase().startsWith('A') &&
edge.raw_target_id.toUpperCase().startsWith('W')
) {
allAuthors[edge.raw_source_id]?.works.push(
allWorks[edge.raw_target_id],
);
}
});
Object.values(allAuthors).forEach((author) => {
author.works.sort((a, b) => a.title.localeCompare(b.title));
});
return Object.values(allAuthors).filter(
(author) =>
author.works.length > 0 &&
author.id !== collaborationNetwork.raw_person_id,
);
}
buildWorksDataSource(collaborationNetwork: CollaborationNetwork): PWork[] {
const allWorks: Record<string, PWork> = collaborationNetwork.work_nodes
.map((node) => ({
id: node.raw_id,
title: node.display_name,
collaborators: [],
}))
.reduce(
(acc, work) => {
acc[work.id] = work;
return acc;
},
{} as Record<string, PWork>,
);
const allAuthors: Record<string, PCollaborator> =
collaborationNetwork.author_nodes
.map((node) => ({
id: node.raw_id,
name: node.display_name,
category:
node.raw_id === collaborationNetwork.raw_person_id
? 'author'
: 'collaborator',
}))
.reduce(
(acc, person) => {
acc[person.id] = person;
return acc;
},
{} as Record<string, PCollaborator>,
);
collaborationNetwork.collaboration_edges.forEach((edge) => {
if (
edge.raw_source_id.toUpperCase().startsWith('A') &&
edge.raw_target_id.toUpperCase().startsWith('W')
) {
allWorks[edge.raw_target_id]?.collaborators.push(
allAuthors[edge.raw_source_id],
);
}
});
Object.values(allWorks).forEach((work) => {
work.collaborators.sort((a, b) => a.name.localeCompare(b.name));
});
return Object.values(allWorks).filter(
(work) => work.collaborators.length > 0,
);
}
buildInstitutionsDataSource(
collaborationNetwork: CollaborationNetwork,
): IInstitution[] {
const institutionsMap: Record<string, IInstitution> = {};
for (const node of collaborationNetwork.institution_nodes) {
institutionsMap[node.raw_id] = {
id: node.raw_id,
name: node.display_name,
collaborators: [],
};
stripOpenAlexIdPrefix(id: string): string {
if (id.startsWith('https://openalex.org/')) {
return id.substring(21);
}
for (const edge of collaborationNetwork.collaboration_edges) {
if (edge.raw_target_id in institutionsMap) {
const institution = institutionsMap[edge.raw_target_id];
institution.collaborators.push({
id: edge.raw_source_id,
name:
collaborationNetwork.author_nodes.find(
(node) => node.raw_id === edge.raw_source_id,
)?.display_name || 'Unbekannt',
});
}
}
for (const institution of Object.values(institutionsMap)) {
institution.collaborators.sort((a, b) =>
a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }),
);
}
return Object.values(institutionsMap);
return id;
}
}
@@ -1,13 +1,4 @@
<div class="page">
<div>
<h6>Nachrichten</h6>
<p>Aktuelle Nachrichten zu dieser Person.</p>
</div>
<ng-template #cardTmp let-article>
<app-news-card [article]="article" />
</ng-template>
<app-card-search
[page]="page()"
[loading]="loading"
@@ -17,3 +8,7 @@
sortingDirectionLabel="Sortierung"
searchLabel="Nachrichten durchsuchen" />
</div>
<ng-template #cardTmp let-article>
<app-news-card [article]="article" />
</ng-template>
@@ -1,5 +1,4 @@
.page {
padding: 28px 32px 42px;
max-width: 100%;
margin: 0 auto;
}
@@ -1,7 +1,6 @@
.person-overview {
width: 100%;
display: block;
padding: 1.5rem 1.5rem 0;
box-sizing: border-box;
}
@@ -13,25 +13,31 @@
<div class="patents-content">
<div class="patents-list">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="filter_alt"></mat-icon>
<mat-select
[value]="activeFilter"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select
(selectionChange)="setFilter($event.value)">
<mat-select-trigger>Filter nach Quelle</mat-select-trigger>
<mat-option value="all">Alle</mat-option>
<mat-option value="EPO">EPO</mat-option>
<mat-option value="USPTO">USPTO</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortMode"
(change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="date">Datum</mat-option>
<mat-option value="title">Titel</mat-option>
</mat-select>
</mat-form-field>
</div>
<table>
@@ -142,15 +148,15 @@
<p class="overview-title">Patentübersicht</p>
<p class="overview-subtitle">Patente mit passendem Erfindername.</p>
<div class="overview-stats">
<div class="overview-stat">
<div class="overview-stat overview-stat--total">
<span class="overview-value">{{ patents.length }}</span>
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat">
<div class="overview-stat overview-stat--epo">
<span class="overview-value">{{ getEpoCount() }}</span>
<span class="overview-label">EPO</span>
</div>
<div class="overview-stat">
<div class="overview-stat overview-stat--uspto">
<span class="overview-value">{{ getUsptoCount() }}</span>
<span class="overview-label">USPTO</span>
</div>
@@ -10,29 +10,9 @@
gap: 16px;
}
.sort-control {
display: inline-flex;
align-items: center;
gap: 6px;
.patents-toolbar-field {
width: fit-content;
padding: 10px 14px;
border-radius: 20px;
background: #f2f2f2;
color: #333;
font-size: 14px;
span {
color: #555;
}
select {
border: 0;
background: transparent;
color: #111827;
font: inherit;
cursor: pointer;
outline: none;
}
min-width: 180px;
}
.patents-content {
@@ -210,6 +190,27 @@
color: #888;
margin-top: 4px;
}
&--total {
.overview-value,
.overview-label {
color: #7255d9;
}
}
&--epo {
.overview-value,
.overview-label {
color: #24834f;
}
}
&--uspto {
.overview-value,
.overview-label {
color: #0b63ce;
}
}
}
.overview-hint {
@@ -3,6 +3,9 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { finalize, of, switchMap } from 'rxjs';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { PatentEntry } from '../../api/model/patentEntry';
import { PersonPatentsResolved } from '../../resolvers/person-patents.resolver';
import {
@@ -16,7 +19,13 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO';
@Component({
selector: 'app-person-patents',
imports: [CommonModule, LoadingComponent],
imports: [
CommonModule,
LoadingComponent,
MatFormFieldModule,
MatSelectModule,
MatIconModule,
],
templateUrl: './person-patents.component.html',
styleUrl: './person-patents.component.scss',
})
@@ -1,36 +1,19 @@
<div class="person-projects">
<div class="description-container">
<h5 style="font-weight: bold">Projekte</h5>
<p>Übersicht der durchgeführten Projekte.</p>
</div>
<mat-card appearance="outlined">
<mat-card-content>
<mat-tab-group
[selectedIndex]="selectedTabIndex()"
(selectedIndexChange)="onTabChange($event)">
<mat-tab label="DFG">
<app-project-filters
[selectedInstitutionsPage]="selectedDfgInstitutionsPage()"
[selectedAuthorsPage]="selectedDfgAuthorsPage()"
[selectedTopicsPage]="selectedTopicsPage()"
[showFundingStartFilter]="true"
[showTopicFilter]="true"
[showFundingEndFilter]="true"
[showAuthorFilter]="true"
[showInstitutionFilter]="true" />
<app-dfg-project-table
[page]="dfgProjectPage()"
[authorFilterEnabled]="true"
[topicFilterEnabled]="true"
[institutionFilterEnabled]="true" />
</mat-tab>
<mat-tab label="EU">
<!-- <app-project-filters
[selectedInstitutionsPage]="selectedEuInstitutionsPage()"
[selectedAuthorsPage]="selectedEuAuthorsPage()" /> -->
<app-eu-project-table [page]="personCordisEuProjectPage()" />
</mat-tab>
</mat-tab-group>
</mat-card-content>
</mat-card>
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
</div>
@@ -1,12 +1,3 @@
.person-projects {
padding: 2rem;
}
.description-container {
display: flex;
flex-direction: column;
}
mat-card,
mat-paginator {
background-color: var(--sg-background);
@@ -1,69 +1,35 @@
import { Component, computed, input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { DfgInstitutionSummaryPage } from '../../api/model/dfgInstitutionSummaryPage';
import {
CordisEuProjectPage,
DfgProjectPage,
AuthorPage,
InstitutionPageV2,
TopicPageV2,
DfgPersonSummaryPage,
} from '../../api';
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { ProjectFilterComponent } from '../../shared/ui/project-filters/project-filters.component';
import { DfgProjectTableComponent } from '../../shared/ui/dfg-project-table/dfg-project-table.component';
import { EuProjectTableComponent } from '../../shared/ui/eu-project-table/eu-project-table.component';
import { projectQueryParamKeys } from '../../resolvers/dfg-projects.resolver';
import { euProjectQueryParamKeys } from '../../resolvers/person-cordis-eu-project-page.resolver';
const PROJECT_TAB_QUERY_PARAM_KEY = 'project_type';
@Component({
selector: 'app-person-projects',
standalone: true,
imports: [
MatCardModule,
MatTabsModule,
ProjectFilterComponent,
DfgProjectTableComponent,
EuProjectTableComponent,
RouterOutlet,
RouterLink,
RouterLinkActive,
],
templateUrl: './person-projects.component.html',
styleUrl: './person-projects.component.scss',
})
export class PersonProjectsComponent {
dfgProjectPage = input.required<DfgProjectPage>();
personCordisEuProjectPage = input.required<CordisEuProjectPage>();
selectedDfgInstitutionsPage = input.required<DfgInstitutionSummaryPage>();
selectedDfgAuthorsPage = input.required<DfgPersonSummaryPage>();
selectedEuInstitutionsPage = input.required<InstitutionPageV2>();
selectedEuAuthorsPage = input.required<AuthorPage>();
selectedTopicsPage = input.required<TopicPageV2>();
readonly dfgQueryParamKeys = projectQueryParamKeys;
readonly euQueryParamKeys = euProjectQueryParamKeys;
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {}
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
selectedTabIndex = computed(() => {
const type = this.queryParamMap().get(PROJECT_TAB_QUERY_PARAM_KEY);
return type === 'eu' ? 1 : 0;
});
onTabChange(index: number): void {
const type = index === 1 ? 'eu' : 'dfg';
this.router.navigate([], {
queryParams: { [PROJECT_TAB_QUERY_PARAM_KEY]: type },
queryParamsHandling: 'merge',
});
}
readonly childRoutes = [
{
path: 'dfg',
label: 'DFG-Projekte',
},
{
path: 'eu',
label: 'EU-Projekte',
},
{
path: 'bund',
label: 'Bund-Projekte',
},
];
}
@@ -1,33 +1,27 @@
<div class="page">
<div>
<h6>Publikationen</h6>
<p>Übersicht der wissenschaftlichen Veröffentlichungen.</p>
</div>
@if (canViewClassificationChart()) {
<mat-accordion multi>
<mat-expansion-panel class="mat-elevation-z1">
<mat-expansion-panel-header>
<mat-panel-title>Forschungszwecke</mat-panel-title>
</mat-expansion-panel-header>
<app-primary-category-year-aggregation-chart
[page]="primaryCategoryYearAggregationPage()" />
</mat-expansion-panel>
@if (canViewClassificationChart()) {
<mat-accordion multi>
<mat-expansion-panel class="mat-elevation-z1">
<mat-expansion-panel-header>
<mat-panel-title>Forschungszwecke</mat-panel-title>
</mat-expansion-panel-header>
<app-primary-category-year-aggregation-chart
[page]="primaryCategoryYearAggregationPage()" />
</mat-expansion-panel>
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>Publikationsliste</mat-panel-title>
<mat-panel-description
>{{ total() >= 10000 ? 'mehr als' : '' }}
{{ total() }} Publikationen</mat-panel-description
>
</mat-expansion-panel-header>
<ng-container *ngTemplateOutlet="filterTableAndPaginator" />
</mat-expansion-panel>
</mat-accordion>
} @else {
<ng-container *ngTemplateOutlet="filterTableAndPaginator" />
}
</div>
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>Publikationsliste</mat-panel-title>
<mat-panel-description
>{{ total() >= 10000 ? 'mehr als' : '' }}
{{ total() }} Publikationen</mat-panel-description
>
</mat-expansion-panel-header>
<ng-container *ngTemplateOutlet="filterTableAndPaginator" />
</mat-expansion-panel>
</mat-accordion>
} @else {
<ng-container *ngTemplateOutlet="filterTableAndPaginator" />
}
<ng-template #filterTableAndPaginator>
<app-publication-filter
@@ -37,7 +31,8 @@
<app-publication-table
[page]="authorWorkPage()"
[institutionFilterEnabled]="true" />
[institutionFilterEnabled]="true"
[rawOaAuthorId]="rawOaAuthorId()" />
<app-query-param-paginator
[total]="total()"
@@ -1,7 +1,3 @@
.page {
padding: 2rem;
}
mat-expansion-panel {
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core';
import { Component, computed, inject, input } from '@angular/core';
import {
WorkPageV2,
@@ -12,6 +12,7 @@ import { PublicationTableComponent } from '../../shared/ui/publication-table/pub
import { PublicationFilterComponent } from '../../shared/ui/publication-filters/publication-filters.component';
import { PrimaryCategoryYearAggregationChartComponent } from '../../shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-person-publications',
@@ -27,6 +28,8 @@ import { CommonModule } from '@angular/common';
styleUrl: './person-publications.component.scss',
})
export class PersonPublicationsComponent {
private readonly activatedRoute = inject(ActivatedRoute);
authorWorkPage = input.required<WorkPageV2>();
total = computed(() => this.authorWorkPage().total ?? 0);
elements = computed(() => this.authorWorkPage().elements ?? []);
@@ -41,4 +44,9 @@ export class PersonPublicationsComponent {
const page = this.primaryCategoryYearAggregationPage();
return (page?.elements?.length ?? 0) > 0;
});
rawOaAuthorId = computed(() => {
const params = this.activatedRoute.parent?.snapshot.paramMap;
return params?.get('id') ?? undefined;
});
}
@@ -149,7 +149,7 @@
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
<nav class="person-tabs" mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link.path) {
@for (link of links(); track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
@@ -163,20 +163,25 @@
}
</nav>
} @else {
<div class="loading">
<mat-progress-spinner diameter="40">
<span>Person wird geladen...</span>
</mat-progress-spinner>
</div>
<app-loading
text="Person wird geladen..."
icon="person"
[size]="150"
[diameter]="150"></app-loading>
}
<mat-tab-nav-panel #tabPanel class="person-panel">
@if (isNetworkResolving()) {
<app-loading
text="Das Netzwerk wird gebaut, kleinen Moment..."
icon="graph_3"
[size]="150"
[diameter]="150" />
} @else {
<router-outlet></router-outlet>
@let activeLink = this.activeLink();
@if (activeLink) {
<div class="description-container">
@if (activeLink.label) {
<h5>{{ activeLink.label }}</h5>
}
@if (activeLink.description) {
<span class="description">{{ activeLink.description }}</span>
}
</div>
}
<div class="content">
<router-outlet></router-outlet>
</div>
</mat-tab-nav-panel>
@@ -372,3 +372,24 @@
opacity: 0.7;
}
}
.description-container {
margin: 3rem 3rem 2rem 3rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
h5 {
margin: 0;
}
}
.description {
color: var(--sg-text-muted);
font-size: 14px;
line-height: 1.5;
}
.content {
margin: 1rem 4rem;
}
+100 -41
View File
@@ -6,15 +6,11 @@ import {
takeUntilDestroyed,
} from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { MatTabsModule } from '@angular/material/tabs';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
ActivatedRoute,
ResolveEnd,
ResolveStart,
Router,
RouterEvent,
RouterModule,
RouterOutlet,
} from '@angular/router';
@@ -26,6 +22,15 @@ 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 { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
type PersonLink = {
label: string;
description?: string;
path: string;
queryParams?: Record<string, any>;
disabled: boolean;
};
@Component({
selector: 'app-person',
@@ -37,7 +42,6 @@ import { BookmarkService } from '../../shared/services/bookmark.service';
PersonInterestingComponent,
RouterOutlet,
RouterModule,
MatProgressSpinner,
LoadingComponent,
],
templateUrl: './person.component.html',
@@ -61,7 +65,9 @@ export class PersonComponent {
readonly params = toSignal(this.activatedRoute.paramMap);
readonly routerEvents = toSignal(this.router.events);
readonly currentUrl = computed(() => this.router.url);
readonly currentUrl = toSignal(
this.router.events.pipe(switchMap(() => of(this.router.url))),
);
// derive authorID directly from route
private readonly authorId = toSignal(
@@ -71,32 +77,6 @@ export class PersonComponent {
),
);
readonly isNetworkResolving = computed(() => {
const event = this.routerEvents();
if (
!(event instanceof RouterEvent) ||
!this.isResolverEvent(event) ||
!this.isNetworkRouterEvent(event)
) {
return false;
}
if (event instanceof ResolveStart) {
return true;
}
return false;
});
isResolverEvent(event: RouterEvent): boolean {
return event instanceof ResolveStart || event instanceof ResolveEnd;
}
isNetworkRouterEvent(event: RouterEvent): boolean {
return event.url.startsWith(`/person/${this.authorId()}/network`);
}
readonly isPersonLoading = signal(false);
readonly isBioLoading = signal(false);
@@ -118,6 +98,19 @@ export class PersonComponent {
{ initialValue: null },
);
readonly companyConnectionsAvailable = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
if (!resolved) {
return of(false);
}
return resolved.companyConnectionsAvailable$;
}),
),
{ initialValue: false },
);
toggleBookmark(): void {
const person = this.person();
if (!person) return;
@@ -250,10 +243,16 @@ export class PersonComponent {
{ initialValue: [] },
);
links = [
{ label: 'Übersicht', path: 'overview', disabled: false },
readonly links = computed<PersonLink[]>(() => [
{
label: 'Übersicht',
description: 'Übersicht über die Person',
path: 'overview',
disabled: false,
},
{
label: 'Projekte',
description: 'Übersicht der durchgeführten Projekte der Person',
path: 'projects',
queryParams: {
page: 0,
@@ -264,13 +263,73 @@ export class PersonComponent {
},
disabled: false,
},
{ label: 'Publikationen', path: 'publications', disabled: false },
{ label: 'Netzwerk', path: 'network', disabled: false },
{ label: 'Unternehmen', path: 'company-connections', disabled: false },
{ label: 'Förderungen', path: 'funding', disabled: false },
{ label: 'Nachrichten', path: 'news', disabled: false },
{ label: 'Patente', path: 'patents', disabled: false },
];
{
label: 'Publikationen',
description: 'Übersicht der Publikationen der Person',
path: 'publications',
disabled: false,
},
{
label: 'Netzwerk',
description: 'Kooperationsnetzwerk der Person',
path: 'network',
disabled: false,
queryParams: {
[collaborationGraphQueryParamKeys.minCollaborators]: '2',
[collaborationGraphQueryParamKeys.maxCollaborators]: '10',
[collaborationGraphQueryParamKeys.yearFrom]: '1900',
[collaborationGraphQueryParamKeys.yearTo]: new Date().getFullYear(),
},
},
...(this.companyConnectionsAvailable()
? [
{
label: 'Unternehmen',
description: 'Unternehmen, mit denen die Person verbunden ist',
path: 'company-connections',
disabled: false,
},
]
: []),
{
label: 'Förderungen',
description: 'Übersicht der Förderungen der Person',
path: 'funding',
disabled: false,
},
{
label: 'Nachrichten',
description: 'Nachrichten über die Person',
path: 'news',
disabled: false,
},
{
label: 'Patente',
description: 'Patente der Person',
path: 'patents',
disabled: false,
},
]);
readonly activeLink = computed<PersonLink | null>(() => {
const currentUrl = this.currentUrl();
if (!currentUrl) {
return null;
}
for (const link of this.links()) {
const linkUrl = this.router
.createUrlTree([link.path], {
relativeTo: this.activatedRoute,
})
.toString();
if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) {
return link;
}
}
return null;
});
onInterestingTagClick(selection: {
id: string;
@@ -0,0 +1,204 @@
<section class="preprocessing-page">
<header class="page-header">
<div>
<h1>Jobs</h1>
<p>
Tasks zur Aufbereitung und Indizierung der Daten manuell ausführen oder
automatisch planen.
</p>
</div>
</header>
<mat-card appearance="outlined" class="container-card">
<mat-card-content class="container-card-content">
<div class="container-info">
<span
class="container-state-dot"
[class.container-state-dot--running]="
containerStatus().state === 'running'
"
[class.container-state-dot--stopped]="
containerStatus().state === 'stopped'
"
[class.container-state-dot--restarting]="
containerStatus().state === 'restarting'
">
</span>
<div>
<strong>{{ containerStatus().name }}</strong>
<div class="container-meta">
<span>{{ containerStatus().image }}</span>
<span class="container-digest">{{
containerStatus().imageDigest
}}</span>
@switch (containerStatus().state) {
@case ('running') {
<span
>Läuft{{
containerStatus().uptime
? ' · seit ' + containerStatus().uptime
: ''
}}</span
>
}
@case ('stopped') {
<span>Gestoppt</span>
}
@case ('restarting') {
<span>Wird neu gestartet …</span>
}
}
@if (containerStatus().updateAvailable) {
<span class="update-badge">
<mat-icon>upgrade</mat-icon>
Neue Version verfügbar
</span>
}
</div>
</div>
</div>
<div class="container-actions">
@if (containerStatus().updateAvailable) {
<button
mat-flat-button
color="primary"
type="button"
[disabled]="containerBusy()"
(click)="updateImage()">
<mat-icon>upgrade</mat-icon>
Image aktualisieren
</button>
}
@if (containerStatus().state === 'running') {
<button
mat-stroked-button
type="button"
[disabled]="containerBusy()"
(click)="restartContainer()">
<mat-icon>restart_alt</mat-icon>
Neu starten
</button>
<button
mat-stroked-button
color="warn"
type="button"
[disabled]="containerBusy()"
(click)="stopContainer()">
<mat-icon>stop</mat-icon>
Stoppen
</button>
} @else {
<button
mat-flat-button
color="primary"
type="button"
[disabled]="containerBusy()"
(click)="startContainer()">
<mat-icon>play_arrow</mat-icon>
Starten
</button>
}
</div>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined">
<mat-card-content>
<app-data-table [columns]="taskColumns" [data]="tasks()" />
</mat-card-content>
</mat-card>
</section>
<ng-template #taskNameTmp let-row>
<div class="task-name-cell">
<strong>{{ row.name }}</strong>
<span class="task-description">{{ row.description }}</span>
<code class="task-index">{{ row.targetIndex }}</code>
</div>
</ng-template>
<ng-template #taskScheduleTmp let-row>
<div class="task-schedule-cell">
<span>{{ formatSchedule(row.schedule) }}</span>
<button
type="button"
role="switch"
class="schedule-toggle"
[class.schedule-toggle--on]="row.enabled"
[attr.aria-checked]="row.enabled"
[attr.aria-label]="row.name + ': automatische Ausführung'"
(click)="toggleEnabled(row, !row.enabled)">
<span class="schedule-toggle__track">
<span class="schedule-toggle__thumb"></span>
</span>
<span class="schedule-toggle__label">{{
row.enabled ? 'Aktiv' : 'Inaktiv'
}}</span>
</button>
</div>
</ng-template>
<ng-template #taskStatusTmp let-row>
@switch (row.status) {
@case ('running') {
<span class="task-status task-status--running">
<mat-progress-spinner
diameter="14"
mode="indeterminate"></mat-progress-spinner>
Läuft
</span>
}
@case ('success') {
<span class="task-status task-status--success">
<mat-icon>check_circle</mat-icon>
Erfolgreich
</span>
}
@case ('failed') {
<span class="task-status task-status--failed">
<mat-icon>error</mat-icon>
Fehlgeschlagen
</span>
}
@default {
<span class="task-status task-status--idle">
<mat-icon>schedule</mat-icon>
Bereit
</span>
}
}
</ng-template>
<ng-template #taskLastRunTmp let-row>
@if (row.lastRun) {
<div class="last-run-cell">
<span>{{ row.lastRun.startedAt | date: 'dd.MM.yyyy HH:mm' }}</span>
<span class="last-run-message">{{ row.lastRun.message }}</span>
</div>
} @else {
<span class="last-run-empty">Noch nicht ausgeführt</span>
}
</ng-template>
<ng-template #taskActionsTmp let-row>
<div class="row-actions">
<button
mat-icon-button
type="button"
aria-label="Jetzt ausführen"
matTooltip="Jetzt ausführen"
[disabled]="row.status === 'running'"
(click)="runNow(row)">
<mat-icon>play_arrow</mat-icon>
</button>
<button
mat-icon-button
type="button"
aria-label="Zeitplan bearbeiten"
matTooltip="Zeitplan bearbeiten"
(click)="openScheduleDialog(row)">
<mat-icon>edit_calendar</mat-icon>
</button>
</div>
</ng-template>
@@ -47,9 +47,9 @@
</ng-template>
<ng-template #journalTemplate let-pub>
@if (pub.journalNumber) {
<span class="journal-chip" [matTooltip]="pub.journalNumber">
{{ pub.journalNumber }}
@if (pub.journalNumber ?? pub.journalTitle) {
<span class="journal-chip" [matTooltip]="pub.journalTitle">
{{ pub.journalNumber || pub.journalTitle }}
</span>
} @else {
<span class="empty-value">—</span>
@@ -71,10 +71,10 @@ export class PublicationsTableComponent {
cellTemplate: this.authorsTemplate(),
},
{
id: 'journalNumber',
id: 'journalTitle',
header: 'Zeitschrift',
type: 'accessor',
accessorKey: 'journalNumber',
accessorKey: 'journalTitle',
cellTemplate: this.journalTemplate(),
},
{
@@ -115,7 +115,7 @@ export class PublicationsTableComponent {
return;
}
const doi = pub.doi?.trim() ?? 'unknown';
const doi = (pub.doi ?? pub.qaProcessedDoi)?.trim() ?? 'unknown';
// Encode DOI and navigate
const encodedDoi = encodeURIComponent(doi);
@@ -41,7 +41,7 @@
<app-topic-chip
[label]="category | workPrimaryCategory"
[color]="primaryCategoryChipColor()"
[disabled]="true" />
[disabled]="false" />
}
</div>
</section>
@@ -39,10 +39,14 @@ export class UniTrendChartComponent {
const xAxisData = years.map(String);
// Resolve the active topic to compare one at a time to prevent line overlaps
const topics = Object.keys(trendData.series[0].topic_data || {});
const availableKeys = Object.keys(trendData.series[0].topic_data || {});
const displayNameKeys = availableKeys.filter(
(k) => !/^T\d+$/i.test(k) && !k.startsWith('http'),
);
const topics = displayNameKeys.length > 0 ? displayNameKeys : availableKeys;
const active = this.activeTopic();
const selectedTopic =
active && topics.includes(active)
active && (availableKeys.includes(active) || topics.includes(active))
? active
: topics.length > 0
? topics[0]
@@ -2,59 +2,102 @@
<!-- Strategy Selection Toggles Bar -->
<div class="strategy-toggles-bar">
<button
mat-button
[class.active]="selectedSearchType() === 'publications'"
(click)="setSearchType('publications')">
(click)="setSearchType('publications')"
matTooltip="Zeigt Publikationstrends nach Einrichtung, Land oder Region">
<mat-icon>library_books</mat-icon> Publikationen
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'authors'"
(click)="setSearchType('authors')">
(click)="setSearchType('authors')"
matTooltip="Zeigt Publikationstrends einzelner Autoren">
<mat-icon>people</mat-icon> Autoren
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'patents'"
(click)="setSearchType('patents')">
(click)="setSearchType('patents')"
matTooltip="Zeigt Patentanmeldungstrends">
<mat-icon>assignment</mat-icon> Patente
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'projects'"
(click)="setSearchType('projects')">
(click)="setSearchType('projects')"
matTooltip="Zeigt Drittmittelförderungstrends">
<mat-icon>business_center</mat-icon> Projekte
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'news'"
[disabled]="!isUde()"
[title]="
[matTooltip]="
!isUde()
? 'News-Trends sind nur für die Universität Duisburg-Essen verfügbar'
: ''
: 'Zeigt Pressemitteilungstrends der UDE'
"
(click)="setSearchType('news')">
<mat-icon>campaign</mat-icon> News
</button>
<button
mat-button
[class.active]="selectedSearchType() === 'all'"
(click)="setSearchType('all')">
(click)="setSearchType('all')"
matTooltip="Zeigt den aggregierten Themenlebenszyklus über alle Fachbereiche">
<mat-icon>dashboard</mat-icon> Themenlebenszyklus (All)
</button>
</div>
<div class="trend-layout">
<!-- Linkes Sidebar-Panel: Steuerung -->
<aside class="trend-sidebar">
<!-- Zeitraum-Auswahl -->
<app-year-range-slider
[minYear]="2000"
[maxYear]="2026"
[(startYear)]="startYear"
[(endYear)]="endYear"
(startYearChange)="updateUrlParams()"
(endYearChange)="updateUrlParams()">
</app-year-range-slider>
<!-- Combined Header Controls Bar: Slider and Scale Toggles on the Same Height -->
<div class="trend-top-controls-bar">
<div class="control-section slider-section">
<app-year-range-slider
[minYear]="2000"
[maxYear]="2026"
[(startYear)]="startYear"
[(endYear)]="endYear"
(startYearChange)="updateUrlParams()"
(endYearChange)="updateUrlParams()">
</app-year-range-slider>
</div>
<!-- Länder/Kontinente vergleichen -->
<div class="control-section scale-section">
<span class="toggle-label">Visualisierungsskala:</span>
<mat-button-toggle-group
[value]="chartMode()"
(change)="onChartModeChange($event)"
aria-label="Visualisierungsskala">
<mat-button-toggle
value="normalized"
matTooltip="Normiert das Publikationsvolumen auf [0,1], um die Form von Wachstumstrends zu vergleichen.">
<mat-icon>trending_down</mat-icon>
<span class="toggle-text">Normierte Skala</span>
</mat-button-toggle>
<mat-button-toggle
value="total"
matTooltip="Zeigt die absolute Anzahl der Publikationen.">
<mat-icon>bar_chart</mat-icon>
<span class="toggle-text">Gesamtvolumen</span>
</mat-button-toggle>
<mat-button-toggle
value="cumulative"
matTooltip="Zeigt das normierte kumulierte Publikationswachstum (S-Kurve).">
<mat-icon>trending_up</mat-icon>
<span class="toggle-text">S-Kurve (Normiert)</span>
</mat-button-toggle>
</mat-button-toggle-group>
</div>
</div>
<!-- Combined Child Component Selectors Row (all filter logic at top before diagrams) -->
<div class="comparison-selectors-row">
<!-- Countries / Regions Selector -->
@if (activeConfig().showLocationSelector) {
<app-location-selector
class="selector-item"
[comparisonCountries]="comparisonCountries()"
[comparisonRegions]="comparisonRegions()"
[locationQuery]="locationQuery()"
@@ -70,9 +113,10 @@
</app-location-selector>
}
<!-- Top-Autoren einer Einrichtung hinzufügen (Authors Tab Sidebar Placement) -->
<!-- Top-Autoren einer Einrichtung hinzufügen -->
@if (activeConfig().showAuthorSelector) {
<app-author-institution-selector
class="selector-item"
[searchQuery]="authorInstSearchQuery()"
[searchResults]="authorInstSearchResults()"
(addInstitutionAuthors)="
@@ -81,60 +125,87 @@
(searchChange)="onAuthorInstSearchChange($event)">
</app-author-institution-selector>
}
</aside>
<!-- Rechtes Haupt-Panel: Toggles & Diagramm -->
<main class="trend-main">
@if (isTrendLoading() && !rawTrendResponse()) {
<app-loading
text="Trenddaten werden initialisiert..."
icon="trending_up"
[size]="200"
[diameter]="200"></app-loading>
} @else if (rawTrendResponse()) {
<div class="trend-toggles-bar">
<span class="toggle-label">Visualisierungsskala:</span>
<div class="toggle-buttons">
<button
[class.active]="chartMode() === 'normalized'"
(click)="setChartMode('normalized')"
title="Normiert das Publikationsvolumen auf [0,1], um die Form von Wachstumstrends zu vergleichen.">
<mat-icon>trending_down</mat-icon> Normierte Skala
</button>
<button
[class.active]="chartMode() === 'total'"
(click)="setChartMode('total')"
title="Zeigt die absolute Anzahl der Publikationen.">
<mat-icon>bar_chart</mat-icon> Gesamtvolumen
</button>
<button
[class.active]="chartMode() === 'cumulative'"
(click)="setChartMode('cumulative')"
title="Zeigt das normierte kumulierte Publikationswachstum (S-Kurve).">
<mat-icon>trending_up</mat-icon> S-Kurve (Normiert)
</button>
</div>
</div>
<!-- Unified Institution Search, Compare, & Recommendations -->
@if (activeConfig().showInstitutionSelector) {
<app-institution-selector
class="selector-item selector-item--main"
[activeTab]="selectedSearchType()"
[comparisonInstitutions]="comparisonInstitutions()"
[primaryInstitution]="primaryInstitution()"
[primaryInstitutionName]="primaryInstitutionName()"
[topSuggestions]="topSuggestions()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="searchQuery()"
[searchResults]="searchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addInstitution)="addInstitution($event.id, $event.name)"
(removeInstitution)="removeInstitution($event)"
(searchChange)="onSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-institution-selector>
}
<!-- Reusable Author Selection UI -->
@if (activeConfig().showAuthorSelector) {
<app-author-selector
class="selector-item selector-item--main"
[activeTab]="selectedSearchType()"
[comparisonAuthors]="comparisonAuthors()"
[topSuggestions]="recommendedAuthors()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="authorSearchQuery()"
[searchResults]="authorSearchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addAuthor)="addAuthor($event.id, $event.name)"
(removeAuthor)="removeAuthor($event)"
(searchChange)="onAuthorSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-author-selector>
}
</div>
<!-- Main Full-Width Content Area -->
<main class="trend-main-fullwidth">
@if (rawTrendResponse()) {
<!-- Chart Holder Card (100% Full Width) -->
<div class="chart-holder-card">
@if (isTrendLoading()) {
@if (isTrendLoading() || isPageResolving()) {
<div class="loader-overlay">
<div class="spinner"></div>
<p>Trenddaten werden abgerufen...</p>
<mat-spinner diameter="40"></mat-spinner>
<p>Daten werden geladen...</p>
</div>
}
@if (
selectedTrendTopics().length > 1 && selectedSearchType() !== 'news'
) {
@if (selectedTrendTopics().length > 0) {
<div class="chart-topic-tabs">
@for (topic of selectedTrendTopics(); track topic) {
<app-topic-chip
[label]="topic"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
@if (selectedSearchType() === 'news') {
<app-topic-chip
[label]="topic"
[active]="isVisible('news_topic_' + topic)"
[color]="getTopicColor(topic)"
[disabled]="false"
[matTooltip]="topic"
(chipClick)="toggleVisibility('news_topic_' + topic)">
</app-topic-chip>
} @else if (selectedTrendTopics().length > 1) {
<app-topic-chip
[label]="topic"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
[matTooltip]="topic"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
}
}
</div>
}
@@ -149,27 +220,39 @@
<!-- Pie Charts Row -->
@if (
selectedPieEntity() &&
selectedSearchType() !== 'news' &&
(selectedPieEntity() || selectedSearchType() === 'news') &&
selectedSearchType() !== 'all'
) {
<div class="pie-charts-row" style="margin-bottom: 24px">
<app-uni-pie-chart
[data]="trendResponse()"
[loading]="isTrendLoading()"
[entityId]="selectedPieEntity()!.id"
[entityName]="selectedPieEntity()!.name"
[startYear]="startYear()"
[endYear]="endYear()"
[getTopicColor]="boundGetTopicColor">
</app-uni-pie-chart>
<div class="pie-charts-row">
@if (selectedSearchType() === 'news') {
<app-uni-pie-chart
[titleText]="'Verteilung der ausgewählten Themen'"
[pieData]="newsSelectedTopicsPieData()"
[loading]="isTrendLoading()"
[startYear]="startYear()"
[endYear]="endYear()"
[getTopicColor]="boundGetTopicColor">
</app-uni-pie-chart>
} @else {
<app-uni-pie-chart
[data]="trendResponse()"
[loading]="isTrendLoading()"
[entityId]="selectedPieEntity()!.id"
[entityName]="selectedPieEntity()!.name"
[startYear]="startYear()"
[endYear]="endYear()"
[getTopicColor]="boundGetTopicColor">
</app-uni-pie-chart>
}
<app-uni-pie-chart
[titleText]="
'Top ' +
topTopicsSize() +
' Themen (Gesamt): ' +
selectedPieEntity()!.name
(selectedSearchType() === 'news'
? 'Alle News'
: (selectedPieEntity()?.name ?? ''))
"
[pieData]="topTopicsData()"
[loading]="isTopTopicsLoading() || isTrendLoading()"
@@ -181,48 +264,42 @@
</div>
}
<!-- Unified Institution Search, Compare, & Recommendations -->
@if (activeConfig().showInstitutionSelector) {
<app-institution-selector
[activeTab]="selectedSearchType()"
[comparisonInstitutions]="comparisonInstitutions()"
[primaryInstitution]="primaryInstitution()"
[primaryInstitutionName]="primaryInstitutionName()"
[topSuggestions]="topSuggestions()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="searchQuery()"
[searchResults]="searchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addInstitution)="addInstitution($event.id, $event.name)"
(removeInstitution)="removeInstitution($event)"
(searchChange)="onSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-institution-selector>
}
<!-- Reusable Author Selection UI (Main Panel below chart) -->
@if (activeConfig().showAuthorSelector) {
<app-author-selector
[activeTab]="selectedSearchType()"
[comparisonAuthors]="comparisonAuthors()"
[topSuggestions]="recommendedAuthors()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[searchQuery]="authorSearchQuery()"
[searchResults]="authorSearchResults()"
[getEntityColor]="boundGetEntityColor"
[isVisible]="boundIsVisible"
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
(addAuthor)="addAuthor($event.id, $event.name)"
(removeAuthor)="removeAuthor($event)"
(searchChange)="onAuthorSearchChange($event)"
(toggleVisibility)="toggleVisibility($event)"
(selectPie)="onSelectPieEntity($event)">
</app-author-selector>
<!-- Topic Treemap (Hierarchie-Tree) for Fuzzy Search -->
@if (isFuzzy() && activeTreemapData()) {
<section class="treemap-section">
<div class="chart-holder-card">
<h3
style="
margin-bottom: 16px;
font-weight: 700;
font-size: 1.1rem;
color: #101a3d;
display: flex;
align-items: center;
gap: 8px;
">
<mat-icon style="color: #6366f1">account_tree</mat-icon>
Themen-Hierarchie &amp; Verteilung (Treemap)
@if (selectedPieEntity()?.name || primaryInstitutionName()) {
<span
style="
font-weight: 500;
font-size: 0.95rem;
color: #64708f;
">
·
{{ selectedPieEntity()?.name || primaryInstitutionName() }}
</span>
}
</h3>
<app-topic-treemap
[data]="activeTreemapData()!"
[selectedNodeId]="selectedTopicTreemapNode()"
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)"
(topicSelect)="onTopicTreemapTopicSelect($event)">
</app-topic-treemap>
</div>
</section>
}
} @else {
<div class="no-data-fallback">
@@ -1,185 +1,14 @@
.trend-layout {
display: grid;
grid-template-columns: 300px minmax(0, 1fr);
gap: 1.5rem;
margin-top: 1.5rem;
font-family: 'Inter', sans-serif;
@media (max-width: 1024px) {
grid-template-columns: 1fr;
}
}
.trend-sidebar {
.trend-layout-wrapper {
display: flex;
flex-direction: column;
gap: 1rem;
}
.control-card {
background: white;
border-radius: 10px;
padding: 1.25rem;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
h3 {
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
color: #6b7280;
margin: 0 0 0.75rem 0;
letter-spacing: 0.05em;
}
}
.checkbox-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: #374151;
cursor: pointer;
input[type='checkbox'] {
accent-color: #3b82f6;
width: 15px;
height: 15px;
cursor: pointer;
}
}
.empty-list-info {
font-size: 0.75rem;
color: #9ca3af;
text-align: center;
padding: 8px 0;
border: 1px dashed #e5e7eb;
border-radius: 5px;
}
.trend-main {
display: flex;
flex-direction: column;
gap: 1rem;
}
.trend-toggles-bar {
display: flex;
justify-content: space-between;
align-items: center;
background: white;
border-radius: 10px;
padding: 0.6rem 1rem;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
.toggle-label {
font-size: 0.8125rem;
font-weight: 500;
color: #4b5563;
}
}
.toggle-buttons {
display: flex;
background: #f3f4f6;
border-radius: 6px;
padding: 2px;
button {
padding: 0.4rem 0.8rem;
border: none;
background: none;
font-size: 0.75rem;
font-weight: 500;
color: #4b5563;
border-radius: 5px;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
&:hover:not(.active) {
color: #111827;
background: rgba(255, 255, 255, 0.5);
}
&.active {
background: white;
color: #3b82f6;
font-weight: 600;
}
}
}
.chart-holder-card {
position: relative;
background: white;
border-radius: 10px;
border: 1px solid #e5e7eb;
overflow: hidden;
min-height: 400px;
}
.chart-topic-tabs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 1rem;
background: #f9fafb;
border-bottom: 1px solid #e5e7eb;
}
.loader-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.8);
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.spinner {
width: 32px;
height: 32px;
border: 3px solid rgba(59, 130, 246, 0.1);
border-radius: 50%;
border-top-color: #3b82f6;
animation: spin 0.8s linear infinite;
margin-bottom: 8px;
}
p {
font-size: 0.8125rem;
color: #4b5563;
margin: 0;
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
width: 100%;
box-sizing: border-box;
font-family:
'Inter',
system-ui,
-apple-system,
sans-serif;
}
.strategy-toggles-bar {
@@ -190,14 +19,13 @@
border-radius: 12px;
padding: 6px;
border: 1px solid #e2e8f0;
margin-bottom: 0.5rem;
button {
padding: 0.5rem 1rem;
padding: 0.45rem 0.9rem;
border: none;
background: none;
font-size: 0.75rem;
font-weight: 600;
font-size: 0.8125rem;
font-weight: 500;
color: #64748b;
border-radius: 8px;
cursor: pointer;
@@ -207,39 +35,190 @@
transition: all 0.2s ease;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
font-size: 18px;
width: 18px;
height: 18px;
}
&:hover:not(.active):not([disabled]) {
color: #0f172a;
background: #f1f5f9;
}
&[disabled] {
opacity: 0.4;
opacity: 0.45;
cursor: not-allowed;
}
&.active {
background: white;
color: #3b82f6;
color: #2563eb;
font-weight: 600;
box-shadow:
0 4px 6px -1px rgba(0, 0, 0, 0.05),
0 2px 4px -1px rgba(0, 0, 0, 0.03);
0 2px 4px rgba(0, 0, 0, 0.05),
0 1px 2px rgba(0, 0, 0, 0.03);
}
}
}
.trend-layout {
display: flex;
flex-direction: column;
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
}
/* Combined Top Header Control Bar */
.trend-top-controls-bar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1.5rem;
background: white;
border-radius: 12px;
padding: 0.75rem 1.25rem;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
width: 100%;
box-sizing: border-box;
.slider-section {
flex: 1;
min-width: 280px;
}
.scale-section {
display: flex;
align-items: center;
gap: 0.75rem;
flex-shrink: 0;
.toggle-label {
font-size: 0.8125rem;
font-weight: 600;
color: #4b5563;
white-space: nowrap;
}
mat-button-toggle-group {
border: 1px solid #e2e8f0;
border-radius: 8px;
overflow: hidden;
background: #f8fafc;
box-shadow: none;
mat-button-toggle {
font-size: 0.75rem;
font-weight: 500;
color: #475569;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
margin-right: 4px;
vertical-align: middle;
}
.toggle-text {
white-space: nowrap;
}
}
.mat-button-toggle-checked {
background-color: white !important;
color: #2563eb !important;
font-weight: 600;
}
}
}
@media (max-width: 900px) {
flex-direction: column;
align-items: stretch;
gap: 1rem;
}
}
.trend-main-fullwidth {
display: flex;
flex-direction: column;
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
}
.chart-holder-card {
position: relative;
background: white;
border-radius: 12px;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
overflow: hidden;
min-height: 450px;
width: 100%;
box-sizing: border-box;
}
.chart-topic-tabs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1.25rem;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
}
.loader-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.85);
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.75rem;
p {
font-size: 0.875rem;
font-weight: 500;
color: #3b82f6;
margin: 0;
}
}
.pie-charts-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 1.25rem;
width: 100%;
box-sizing: border-box;
}
.comparison-selectors-row {
display: grid;
grid-template-columns: 3fr 7fr;
gap: 1.25rem;
align-items: stretch;
width: 100%;
box-sizing: border-box;
@media (max-width: 768px) {
@media (max-width: 900px) {
grid-template-columns: 1fr;
}
.selector-item {
width: 100%;
height: 100%;
min-width: 0;
box-sizing: border-box;
}
}
.no-data-fallback {
@@ -249,14 +228,21 @@
justify-content: center;
min-height: 400px;
background: white;
border-radius: 10px;
border-radius: 12px;
border: 1px solid #e5e7eb;
color: #9ca3af;
gap: 0.5rem;
gap: 0.75rem;
mat-icon {
font-size: 48px;
width: 48px;
height: 48px;
font-size: 56px;
width: 56px;
height: 56px;
}
p {
font-size: 0.9375rem;
font-weight: 500;
color: #6b7280;
margin: 0;
}
}
@@ -11,16 +11,26 @@ import {
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import {
ActivatedRoute,
Router,
ResolveStart,
ResolveEnd,
} from '@angular/router';
import { forkJoin } from 'rxjs';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import {
MatButtonToggleModule,
MatButtonToggleChange,
} from '@angular/material/button-toggle';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatTooltipModule } from '@angular/material/tooltip';
import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component';
import { UniPieChartComponent } from '../uni-pie-chart/uni-pie-chart.component';
import {
@@ -46,6 +56,16 @@ import { AuthorSelectorComponent } from '../../../shared/ui/author-selector/auth
import { AuthorInstitutionSelectorComponent } from '../../../shared/ui/author-institution-selector/author-institution-selector.component';
import { SearchResultsStateService } from '../../keywords-search/search-results/search-results-state.service';
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
import { TopicTreemapComponent } from '../../../shared/ui/topic-treemap/topic-treemap.component';
import {
TopicTreemapData,
TopicTreemapField,
TopicTreemapSubfield,
TopicTreemapTopic,
TopicTreemapValue,
TopicTreemapTopicSelect,
} from '../../../shared/ui/topic-treemap/topic-treemap.models';
import { TopicsService } from '../../../api/api/topics.service';
export interface CompareItem {
id: string;
@@ -115,8 +135,10 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
UniPieChartComponent,
MatCheckboxModule,
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatProgressSpinnerModule,
MatTooltipModule,
TopicChipComponent,
YearRangeSliderComponent,
LocationSelectorComponent,
@@ -124,6 +146,7 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
AuthorSelectorComponent,
AuthorInstitutionSelectorComponent,
LoadingComponent,
TopicTreemapComponent,
],
templateUrl: './uni-trend-parent.component.html',
styleUrl: './uni-trend-parent.component.scss',
@@ -131,6 +154,7 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
})
export class UniTrendParentComponent implements OnInit {
private readonly apiService = inject(UniversityRankingsService);
private readonly topicsService = inject(TopicsService);
private readonly institutionsApiService = inject(InstitutionsService);
private readonly personsApiService = inject(PersonsService);
private readonly organizationService = inject(OrganizationService, {
@@ -208,6 +232,7 @@ export class UniTrendParentComponent implements OnInit {
readonly fetchedFuzzy = signal<boolean | null>(null);
// Results & Loading signals
readonly isPageResolving = signal<boolean>(false);
readonly rawTrendResponse = signal<TrendResponse | null>(null);
readonly isTrendLoading = signal<boolean>(false);
readonly topSuggestions = signal<TopInstitutionItem[]>([]);
@@ -217,6 +242,12 @@ export class UniTrendParentComponent implements OnInit {
readonly isTopTopicsLoading = signal<boolean>(false);
readonly topTopicsError = signal<boolean>(false);
// Topic Treemap signals
readonly isFuzzy = computed(() => this.state?.fuzzySearch() ?? true);
readonly topicTreemap = signal<TopicTreemapData | null>(null);
readonly isTreemapLoading = signal<boolean>(false);
readonly selectedTopicTreemapNode = signal<string | undefined>(undefined);
getMappedTopic(topicOrKeyword: string): string {
const kws = this.keywords();
const topics = this.state?.topicsList() ?? kws;
@@ -263,6 +294,220 @@ export class UniTrendParentComponent implements OnInit {
readonly boundGetTopicColor = this.getTopicColor.bind(this);
readonly newsSelectedTopicsPieData = computed(() => {
const data = this.trendResponse();
if (!data || !data.series || this.selectedSearchType() !== 'news') {
return null;
}
const startYr = this.startYear();
const endYr = this.endYear();
return data.series.map((s) => {
const topicName = s.entity_name;
const yearlyItems =
s.topic_data[topicName] || Object.values(s.topic_data)[0] || [];
const totalRaw = yearlyItems
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((sum, item) => sum + (item.raw || 0), 0);
return {
name: topicName,
value: totalRaw,
};
});
});
cleanEntityId(id: string | null | undefined): string {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
}
// Dynamic Treemap Data for Selected Entity (Institution or Author or Region/Country)
readonly activeTreemapData = computed<TopicTreemapData | null>(() => {
const data = this.trendResponse();
const searchType = this.selectedSearchType();
const isFuzzy = this.isFuzzy();
if (!data || !data.series || !isFuzzy) return null;
const startYr = this.startYear();
const endYr = this.endYear();
const activePie = this.selectedPieEntity();
let targetEntityId: string | undefined = activePie?.id || undefined;
let targetEntityName = activePie?.name || 'Ausgewählte Entität';
if (!targetEntityId) {
if (searchType === 'authors') {
const firstAuthor = this.comparisonAuthors()[0];
targetEntityId = firstAuthor?.id || undefined;
targetEntityName = firstAuthor?.name || 'Autor';
} else {
targetEntityId = this.primaryInstitution() || undefined;
targetEntityName = this.primaryInstitutionName();
}
}
const cleanTargetId = targetEntityId
? this.cleanEntityId(targetEntityId)
: '';
let matchingSeries: TrendSeries[] = [];
if (searchType === 'news') {
matchingSeries = data.series;
} else {
matchingSeries = data.series.filter(
(s) => this.cleanEntityId(s.entity_id) === cleanTargetId,
);
if (matchingSeries.length === 0 && data.series.length > 0) {
matchingSeries = data.series;
}
}
if (matchingSeries.length === 0) return null;
const keywordEntries = this.state?.selectedKeywordEntries() ?? [];
const fieldsMap = new Map<
string,
{
id: string;
name: string;
subfieldsMap: Map<
string,
{
id: string;
name: string;
topicsMap: Map<
string,
{
id: string;
name: string;
total: number;
values: TopicTreemapValue[];
}
>;
}
>;
}
>();
matchingSeries.forEach((s) => {
Object.entries(s.topic_data || {}).forEach(
([topicName, yearlyDataList]) => {
const totalCount = yearlyDataList
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((sum, item) => sum + (item.raw || 0), 0);
if (totalCount <= 0) return;
const mappedName = this.getMappedTopic(topicName);
const targetLower = topicName.toLowerCase().trim();
const mappedLower = mappedName.toLowerCase().trim();
const match = keywordEntries.find(
(e) =>
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
mappedLower ||
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
targetLower ||
e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower,
);
const fieldName =
match?.topic_mapping?.topic?.field?.display_name ||
'Information & Communication Technology';
const fieldId = match?.topic_mapping?.topic?.field?.id
? String(match.topic_mapping.topic.field.id)
: 'field_ict';
const subfieldName =
match?.topic_mapping?.topic?.subfield?.display_name || fieldName;
const subfieldId = match?.topic_mapping?.topic?.subfield?.id
? String(match.topic_mapping.topic.subfield.id)
: `subfield_${fieldId}`;
const topicId = match?.topic_mapping?.topic?.id
? String(match.topic_mapping.topic.id)
: topicName;
if (!fieldsMap.has(fieldId)) {
fieldsMap.set(fieldId, {
id: fieldId,
name: fieldName,
subfieldsMap: new Map(),
});
}
const fieldEntry = fieldsMap.get(fieldId)!;
if (!fieldEntry.subfieldsMap.has(subfieldId)) {
fieldEntry.subfieldsMap.set(subfieldId, {
id: subfieldId,
name: subfieldName,
topicsMap: new Map(),
});
}
const subfieldEntry = fieldEntry.subfieldsMap.get(subfieldId)!;
if (!subfieldEntry.topicsMap.has(topicId)) {
const yearlyValues: TopicTreemapValue[] = yearlyDataList
.filter((y) => y.year >= startYr && y.year <= endYr)
.map((y) => ({
year: y.year,
count: y.raw || 0,
share: y.normalized || 0,
}));
subfieldEntry.topicsMap.set(topicId, {
id: topicId,
name: topicName,
total: totalCount,
values: yearlyValues,
});
}
},
);
});
const years = Array.from(
{ length: endYr - startYr + 1 },
(_, i) => startYr + i,
);
const fields: TopicTreemapField[] = Array.from(fieldsMap.values()).map(
(f) => {
const subfields: TopicTreemapSubfield[] = Array.from(
f.subfieldsMap.values(),
).map((sf) => {
const topics: TopicTreemapTopic[] = Array.from(sf.topicsMap.values());
const sfTotal = topics.reduce((sum, t) => sum + t.total, 0);
return {
id: sf.id,
name: sf.name,
total: sfTotal,
values: [],
topics,
};
});
const fTotal = subfields.reduce((sum, sf) => sum + sf.total, 0);
return {
id: f.id,
name: f.name,
total: fTotal,
values: [],
subfields,
};
},
);
if (fields.length === 0) return null;
return {
institution_id: cleanTargetId,
organization_name: targetEntityName,
years,
fields,
};
});
// Autocomplete UI state
readonly searchQuery = signal<string>('');
readonly searchResults = signal<AutocompleteResponseResultsInner[]>([]);
@@ -280,6 +525,41 @@ export class UniTrendParentComponent implements OnInit {
readonly entityVisibilityMap = signal<Map<string, boolean>>(new Map());
isTopicEmpty(topic: string): boolean {
const res = this.rawTrendResponse();
if (!res || !res.series || res.series.length === 0) return false;
const startYr = this.startYear();
const endYr = this.endYear();
const topicLower = topic.toLowerCase().trim();
const mappedLower = this.getMappedTopic(topic).toLowerCase().trim();
return !res.series.some((s) => {
if (!s.topic_data) return false;
const matchingKey = Object.keys(s.topic_data).find((key) => {
const kLower = key.toLowerCase().trim();
return (
kLower === topicLower ||
kLower === mappedLower ||
(kLower.startsWith('news_topic_') &&
kLower.slice('news_topic_'.length) === topicLower)
);
});
if (!matchingKey) return false;
const yearlyList = s.topic_data[matchingKey];
if (!yearlyList || !Array.isArray(yearlyList)) return false;
const total = yearlyList
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((sum, item) => sum + (item.raw || 0), 0);
return total > 0;
});
}
findFirstNonEmptyTopic(topics: string[]): string {
if (!topics || topics.length === 0) return '';
const nonEmpties = topics.filter((t) => !this.isTopicEmpty(t));
return nonEmpties.length > 0 ? nonEmpties[0] : topics[0] || '';
}
isVisible(id: string): boolean {
return this.entityVisibilityMap().get(id) !== false;
}
@@ -294,12 +574,48 @@ export class UniTrendParentComponent implements OnInit {
}
getEntityColor(entityId: string): string {
if (this.selectedSearchType() === 'news') {
const topicName = entityId.startsWith('news_topic_')
? entityId.slice('news_topic_'.length)
: entityId;
return this.getTopicColor(topicName);
}
if (this.selectedSearchType() === 'all') {
const cleanTarget = this.cleanEntityId(entityId).toLowerCase();
const allColors: Record<string, string> = {
publications: '#3b82f6',
works: '#3b82f6',
patents: '#10b981',
projects: '#f59e0b',
news: '#ec4899',
};
if (allColors[cleanTarget]) {
return allColors[cleanTarget];
}
const seriesList = this.rawTrendResponse()?.series || [];
const seriesIdx = seriesList.findIndex(
(s) => this.cleanEntityId(s.entity_id).toLowerCase() === cleanTarget,
);
const fixedColors = ['#3b82f6', '#10b981', '#f59e0b', '#ec4899'];
if (seriesIdx !== -1) {
return fixedColors[seriesIdx % fixedColors.length];
}
return '#3b82f6';
}
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const defaultInstId = 'https://openalex.org/I62318514';
const primaryId = this.primaryInstitution() || defaultInstId;
const insts = this.comparisonInstitutions().map((i) => i.id);
const countries = this.comparisonCountries().map((c) => c.id);
const regions = this.comparisonRegions().map((r) => r.id);
const authors = this.comparisonAuthors().map((a) => a.id);
const primaryId = cleanId(this.primaryInstitution() || defaultInstId);
const insts = this.comparisonInstitutions().map((i) => cleanId(i.id));
const countries = this.comparisonCountries().map((c) => cleanId(c.id));
const regions = this.comparisonRegions().map((r) => cleanId(r.id));
const authors = this.comparisonAuthors().map((a) => cleanId(a.id));
const orderedIds = [
primaryId,
@@ -309,7 +625,8 @@ export class UniTrendParentComponent implements OnInit {
...authors,
];
const idx = orderedIds.indexOf(entityId);
const targetCleanId = cleanId(entityId);
const idx = orderedIds.indexOf(targetCleanId);
if (idx === -1) return '#9ca3af';
const entityColors = [
@@ -345,17 +662,147 @@ export class UniTrendParentComponent implements OnInit {
readonly boundGetEntityColor = (id: string) => this.getEntityColor(id);
readonly boundIsVisible = (id: string) => this.isVisible(id);
// Computed: filters out items locally if they were removed from list
// Computed: filters out items locally if they were removed from list and normalizes topic_data keys & entity names
readonly trendResponse = computed(() => {
const raw = this.rawTrendResponse();
if (!raw) return null;
if (!raw || !raw.series) return null;
const topics = this.selectedTrendTopics();
const type = this.selectedSearchType();
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const primaryInstCleanId = cleanId(
this.primaryInstitution() || 'I62318514',
);
const resolveEntityName = (s: TrendSeries): string => {
let rawName = s.entity_name || '';
if (rawName.startsWith('news_topic_')) {
rawName = rawName.slice('news_topic_'.length);
}
if (
rawName.startsWith('http://') ||
rawName.startsWith('https://') ||
rawName.includes('openalex.org/topics/')
) {
const mapped = this.getMappedTopic(rawName);
if (mapped && !mapped.startsWith('http')) {
return mapped;
}
const match = this.state?.topics()?.find((t) => t.id === rawName);
if (match?.display_name) {
return match.display_name;
}
}
const cId = cleanId(s.entity_id);
if (s.entity_type === 'institution') {
if (cId === primaryInstCleanId) {
return (
this.primaryInstitutionName() ||
s.entity_name ||
'Haupt-Einrichtung'
);
}
const foundInst = this.comparisonInstitutions().find(
(i) => cleanId(i.id) === cId,
);
if (foundInst && foundInst.name && foundInst.name !== foundInst.id) {
return foundInst.name;
}
} else if (s.entity_type === 'country') {
const foundCountry = this.comparisonCountries().find(
(c) => cleanId(c.id) === cId,
);
if (
foundCountry &&
foundCountry.name &&
foundCountry.name !== foundCountry.id
) {
return foundCountry.name;
}
} else if (s.entity_type === 'region') {
const foundRegion = this.comparisonRegions().find(
(r) => cleanId(r.id) === cId,
);
if (
foundRegion &&
foundRegion.name &&
foundRegion.name !== foundRegion.id
) {
return foundRegion.name;
}
} else if (s.entity_type === 'author') {
const foundAuthor = this.comparisonAuthors().find(
(a) => cleanId(a.id) === cId,
);
if (
foundAuthor &&
foundAuthor.name &&
foundAuthor.name !== foundAuthor.id
) {
return foundAuthor.name;
}
}
return s.entity_name &&
!s.entity_name.startsWith('I') &&
s.entity_name.length > 8
? s.entity_name
: s.entity_name || cId;
};
// Map series topic_data keys to display names so they match selectedTrendTopics
const normalizeTopicData = (s: TrendSeries): TrendSeries => {
const nameResolved = resolveEntityName(s);
if (!s.topic_data) return { ...s, entity_name: nameResolved };
const rawTopicKeys = Object.keys(s.topic_data);
if (rawTopicKeys.length === 0) return { ...s, entity_name: nameResolved };
const newTopicData: Record<string, TopicYearlyData[]> = {};
topics.forEach((topicName, idx) => {
const mappedName = this.getMappedTopic(topicName);
let matchKey = rawTopicKeys.find(
(rk) =>
rk.toLowerCase() === topicName.toLowerCase() ||
rk.toLowerCase() === mappedName.toLowerCase() ||
rk.toLowerCase().includes(topicName.toLowerCase()) ||
rk.toLowerCase().includes(mappedName.toLowerCase()),
);
if (!matchKey && rawTopicKeys[idx]) {
matchKey = rawTopicKeys[idx];
}
if (matchKey && s.topic_data[matchKey]) {
newTopicData[topicName] = s.topic_data[matchKey];
} else if (rawTopicKeys[0] && s.topic_data[rawTopicKeys[0]]) {
newTopicData[topicName] = s.topic_data[rawTopicKeys[0]];
}
});
// Preserve existing keys as well
Object.assign(newTopicData, s.topic_data);
return {
...s,
entity_name: nameResolved,
topic_data: newTopicData,
};
};
if (type === 'news' || type === 'all' || type === 'patents') {
return {
...raw,
series: raw.series.map((s) => ({
...s,
...normalizeTopicData(s),
visible: this.isVisible(s.entity_id),
})),
};
@@ -368,7 +815,7 @@ export class UniTrendParentComponent implements OnInit {
const filtered = raw.series
.filter((s) => currentAuthorIds.has(s.entity_id.toLowerCase()))
.map((s) => ({
...s,
...normalizeTopicData(s),
visible: this.isVisible(s.entity_id),
}));
return {
@@ -378,13 +825,6 @@ export class UniTrendParentComponent implements OnInit {
}
// Default: publications, patents, projects
// Resilient ID normalization helper
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const currentInstIds = new Set(
this.comparisonInstitutions().map((i: CompareItem) => cleanId(i.id)),
);
@@ -394,9 +834,6 @@ export class UniTrendParentComponent implements OnInit {
const currentRegionIds = new Set(
this.comparisonRegions().map((r: CompareItem) => cleanId(r.id)),
);
const primaryInstCleanId = cleanId(
this.primaryInstitution() || 'I62318514',
);
const primaryInstSeries: TrendSeries[] = [];
const compInstSeries: TrendSeries[] = [];
@@ -428,7 +865,7 @@ export class UniTrendParentComponent implements OnInit {
...countrySeries,
...regionSeries,
].map((s) => ({
...s,
...normalizeTopicData(s),
visible: this.isVisible(s.entity_id),
}));
@@ -445,6 +882,88 @@ export class UniTrendParentComponent implements OnInit {
this.availableYears.push(y);
}
this.router.events.subscribe((event) => {
if (event instanceof ResolveStart) {
this.isPageResolving.set(true);
} else if (event instanceof ResolveEnd) {
this.isPageResolving.set(false);
}
});
// Subscribe to route resolver data
this.route.data.subscribe((data) => {
if (data['trendData']) {
const resolved = data['trendData'];
const res = resolved.trendResponse ?? resolved;
this.rawTrendResponse.set(res);
const type = resolved.searchType || this.selectedSearchType();
this.selectedSearchType.set(type);
this.fetchedSearchType.set(type);
const fuzzy = this.state?.fuzzySearch() ?? true;
this.fetchedFuzzy.set(fuzzy);
if (resolved.topics && resolved.topics.length > 0) {
this.selectedTrendTopics.set(resolved.topics);
this.fetchedTopics.set([...resolved.topics]);
const targetTopic =
resolved.initialActiveTopic ||
resolved.topics.find((t: string) => !this.isTopicEmpty(t)) ||
resolved.topics[0];
this.activeChartTopic.set(targetTopic);
} else {
this.fetchedTopics.set([...this.selectedTrendTopics()]);
}
if (resolved.institutions && resolved.institutions.length > 0) {
this.comparisonInstitutions.set(resolved.institutions);
this.fetchedInstitutions.set([...resolved.institutions]);
} else {
this.fetchedInstitutions.set([...this.comparisonInstitutions()]);
}
if (resolved.countries && resolved.countries.length > 0) {
this.comparisonCountries.set(resolved.countries);
this.fetchedCountries.set([...resolved.countries]);
} else {
this.fetchedCountries.set([...this.comparisonCountries()]);
}
if (resolved.regions && resolved.regions.length > 0) {
this.comparisonRegions.set(resolved.regions);
this.fetchedRegions.set([...resolved.regions]);
} else {
this.fetchedRegions.set([...this.comparisonRegions()]);
}
if (resolved.authors && resolved.authors.length > 0) {
this.comparisonAuthors.set(resolved.authors);
this.fetchedAuthors.set([...resolved.authors]);
} else {
this.fetchedAuthors.set([...this.comparisonAuthors()]);
}
if (resolved.topSuggestions) {
this.topSuggestions.set(resolved.topSuggestions);
}
if (resolved.recommendedAuthors) {
this.recommendedAuthors.set(resolved.recommendedAuthors);
}
if (resolved.treemapData) {
this.topicTreemap.set(resolved.treemapData);
}
if (resolved.treemapNode !== undefined) {
this.selectedTopicTreemapNode.set(resolved.treemapNode || undefined);
}
this.isTrendLoading.set(false);
}
});
// Effect: automatically sync checkboxes list whenever input keywords or fuzzy state changes
effect(() => {
const kws = this.keywords();
@@ -476,11 +995,20 @@ export class UniTrendParentComponent implements OnInit {
this.selectedTrendTopics.set(topics);
}
// Initialize active chart topic to the first selected topic if empty or invalid
// Initialize active chart topic to a valid non-empty topic
const active = currentActive;
const updatedSelections = untracked(() => this.selectedTrendTopics());
if (!active || !updatedSelections.includes(active)) {
this.activeChartTopic.set(updatedSelections[0] || '');
const mappedActive = this.getMappedTopic(active);
if (
mappedActive &&
updatedSelections.includes(mappedActive) &&
!this.isTopicEmpty(mappedActive)
) {
this.activeChartTopic.set(mappedActive);
} else {
this.activeChartTopic.set(
this.findFirstNonEmptyTopic(updatedSelections),
);
}
// If comparison list is empty, initialize default institutions/authors dynamically
@@ -511,7 +1039,7 @@ export class UniTrendParentComponent implements OnInit {
});
});
// Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with subset check)
// Effect: automatically refetch trend data whenever topics or comparisons change (fully reactive with cached rawTrendResponse check)
effect(() => {
const topics = this.selectedTrendTopics();
const insts = this.comparisonInstitutions();
@@ -526,55 +1054,63 @@ export class UniTrendParentComponent implements OnInit {
const fetchedT = new Set(untracked(() => this.fetchedTopics()));
const fetchedType = untracked(() => this.fetchedSearchType());
const fetchedF = untracked(() => this.fetchedFuzzy());
const rawRes = untracked(() => this.rawTrendResponse());
const allTopicsFetched = topics.every((t) => fetchedT.has(t));
const sameType = searchType === fetchedType;
const sameFuzzy = fuzzy === fetchedF;
let allEntitiesFetched = false;
if (sameType) {
if (sameType && rawRes && rawRes.series) {
const rawSeriesCleanIds = new Set(
rawRes.series.map((s) => {
const id = s.entity_id;
return id.includes('/')
? id.split('/').pop()!.toLowerCase()
: id.toLowerCase();
}),
);
if (searchType === 'authors') {
const fetchedA = new Set(
untracked(() => this.fetchedAuthors()).map((a) =>
a.id.toLowerCase(),
),
);
allEntitiesFetched = authors.every((a) =>
fetchedA.has(a.id.toLowerCase()),
);
} else if (searchType === 'news' || searchType === 'all') {
allEntitiesFetched =
authors.length === 0 ||
authors.every((a) => {
const cleanA = a.id.includes('/')
? a.id.split('/').pop()!.toLowerCase()
: a.id.toLowerCase();
return rawSeriesCleanIds.has(cleanA);
});
} else if (
searchType === 'news' ||
searchType === 'all' ||
searchType === 'patents'
) {
allEntitiesFetched = true;
} else {
// publications, patents, projects
const fetchedI = new Set(
untracked(() => this.fetchedInstitutions()).map((i) =>
i.id.toLowerCase(),
),
);
const fetchedC = new Set(
untracked(() => this.fetchedCountries()).map((c) =>
c.id.toLowerCase(),
),
);
const fetchedR = new Set(
untracked(() => this.fetchedRegions()).map((r) =>
r.id.toLowerCase(),
),
);
allEntitiesFetched =
insts.every((i) => fetchedI.has(i.id.toLowerCase())) &&
countries.every((c) => fetchedC.has(c.id.toLowerCase())) &&
regions.every((r) => fetchedR.has(r.id.toLowerCase()));
(insts.length === 0 ||
insts.every((i) => {
const cleanI = i.id.includes('/')
? i.id.split('/').pop()!.toLowerCase()
: i.id.toLowerCase();
return rawSeriesCleanIds.has(cleanI);
})) &&
(countries.length === 0 ||
countries.every((c) =>
rawSeriesCleanIds.has(c.id.toLowerCase()),
)) &&
(regions.length === 0 ||
regions.every((r) => rawSeriesCleanIds.has(r.id.toLowerCase())));
}
}
const hasResponse = !!untracked(() => this.rawTrendResponse());
if (
allTopicsFetched &&
sameType &&
sameFuzzy &&
allEntitiesFetched &&
hasResponse
!!rawRes
) {
// All requested data is already present in rawTrendResponse, so skip backend call!
return;
@@ -762,7 +1298,7 @@ export class UniTrendParentComponent implements OnInit {
const end = this.endYear();
const strategy = this.selectedSearchType();
if (!entity || strategy === 'news' || strategy === 'all') {
if (!entity || strategy === 'all') {
this.topTopicsData.set([]);
return;
}
@@ -899,12 +1435,16 @@ export class UniTrendParentComponent implements OnInit {
if (kws.length === 0) return;
const topics = this.state?.topicsList() ?? kws;
const topic = topics[0] || kws[0] || 'Artificial Intelligence';
const topic =
this.findFirstNonEmptyTopic(topics) ||
topics[0] ||
kws[0] ||
'Artificial Intelligence';
this.personsApiService
.searchPersonsList(
undefined, // query
'University of Duisburg-Essen', // primary institution
this.primaryInstitution() || 'I62318514', // primary institution ID
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
@@ -993,7 +1533,7 @@ export class UniTrendParentComponent implements OnInit {
this.personsApiService
.searchPersonsList(
undefined, // query
'University of Duisburg-Essen', // UDE
this.primaryInstitution() || 'I62318514', // UDE institution ID
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
@@ -1068,9 +1608,33 @@ export class UniTrendParentComponent implements OnInit {
)
.subscribe({
next: (response: TrendResponse) => {
this.rawTrendResponse.set(response);
const currentRaw = untracked(() => this.rawTrendResponse());
if (!currentRaw || !currentRaw.series) {
this.rawTrendResponse.set(response);
} else {
const seriesMap = new Map<string, TrendSeries>();
currentRaw.series.forEach((s) => {
seriesMap.set(`${s.entity_type}_${s.entity_id}`, s);
});
response.series.forEach((s) => {
const key = `${s.entity_type}_${s.entity_id}`;
const prev = seriesMap.get(key);
if (prev && prev.topic_data && s.topic_data) {
seriesMap.set(key, {
...prev,
...s,
topic_data: { ...prev.topic_data, ...s.topic_data },
});
} else {
seriesMap.set(key, s);
}
});
this.rawTrendResponse.set({
...response,
series: Array.from(seriesMap.values()),
});
}
this.isTrendLoading.set(false);
this.updateUrlParams();
},
error: () => {
this.isTrendLoading.set(false);
@@ -1111,6 +1675,7 @@ export class UniTrendParentComponent implements OnInit {
end_year: this.endYear(),
chart_mode: this.chartMode(),
active_chart_topic: this.activeChartTopic(),
treemapNode: this.selectedTopicTreemapNode() ?? null,
};
this.router.navigate([], {
@@ -1120,6 +1685,34 @@ export class UniTrendParentComponent implements OnInit {
});
}
fetchTreemapData() {
const fuzzy = this.state?.fuzzySearch() ?? true;
const topics = this.selectedTrendTopics();
if (!fuzzy || topics.length === 0) {
this.topicTreemap.set(null);
return;
}
this.isTreemapLoading.set(true);
this.topicsService.countTopicHierarchy(topics).subscribe({
next: (res: any) => {
this.topicTreemap.set(res);
this.isTreemapLoading.set(false);
},
error: () => {
this.isTreemapLoading.set(false);
},
});
}
onTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedTopicTreemapNode.set(nodeId);
this.updateUrlParams();
}
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
// Topic selected inside treemap component
}
// Checkbox topic toggling
onTrendTopicToggle(topic: string, event: Event) {
const isChecked = (event.target as HTMLInputElement).checked;
@@ -1141,8 +1734,8 @@ export class UniTrendParentComponent implements OnInit {
this.selectedTrendTopics.set(updated);
const active = this.activeChartTopic();
if (!updated.includes(active)) {
this.activeChartTopic.set(updated[0] || '');
if (!updated.includes(active) || this.isTopicEmpty(active)) {
this.activeChartTopic.set(this.findFirstNonEmptyTopic(updated));
}
}
@@ -1252,7 +1845,7 @@ export class UniTrendParentComponent implements OnInit {
this.personsApiService
.searchPersonsList(
undefined, // query
name, // institutionName
id, // institutionId
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
@@ -1311,39 +1904,18 @@ export class UniTrendParentComponent implements OnInit {
this.updateUrlParams();
}
isTopicEmpty(topic: string): boolean {
const data = this.trendResponse();
if (!data || !data.series || data.series.length === 0) {
return false;
onChartModeChange(event: MatButtonToggleChange) {
if (event.value) {
this.setChartMode(event.value);
}
const mapped = this.getMappedTopic(topic);
const startYr = this.startYear();
const endYr = this.endYear();
let totalRaw = 0;
data.series.forEach((s) => {
if (s.visible !== false && s.topic_data) {
const items = s.topic_data[topic] || s.topic_data[mapped];
if (items) {
items.forEach((y) => {
if (y.year >= startYr && y.year <= endYr) {
totalRaw += y.raw || 0;
}
});
}
}
});
return totalRaw === 0;
}
// Topic tab toggle (data reuses instantly)
// Topic tab toggle (data reuses instantly, no router navigation to prevent chart flickering)
updateActiveChartTopic(topic: string) {
if (this.isTopicEmpty(topic)) {
return;
}
this.activeChartTopic.set(topic);
this.updateUrlParams();
}
// Autocomplete query changes for institutions