changed backend search filter & frontend topic search component (the topics are for now not in the frontend (fetched everytime to reflect changes))
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Kazgatari
2026-06-06 11:20:25 +02:00
parent 765c5c9509
commit ba296ef499
16 changed files with 764 additions and 75 deletions
+58
View File
@@ -90,8 +90,12 @@ def insert_element(db: Session, value: S) -> S:
def _load_topic_cache() -> dict:
"""Loads the topic hierarchy cache from a JSON file."""
import os
try:
cache_path = "/data/" + topic_cache_filename
if not os.path.exists(cache_path):
current_dir = os.path.dirname(__file__)
cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename)
with open(cache_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as exc:
@@ -226,3 +230,57 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
counts["domains"][domain] = counts["domains"].get(domain, 0) + 1
return counts
def get_topic_hierarchy() -> dict:
"""
Builds and returns a hierarchical tree structure of topics:
Domains -> Fields -> Subfields -> Topics
"""
flat_cache = _load_topic_cache()
tree = {}
for topic_name, info in flat_cache.items():
domain = info.get("domain") or "Unbekannter Bereich"
field = info.get("field") or "Unbekanntes Feld"
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
topic_id = info.get("topic_id", "")
# Clean topic ID to just be the trailing ID or keep full URL
# For querying, display name is used in persons search, but ID is useful
if domain not in tree:
tree[domain] = {}
if field not in tree[domain]:
tree[domain][field] = {}
if subfield not in tree[domain][field]:
tree[domain][field][subfield] = []
tree[domain][field][subfield].append({
"id": topic_id,
"name": topic_name
})
formatted_domains = []
for d_name, d_fields in tree.items():
formatted_fields = []
for f_name, f_subfields in d_fields.items():
formatted_subfields = []
for sf_name, sf_topics in f_subfields.items():
sf_topics.sort(key=lambda x: x["name"])
formatted_subfields.append({
"name": sf_name,
"topics": sf_topics
})
formatted_subfields.sort(key=lambda x: x["name"])
formatted_fields.append({
"name": f_name,
"subfields": formatted_subfields
})
formatted_fields.sort(key=lambda x: x["name"])
formatted_domains.append({
"name": d_name,
"fields": formatted_fields
})
formatted_domains.sort(key=lambda x: x["name"])
return {"domains": formatted_domains}
+5 -1
View File
@@ -366,6 +366,8 @@ def advanced_search_persons(
page_size: int = 10,
include: Optional[set[str]] = None,
strict: Optional[bool] = False,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None,
) -> CustomAuthorsListResponse:
try:
query_body = build_authors_search(
@@ -376,7 +378,9 @@ def advanced_search_persons(
page_size=page_size,
include=include,
strict=strict,
track_total_hits = True
track_total_hits = True,
filter_mode=filter_mode,
filter_year=filter_year
)
response_dict = elasticsearch.search(
index=INDEX_NAME,
+6 -4
View File
@@ -9,16 +9,18 @@ from pydantic import Field
from typing import List, Optional
from inse.models.author import Author
from inse.models.meta import Meta
from inse.models.authors_list_response import AuthorsListResponse
from inse.models.group_by_result import GroupByResult
class CustomAuthor(Author):
relevance_rating: Optional[str] = Field(default=None, description="The relevance suitability rating.")
class CustomAuthorsListResponse(BaseModel):
meta: Optional[Meta] = None
results: Optional[List[CustomAuthor]] = None
group_by: Optional[List[GroupByResult]] = None
class CustomAuthorsListResponse(AuthorsListResponse):
pass
#meta: Optional[Meta] = None
#results: Optional[List[CustomAuthor]] = None
#group_by: Optional[List[GroupByResult]] = None
class PersonBio(BaseModel):
+48 -13
View File
@@ -11,8 +11,9 @@ def build_authors_search(
page_size: int = 10,
include: Optional[Set[str]] = None,
strict: Optional[bool] = False,
track_total_hits: Optional[bool] = False
track_total_hits: Optional[bool] = False,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None
) -> dict:
"""
Builds an Elasticsearch search request query body for authors as a dictionary.
@@ -55,11 +56,20 @@ def build_authors_search(
# 2. Build Filters
filter_clauses = []
if institution_name:
if strict:
if filter_year is not None:
target_year = filter_year
mode = filter_mode or "from"
else:
from datetime import datetime
current_year = datetime.now().year
target_year = current_year - 1
mode = "from"
range_query = {"gte": target_year}
if mode == "in":
range_query["lte"] = target_year
if strict:
filter_clauses.append({
"nested": {
"path": "affiliations",
@@ -73,9 +83,7 @@ def build_authors_search(
},
{
"range": {
"affiliations.years": {
"gte": target_year
}
"affiliations.years": range_query
}
}
]
@@ -85,15 +93,42 @@ def build_authors_search(
})
else:
filter_clauses.append({
"nested": {
"path": "affiliations",
"query": {
"match_phrase": {
"affiliations.institution.display_name": institution_name
"bool": {
"filter": [
{
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.display_name": institution_name
}
}
}
},
{
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name
}
},
{
"range": {
"affiliations.years": range_query
}
}
]
}
}
}
}
}
})
]
}
})
if topics:
for t in topics:
+8
View File
@@ -209,6 +209,12 @@ def search_persons_list(
strict: Annotated[
Optional[bool], Query(description="Strict institution search by target year")
] = False,
filter_mode: Annotated[
Optional[str], Query(alias="filterMode", description="Filter mode: 'in' or 'from'")
] = "from",
filter_year: Annotated[
Optional[int], Query(alias="filterYear", description="Filter year")
] = None,
):
include_set = (
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
@@ -223,4 +229,6 @@ def search_persons_list(
page_size=page_size,
include=include_set,
strict=strict,
filter_mode=filter_mode,
filter_year=filter_year,
)
+10
View File
@@ -208,3 +208,13 @@ def count_topic_hierarchy(
],
):
return logic.count_topic_hierarchy(topic_names)
@router.get(
"/topics/hierarchy",
operation_id="getTopicHierarchy",
response_model=dict,
summary="Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).",
tags=["Topics"],
)
def get_topic_hierarchy():
return logic.get_topic_hierarchy()
+16 -8
View File
@@ -731,10 +731,10 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -755,6 +755,10 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>strict, 'strict');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterMode, 'filterMode');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterYear, 'filterYear');
let localVarHeaders = this.defaultHeaders;
@@ -810,10 +814,10 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -834,6 +838,10 @@ export class PersonsService extends BaseService implements PersonsServiceInterfa
<any>include, 'include');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>strict, 'strict');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterMode, 'filterMode');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>filterYear, 'filterYear');
let localVarHeaders = this.defaultHeaders;
@@ -124,19 +124,7 @@ export interface PersonsServiceInterface {
*/
searchPersonsByName_4(authorName: string, include: string, limit?: number, pageOffset?: number, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* Searches for persons with advanced filters (Topic &amp; Institution) and pagination.
*
* @endpoint get /api/inse-service/persons/search-list
* @param query Search query (e.g., Arman AND Arzani)
* @param institutionName Filter by institution name
* @param topic Filter by topic display names
* @param page Page number (1-indexed)
* @param pageSize Results per page
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
*/
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
/**
* Searches for persons with advanced filters (Topic &amp; Institution) and pagination.
@@ -150,6 +138,6 @@ export interface PersonsServiceInterface {
* @param include Comma-separated include tags
* @param strict Strict institution search by target year
*/
searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
searchPersonsList_5(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, filterMode?: string, filterYear?: number, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
}
+51
View File
@@ -162,4 +162,55 @@ export class TopicsService extends BaseService implements TopicsServiceInterface
);
}
/**
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
* @endpoint get /api/inse-service/topics/hierarchy
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -39,4 +39,11 @@ export interface TopicsServiceInterface {
*/
countTopicHierarchy(topic: Array<string>, extraHttpRequestParams?: any): Observable<object>;
/**
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
*
* @endpoint get /api/inse-service/topics/hierarchy
*/
getTopicHierarchy(extraHttpRequestParams?: any): Observable<object>;
}
@@ -92,7 +92,9 @@
</button>
</div>
<h2 class="person-name">{{ person.display_name }}</h2>
<p class="institution"><span>{{ institution(person)?.display_name }}</span><img alt="" class="flag-img" [src]="`https://flagcdn.io/${institution(person)?.country_code?.toLowerCase()}.svg`" height="15"></p>
<p class="institution"><span>{{ institution(person)?.display_name }}</span><img alt="" class="flag-img"
[src]="`https://flagcdn.io/${institution(person)?.country_code?.toLowerCase()}.svg`" height="15">
</p>
<p class="person-id">{{ getDistinguishingId(person) }}</p>
<p class="stats">
Works: {{ person.works_count }} ·
@@ -182,21 +184,11 @@
}
</div>
<div class="checkbox-list">
@for (topic of filteredTopicsList; track topic) {
<label class="checkbox-label">
<input type="checkbox" [checked]="isTopicSelected(topic)" (change)="toggleTopic(topic)" />
<span class="checkbox-text">{{ topic }}</span>
</label>
}
@if (topicsList.length > 5 && !topicSearchControl.value) {
<button class="show-more-btn" (click)="toggleShowAllTopics()">
<span>{{ showAllTopics ? 'Weniger anzeigen' : 'Mehr anzeigen' }}</span>
<mat-icon>{{ showAllTopics ? 'expand_less' : 'expand_more' }}</mat-icon>
</button>
}
</div>
<app-topic-hierarchy
[selectedTopics]="selectedTopics"
[searchQuery]="topicSearchControl.value"
(selectionChange)="onTopicSelectionChange($event)">
</app-topic-hierarchy>
</div>
<!-- Section 2: Institution Filter -->
@@ -212,11 +204,36 @@
</button>
}
</div>
<div class="strict-search-wrapper" style="margin-top: 8px;">
<label class="checkbox-label">
<input type="checkbox" [formControl]="strictControl" (change)="applySidebarFilters()" />
<span class="checkbox-text">Letzten 2 Jahre</span>
</label>
<div class="year-filter-wrapper" style="margin-top: 12px; display: flex; flex-direction: column; gap: 8px;">
<mat-checkbox [formControl]="yearFilterEnabledControl" (change)="applySidebarFilters()">
<span style="font-size: 12px; font-weight: 500; color: var(--sg-text);">Zusammenarbeit nach Jahr
filtern</span>
</mat-checkbox>
@if (yearFilterEnabledControl.value) {
<div class="year-filter-options" style="display: flex; flex-direction: column; gap: 8px; padding-left: 28px;">
<mat-radio-group [formControl]="filterModeControl" (change)="applySidebarFilters()"
style="display: flex; gap: 16px;">
<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-group>
<mat-form-field appearance="outline"
style="width: 100%; font-size: 13px; margin-top: 4px;">
<mat-label>Jahr</mat-label>
<input matInput type="number" [formControl]="filterYearControl" (change)="applySidebarFilters()"
(keyup.enter)="applySidebarFilters()" placeholder="Z. B. 2025" />
@if (filterYearControl.hasError('min')) {
<mat-error>Jahr muss ≥ 1900 sein</mat-error>
}
@if (filterYearControl.hasError('max')) {
<mat-error>Zukünftige Jahre sind nicht erlaubt</mat-error>
}
</mat-form-field>
</div>
}
</div>
</div>
@@ -229,4 +246,4 @@
</aside>
</div>
</section>
</section>
@@ -2,7 +2,7 @@ import { Component, inject, signal, DestroyRef } from '@angular/core';
import { Router, RouterLink, ActivatedRoute } from '@angular/router';
import { CommonModule } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon';
import { MatPaginatorModule } from '@angular/material/paginator';
@@ -10,9 +10,13 @@ import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { CustomAuthor} from '../../api/model/custom-author';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio';
import { CustomAuthor } from '../../api/model/custom-author';
// import { PersonsSearchService } from '../../api/api/persons-search.service';
import { DehydratedInstitution, PersonsService } from '../../api';
import { TopicsService } from '../../api/api/topics.service';
import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component';
import { SharedStateService } from '../../shared/services/shared-state.service';
import { PaginationService } from '../../shared/services/pagination.service';
import { finalize } from 'rxjs';
@@ -30,6 +34,9 @@ import { MatSnackBar } from '@angular/material/snack-bar';
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatCheckboxModule,
MatRadioModule,
TopicHierarchyComponent,
],
templateUrl: './person-list.component.html',
styleUrl: './person-list.component.scss',
@@ -39,6 +46,7 @@ export class PersonListComponent {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly personsService = inject(PersonsService);
private readonly topicsService = inject(TopicsService);
private readonly destroyRef = inject(DestroyRef);
private readonly snackBar = inject(MatSnackBar);
public readonly state = inject(SharedStateService);
@@ -73,7 +81,12 @@ export class PersonListComponent {
sortControl = new FormControl('relevance', { nonNullable: true });
topicSearchControl = new FormControl('', { nonNullable: true });
institutionControl = new FormControl('', { nonNullable: true });
strictControl = new FormControl(false, { nonNullable: true });
yearFilterEnabledControl = new FormControl(false, { nonNullable: true });
filterModeControl = new FormControl<'in' | 'from'>('from', { nonNullable: true });
filterYearControl = new FormControl<number>(new Date().getFullYear() - 1, {
nonNullable: true,
validators: [Validators.min(1900), Validators.max(new Date().getFullYear())]
});
showAllTopics = false;
// Bookmarking
@@ -88,7 +101,9 @@ export class PersonListComponent {
const page = params['page'] ? Number.parseInt(params['page'], 10) : 1;
const pageSize = params['pageSize'] ? Number.parseInt(params['pageSize'], 10) : 10;
const institutionName = params['institutionName'] || '';
const strict = params['strict'] === 'true';
const yearFilterEnabled = params['yearFilterEnabled'] === 'true';
const filterMode = (params['filterMode'] === 'in' || params['filterMode'] === 'from') ? params['filterMode'] : 'from';
const filterYear = params['filterYear'] ? Number.parseInt(params['filterYear'], 10) : (new Date().getFullYear() - 1);
const topics = this.parseQueryParamArray(params['topic']);
@@ -103,11 +118,17 @@ export class PersonListComponent {
if (this.institutionControl.value !== institutionName) {
this.institutionControl.setValue(institutionName);
}
if (this.strictControl.value !== strict) {
this.strictControl.setValue(strict);
if (this.yearFilterEnabledControl.value !== yearFilterEnabled) {
this.yearFilterEnabledControl.setValue(yearFilterEnabled);
}
if (this.filterModeControl.value !== filterMode) {
this.filterModeControl.setValue(filterMode);
}
if (this.filterYearControl.value !== filterYear) {
this.filterYearControl.setValue(filterYear);
}
this.load(query, page, pageSize, topics, institutionName, strict);
this.load(query, page, pageSize, topics, institutionName, yearFilterEnabled, filterMode, filterYear);
});
}
@@ -117,7 +138,9 @@ export class PersonListComponent {
pageSize: number = 10,
topics?: string[],
institutionName?: string,
strict: boolean = false
yearFilterEnabled: boolean = false,
filterMode: 'in' | 'from' = 'from',
filterYear?: number
): void {
this.loadingState.set(true);
@@ -128,7 +151,9 @@ export class PersonListComponent {
page,
pageSize,
this.defaultIncludes,
strict || undefined
yearFilterEnabled ? true : undefined,
yearFilterEnabled ? filterMode : undefined,
yearFilterEnabled ? filterYear : undefined
)
.pipe(
finalize(() => this.loadingState.set(false)),
@@ -206,7 +231,11 @@ export class PersonListComponent {
list.push({ category: 'topic', value: t, label: t });
});
if (this.institutionControl.value) {
const label = `Institution: ${this.institutionControl.value}${this.strictControl.value ? ' (Strict)' : ''}`;
let label = `Institution: ${this.institutionControl.value}`;
if (this.yearFilterEnabledControl.value) {
const modeLabel = this.filterModeControl.value === 'in' ? 'in' : 'from';
label += ` (${modeLabel} ${this.filterYearControl.value})`;
}
list.push({
category: 'institutionName',
value: this.institutionControl.value,
@@ -221,7 +250,9 @@ export class PersonListComponent {
this.selectedTopics.delete(filter.value);
} else if (filter.category === 'institutionName') {
this.institutionControl.setValue('');
this.strictControl.setValue(false);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
}
this.applySidebarFilters();
}
@@ -229,16 +260,24 @@ export class PersonListComponent {
clearAllFilters(): void {
this.selectedTopics.clear();
this.institutionControl.setValue('');
this.strictControl.setValue(false);
this.yearFilterEnabledControl.setValue(false);
this.filterModeControl.setValue('from');
this.filterYearControl.setValue(new Date().getFullYear() - 1);
this.applySidebarFilters();
}
applySidebarFilters(): void {
if (this.yearFilterEnabledControl.value && this.filterYearControl.invalid) {
return;
}
this.router.navigate([], {
queryParams: {
topic: this.selectedTopics.size ? Array.from(this.selectedTopics) : null,
institutionName: this.institutionControl.value || null,
strict: this.strictControl.value ? 'true' : null,
yearFilterEnabled: this.institutionControl.value && this.yearFilterEnabledControl.value ? 'true' : null,
filterMode: this.institutionControl.value && this.yearFilterEnabledControl.value ? this.filterModeControl.value : null,
filterYear: this.institutionControl.value && this.yearFilterEnabledControl.value ? this.filterYearControl.value : null,
strict: null,
page: 1,
},
queryParamsHandling: 'merge',
@@ -341,6 +380,11 @@ export class PersonListComponent {
}
}
onTopicSelectionChange(newSelection: Set<string>): void {
this.selectedTopics = newSelection;
this.applySidebarFilters();
}
isBookmarked(person: CustomAuthor): boolean {
return !!person.id && this.bookmarkedIds.has(person.id);
}
@@ -0,0 +1,93 @@
<div class="hierarchy-container">
@if (loading()) {
<div class="loading-state">
<mat-spinner diameter="24"></mat-spinner>
<span>Lade Themen...</span>
</div>
} @else {
@if (searchQuery) {
<!-- Flat Search Results Mode -->
<div class="search-results">
<span class="results-meta">{{ filteredFlatTopics.length }} Treffer</span>
<div class="flat-list">
@for (topic of filteredFlatTopics; track topic.id) {
<div class="flat-row">
<mat-checkbox
[checked]="selectedTopics.has(topic.name)"
(change)="toggleTopic(topic.name)">
<span class="topic-name">{{ topic.name }}</span>
</mat-checkbox>
<span class="topic-path" [title]="topic.path">{{ topic.path }}</span>
</div>
} @empty {
<div class="empty-search">Keine passenden Themen.</div>
}
</div>
</div>
} @else {
<!-- Embedded Multi-Nested Hierarchy Tree Mode -->
<div class="tree-root">
@for (domain of domains; track domain.name) {
<!-- LEVEL 1: Domain -->
<div class="tree-node domain-node">
<button class="node-header domain-header" (click)="toggleDomain(domain.name)">
<mat-icon class="toggle-icon">
{{ expandedDomains.has(domain.name) ? 'expand_more' : 'chevron_right' }}
</mat-icon>
<span class="node-title domain-title">{{ domain.name }}</span>
</button>
@if (expandedDomains.has(domain.name)) {
<div class="node-children domain-children">
@for (field of domain.fields; track field.name) {
<!-- LEVEL 2: Field -->
<div class="tree-node field-node">
<button class="node-header field-header" (click)="toggleField(field.name)">
<mat-icon class="toggle-icon">
{{ expandedFields.has(field.name) ? 'expand_more' : 'chevron_right' }}
</mat-icon>
<mat-icon class="folder-icon">folder</mat-icon>
<span class="node-title field-title">{{ field.name }}</span>
</button>
@if (expandedFields.has(field.name)) {
<div class="node-children field-children">
@for (subfield of field.subfields; track subfield.name) {
<!-- LEVEL 3: Subfield -->
<div class="tree-node subfield-node">
<button class="node-header subfield-header" (click)="toggleSubfield(subfield.name)">
<mat-icon class="toggle-icon">
{{ expandedSubfields.has(subfield.name) ? 'expand_more' : 'chevron_right' }}
</mat-icon>
<mat-icon class="folder-icon">folder_open</mat-icon>
<span class="node-title subfield-title">{{ subfield.name }}</span>
</button>
@if (expandedSubfields.has(subfield.name)) {
<div class="node-children subfield-children">
@for (topic of subfield.topics; track topic.id) {
<!-- LEVEL 4: Topic Checkbox -->
<div class="tree-leaf topic-node">
<mat-checkbox
[checked]="selectedTopics.has(topic.name)"
(change)="toggleTopic(topic.name)">
<span class="topic-label" [title]="topic.name">{{ topic.name }}</span>
</mat-checkbox>
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
</div>
}
}
</div>
@@ -0,0 +1,194 @@
.hierarchy-container {
width: 100%;
max-height: 400px;
overflow-y: auto;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-background);
padding: 4px;
margin-top: 4px;
}
.loading-state {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 16px;
color: var(--sg-text-muted);
font-size: 12px;
}
/* Flat Search Results Styles */
.search-results {
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px;
}
.results-meta {
font-size: 11px;
font-weight: 600;
color: var(--sg-text-muted);
text-transform: uppercase;
padding-left: 4px;
}
.flat-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.flat-row {
display: flex;
flex-direction: column;
padding: 6px;
border-bottom: 1px solid var(--sg-border-soft);
&:last-child {
border-bottom: none;
}
.topic-name {
font-size: 12px;
color: var(--sg-text);
font-weight: 500;
}
.topic-path {
font-size: 10px;
color: var(--sg-text-soft);
padding-left: 28px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
}
.empty-search {
padding: 16px;
font-size: 12px;
color: var(--sg-text-muted);
text-align: center;
}
/* Hierarchy Tree Styles */
.tree-root {
display: flex;
flex-direction: column;
gap: 2px;
}
.tree-node {
display: flex;
flex-direction: column;
}
.node-header {
display: flex;
align-items: center;
width: 100%;
background: transparent;
border: none;
padding: 4px 6px;
text-align: left;
cursor: pointer;
border-radius: 4px;
color: var(--sg-text);
&:hover {
background: var(--sg-surface-soft);
}
.toggle-icon {
font-size: 16px;
width: 16px;
height: 16px;
color: var(--sg-text-soft);
margin-right: 2px;
}
.folder-icon {
font-size: 14px;
width: 14px;
height: 14px;
color: var(--sg-primary-soft);
margin-right: 4px;
}
.node-title {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
}
.domain-header {
padding-top: 6px;
padding-bottom: 6px;
.domain-title {
font-size: 12px;
font-weight: 600;
color: var(--sg-text);
}
}
.field-header {
.field-title {
font-size: 11.5px;
font-weight: 500;
color: var(--sg-text-muted);
}
}
.subfield-header {
.subfield-title {
font-size: 11px;
color: var(--sg-text-muted);
}
}
.node-children {
display: flex;
flex-direction: column;
gap: 2px;
}
.domain-children {
padding-left: 12px;
border-left: 1px solid var(--sg-border-soft);
margin-left: 12px;
margin-bottom: 4px;
}
.field-children {
padding-left: 14px;
border-left: 1px solid var(--sg-border-soft);
margin-left: 14px;
}
.subfield-children {
padding-left: 14px;
border-left: 1px dashed var(--sg-border-soft);
margin-left: 14px;
margin-bottom: 2px;
}
.tree-leaf {
padding: 2px 4px;
}
.topic-node {
.topic-label {
font-size: 11px;
color: var(--sg-text);
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: block;
max-width: 190px;
}
}
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TopicHierarchyComponent } from './topic-hierarchy.component';
describe('TopicHierarchyComponent', () => {
let component: TopicHierarchyComponent;
let fixture: ComponentFixture<TopicHierarchyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TopicHierarchyComponent]
})
.compileComponents();
fixture = TestBed.createComponent(TopicHierarchyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,147 @@
import { Component, Input, Output, EventEmitter, OnInit, signal, effect } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { TopicsService } from '../../api/api/topics.service';
export interface TopicItem {
id: string;
name: string;
}
export interface SubfieldNode {
name: string;
topics: TopicItem[];
}
export interface FieldNode {
name: string;
subfields: SubfieldNode[];
}
export interface DomainNode {
name: string;
fields: FieldNode[];
}
interface FlatTopic {
id: string;
name: string;
path: string;
}
@Component({
selector: 'app-topic-hierarchy',
standalone: true,
imports: [
CommonModule,
MatCheckboxModule,
MatIconModule,
MatProgressSpinnerModule
],
templateUrl: './topic-hierarchy.component.html',
styleUrl: './topic-hierarchy.component.scss'
})
export class TopicHierarchyComponent implements OnInit {
@Input() selectedTopics: Set<string> = new Set<string>();
@Input() searchQuery: string = '';
@Output() selectionChange = new EventEmitter<Set<string>>();
domains: DomainNode[] = [];
flatTopics: FlatTopic[] = [];
filteredFlatTopics: FlatTopic[] = [];
loading = signal(true);
// Set of names of expanded nodes (lazy content rendering)
expandedDomains = new Set<string>();
expandedFields = new Set<string>();
expandedSubfields = new Set<string>();
constructor(private topicsService: TopicsService) {
// React to search query inputs
effect(() => {
this.filterFlatTopics();
});
}
ngOnInit(): void {
this.topicsService.getTopicHierarchy().subscribe({
next: (res: any) => {
this.domains = res.domains || [];
this.flattenTopics(this.domains);
this.loading.set(false);
},
error: (err) => {
console.error('Error fetching topic hierarchy:', err);
this.loading.set(false);
}
});
}
flattenTopics(domains: DomainNode[]): void {
const flat: FlatTopic[] = [];
domains.forEach((domain) => {
domain.fields?.forEach((field) => {
field.subfields?.forEach((subfield) => {
subfield.topics?.forEach((topic) => {
if (topic.name && topic.id) {
flat.push({
id: topic.id,
name: topic.name,
path: `${domain.name} > ${field.name} > ${subfield.name}`
});
}
});
});
});
});
this.flatTopics = flat;
this.filterFlatTopics();
}
filterFlatTopics(): void {
if (!this.searchQuery) {
this.filteredFlatTopics = [];
return;
}
const query = this.searchQuery.toLowerCase();
this.filteredFlatTopics = this.flatTopics.filter((t) =>
t.name.toLowerCase().includes(query) || t.path.toLowerCase().includes(query)
);
}
toggleTopic(name: string): void {
const nextSelection = new Set(this.selectedTopics);
if (nextSelection.has(name)) {
nextSelection.delete(name);
} else {
nextSelection.add(name);
}
this.selectionChange.emit(nextSelection);
}
toggleDomain(name: string): void {
if (this.expandedDomains.has(name)) {
this.expandedDomains.delete(name);
} else {
this.expandedDomains.add(name);
}
}
toggleField(name: string): void {
if (this.expandedFields.has(name)) {
this.expandedFields.delete(name);
} else {
this.expandedFields.add(name);
}
}
toggleSubfield(name: string): void {
if (this.expandedSubfields.has(name)) {
this.expandedSubfields.delete(name);
} else {
this.expandedSubfields.add(name);
}
}
}