Files
smartguide/webapp/src/app/modules/patents/patents.component.ts
T
khalti 34b01f2ae8
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
feat(patents): color OpenAlex topic and IPC/CPC classification tags by academic field, reusing the existing topic-chip color palette
2026-07-11 20:50:31 +02:00

400 lines
14 KiB
TypeScript

import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
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 { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api/model/patentEntry';
import { IpcClassification } from '../../api';
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type ClassificationSystem = 'IPC' | 'CPC';
interface ClassificationCard {
key: string;
symbols: string[];
system: ClassificationSystem;
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
sectionName: string | null;
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
const MIN_YEAR = 1978;
@Component({
selector: 'app-patents',
imports: [
CommonModule,
RouterModule,
MatIconModule,
MatButtonModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatChipsModule,
MatDividerModule,
TopicChipComponent,
],
templateUrl: './patents.component.html',
styleUrl: './patents.component.scss',
})
export class PatentsComponent implements OnInit {
private router = inject(Router);
private route = inject(ActivatedRoute);
private patentsApi = inject(PatentsService);
patents: PatentEntry[] = [];
total = 0;
page = 0;
pageSize = 10;
loading = true;
error = false;
searchTerm = '';
activeFilter: SourceFilter = 'all';
sortDirection: string = 'asc';
// Jahr-Slider
readonly minYear = MIN_YEAR;
readonly maxYear = new Date().getFullYear();
selectedStartYear = MIN_YEAR;
selectedEndYear = new Date().getFullYear();
private searchSubject = new Subject<string>();
showDetail = false;
selectedPatent: PatentEntry | null = null;
readonly expandedClassificationKeys = new Set<string>();
constructor() {
this.searchSubject
.pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed())
.subscribe((term) => {
this.searchTerm = term;
this.page = 0;
this.loadPatents();
this.updateQueryParams();
});
}
ngOnInit(): void {
const qp = this.route.snapshot.queryParamMap;
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 d = qp.get('sort_direction');
if (d === 'asc' || d === 'desc') this.sortDirection = d;
const sy = parseInt(qp.get('year_from') ?? '', 10);
const ey = parseInt(qp.get('year_to') ?? '', 10);
if (!isNaN(sy)) this.selectedStartYear = sy;
if (!isNaN(ey)) this.selectedEndYear = ey;
this.loadPatents();
}
get rangeStartPercent(): string {
const total = this.maxYear - this.minYear;
return `${((this.selectedStartYear - this.minYear) / total) * 100}%`;
}
get rangeEndPercent(): string {
const total = this.maxYear - this.minYear;
return `${((this.selectedEndYear - this.minYear) / total) * 100}%`;
}
get canResetYearRange(): boolean {
return this.selectedStartYear !== this.minYear || this.selectedEndYear !== this.maxYear;
}
// Fired continuously while dragging: only updates the displayed value/handle
// position, no HTTP request yet.
onStartYearDrag(event: Event): void {
const input = event.target as HTMLInputElement;
this.selectedStartYear = Math.min(parseInt(input.value, 10), this.selectedEndYear);
}
onEndYearDrag(event: Event): void {
const input = event.target as HTMLInputElement;
this.selectedEndYear = Math.max(parseInt(input.value, 10), this.selectedStartYear);
}
// Fired once on release: commits the value and triggers the search request.
onStartYearInput(event: Event): void {
const input = event.target as HTMLInputElement;
this.selectedStartYear = Math.min(parseInt(input.value, 10), this.selectedEndYear);
input.value = String(this.selectedStartYear);
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
onEndYearInput(event: Event): void {
const input = event.target as HTMLInputElement;
this.selectedEndYear = Math.max(parseInt(input.value, 10), this.selectedStartYear);
input.value = String(this.selectedEndYear);
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
resetYearRange(): void {
this.selectedStartYear = this.minYear;
this.selectedEndYear = this.maxYear;
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
private loadPatents(): void {
this.loading = true;
this.error = false;
const source = this.activeFilter === 'all' ? undefined : this.activeFilter;
this.patentsApi
.getAllPatents(
this.page,
this.pageSize,
this.searchTerm || undefined,
source,
'date',
this.sortDirection,
this.selectedStartYear,
this.selectedEndYear,
)
.subscribe({
next: (res) => {
this.patents = res.patents;
this.total = res.total;
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
},
});
}
onSearchInput(event: Event): void {
this.searchSubject.next((event.target as HTMLInputElement).value);
}
clearSearch(): void {
this.searchTerm = '';
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
setFilterFromChip(event: any): void {
const val = event.value;
this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all';
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
setSortDirection(direction: string): void {
this.sortDirection = direction;
this.loadPatents();
this.updateQueryParams();
}
handlePageChange(event: PageEvent): void {
this.page = event.pageIndex;
this.pageSize = event.pageSize;
this.loadPatents();
this.updateQueryParams();
}
openPatent(patent: PatentEntry): void {
this.router.navigate(['/patent', patent.patent_id]);
}
selectPatent(patent: PatentEntry): void {
this.selectedPatent = patent;
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.showDetail = false;
this.selectedPatent = null;
this.expandedClassificationKeys.clear();
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
search: this.searchTerm || null,
page: this.page,
size: this.pageSize,
source: this.activeFilter === 'all' ? null : this.activeFilter,
sort_direction: this.sortDirection,
year_from: this.selectedStartYear !== this.minYear ? this.selectedStartYear : null,
year_to: this.selectedEndYear !== this.maxYear ? this.selectedEndYear : null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
formatDate(date: string | null): string {
if (!date) return '-';
const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
const parsed = new Date(d);
if (isNaN(parsed.getTime())) return date;
return new Intl.DateTimeFormat('de-DE').format(parsed);
}
getPublicationStageLabel(patent: PatentEntry): string | null {
return patent.kind ?? patent.application_type ?? null;
}
getPatentMetadataRows(patent: PatentEntry) {
const rows: { label: string; value: string; variant?: 'source' }[] = [];
rows.push({ label: 'Quelle', value: patent.source, variant: 'source' });
rows.push({ label: 'Patent-Nr.', value: patent.patent_id });
if (patent.publication_date)
rows.push({ label: 'Veröffentlichungsdatum', value: this.formatDate(patent.publication_date) });
if (patent.application_number)
rows.push({ label: 'Anmeldungsnummer', value: patent.application_number });
if (patent.application_date)
rows.push({ label: 'Anmeldedatum', value: this.formatDate(patent.application_date) });
const stage = this.getPublicationStageLabel(patent);
if (stage)
rows.push({ label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp', value: this.formatMetadataLabel(stage) });
if (patent.number_of_claims != null)
rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
if (patent.status)
rows.push({ label: 'Status', value: this.formatMetadataLabel(patent.status) });
return rows;
}
private formatMetadataLabel(value: string): string {
return value.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
}
getClassificationCards(
entries: IpcClassification[] | undefined,
system: ClassificationSystem,
): ClassificationCard[] {
if (!entries?.length) return [];
const merged = new Map<string, ClassificationCard>();
for (const entry of entries) {
const card = this.buildClassificationCard(entry, system);
const mergeKey = card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const s of card.symbols) {
if (!existing.symbols.includes(s)) existing.symbols.push(s);
}
continue;
}
merged.set(mergeKey, card);
}
return [...merged.values()];
}
toggleClassificationExpanded(key: string): void {
this.expandedClassificationKeys.has(key)
? this.expandedClassificationKeys.delete(key)
: this.expandedClassificationKeys.add(key);
}
isClassificationExpanded(key: string): boolean {
return this.expandedClassificationKeys.has(key);
}
isLongDescription(text: string | null): boolean {
return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
}
getDescriptionPreview(text: string | null): string {
if (!text) return '';
return text.length <= DESCRIPTION_PREVIEW_LENGTH
? text
: `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
}
private buildClassificationCard(entry: IpcClassification, system: ClassificationSystem): ClassificationCard {
const level = this.getClassificationLevel(entry);
const primaryDescription = this.extractDescriptionText(entry[level.field]);
return {
key: `${system}-${entry.symbol}`,
symbols: [entry.symbol],
system,
levelLabel: level.label,
primaryDescription,
hierarchy: this.buildHierarchyRows(entry, primaryDescription),
sectionName: entry.section ?? null,
};
}
topicColor(topic: OpenAlexTopicTag): string {
return topicHierarchyColor({
id: topic.topic_id,
name: topic.topic_display_name,
field_name: topic.field_name,
domain_name: topic.domain_name,
});
}
sectionColor(card: ClassificationCard): string {
return topicHierarchyColor({ field_name: card.sectionName });
}
private getClassificationLevel(entry: IpcClassification): { label: string; field: keyof IpcClassification } {
if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };
if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' };
if (entry.section) return { label: 'Sektion', field: 'section' };
return { label: 'Code', field: 'symbol' };
}
private buildHierarchyRows(entry: IpcClassification, primaryDescription: string | null) {
const rows: { label: string; value: string }[] = [];
const seen = new Set<string>();
const addRow = (label: string, raw: string | null) => {
const value = this.extractDescriptionText(raw);
if (!value) return;
const norm = value.toLocaleLowerCase('en');
if (seen.has(norm) || norm === primaryDescription?.toLocaleLowerCase('en')) return;
seen.add(norm);
rows.push({ label, value });
};
addRow('Sektion', entry.section ?? null);
addRow('Klasse', entry.class ?? null);
addRow('Unterklasse', entry.subclass ?? null);
return rows;
}
private extractDescriptionText(value: string | null | undefined): string | null {
if (!value?.trim()) return null;
const text = value.includes(' - ') ? value.split(' - ').slice(1).join(' - ').trim() : value.trim();
if (!text) return null;
const first = text.split(/[;|]/)[0]?.trim() ?? text;
return first === first.toUpperCase() ? first.charAt(0) + first.slice(1).toLowerCase() : first;
}
}