From 29c954227fd468c9dc520f65172306d6cefcea24 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 26 Jun 2026 12:05:00 +0200 Subject: [PATCH 01/41] use shared topic chips in person card --- .../main/inse/models/openalex/work_topic.py | 4 +- webapp/src/app/api/model/workTopic.ts | 1 + .../person-card/person-card.component.html | 23 ++++---- .../person-card/person-card.component.scss | 53 ++++--------------- .../person-card/person-card.component.ts | 33 ++++++++---- .../ui/topic-chip/topic-chip.component.scss | 1 + 6 files changed, 51 insertions(+), 64 deletions(-) diff --git a/service/src/main/inse/models/openalex/work_topic.py b/service/src/main/inse/models/openalex/work_topic.py index c4c6fce6..e780d369 100644 --- a/service/src/main/inse/models/openalex/work_topic.py +++ b/service/src/main/inse/models/openalex/work_topic.py @@ -33,11 +33,12 @@ class WorkTopic(BaseModel): """ # noqa: E501 id: Optional[StrictStr] = None display_name: Optional[StrictStr] = None + description: Optional[StrictStr] = None score: Optional[Union[StrictFloat, StrictInt]] = None subfield: Optional[WorkTopicSubfield] = None var_field: Optional[WorkTopicField] = Field(default=None, alias="field") domain: Optional[WorkTopicDomain] = None - __properties: ClassVar[List[str]] = ["id", "display_name", "score", "subfield", "field", "domain"] + __properties: ClassVar[List[str]] = ["id", "display_name", "description", "score", "subfield", "field", "domain"] model_config = ConfigDict( validate_by_name=True, @@ -101,6 +102,7 @@ class WorkTopic(BaseModel): _obj = cls.model_validate({ "id": obj.get("id"), "display_name": obj.get("display_name"), + "description": obj.get("description"), "score": obj.get("score"), "subfield": WorkTopicSubfield.from_dict(obj["subfield"]) if obj.get("subfield") is not None else None, "field": WorkTopicField.from_dict(obj["field"]) if obj.get("field") is not None else None, diff --git a/webapp/src/app/api/model/workTopic.ts b/webapp/src/app/api/model/workTopic.ts index 4b326824..4b365f33 100644 --- a/webapp/src/app/api/model/workTopic.ts +++ b/webapp/src/app/api/model/workTopic.ts @@ -18,6 +18,7 @@ import { WorkTopicField } from './workTopicField'; export interface WorkTopic { id?: string | null; display_name?: string | null; + description?: string | null; score?: Score | null; subfield?: WorkTopicSubfield | null; field?: WorkTopicField | null; diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index e07bb800..3522a567 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -98,18 +98,19 @@
@for (topic of topics(); track topic.id) { - + class="person-topic-chip" + size="mini" + [label]="topic.display_name || ''" + [description]="topic.description" + [subfieldName]="topic.subfield?.display_name" + [fieldName]="topic.field?.display_name" + [domainName]="topic.domain?.display_name" + [color]="getTopicColor(topic)" + [active]="isTopicSelected(topic)" + (chipClick)="handleTopicClick(topic)"> + }
diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index 5dd6b14c..bb40d858 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -246,55 +246,22 @@ .topic-row { display: flex; flex-wrap: wrap; - gap: 4px; + gap: 5px; } -.topic-tag { - background: var(--sg-surface-soft); - border: 1px solid var(--sg-border); - color: var(--sg-text-muted); - font-size: 10px; - font-weight: 600; - padding: 2px 6px; - border-radius: 4px; - cursor: pointer; - transition: all 0.2s ease; +app-topic-chip.person-topic-chip { max-width: 100%; +} + +:host ::ng-deep app-topic-chip.person-topic-chip .topic-chip__button { + max-width: 100%; +} + +:host ::ng-deep app-topic-chip.person-topic-chip .topic-chip__label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - box-sizing: border-box; - margin: 0; - line-height: normal; - font-family: inherit; - display: inline-flex; - align-items: center; - - &:hover, - &:focus-visible { - background: var(--sg-primary-soft); - border-color: var(--sg-primary); - color: var(--sg-primary); - outline: none; - box-shadow: - 0 0 0 2px var(--sg-background), - 0 0 0 4px var(--sg-primary); - } - - &.active { - background: var(--sg-primary-soft); - border-color: var(--sg-primary); - color: var(--sg-primary); - font-weight: 700; - box-shadow: 0 0 0 1.5px var(--sg-primary); - - &:hover, - &:focus-visible { - box-shadow: - 0 0 0 2px var(--sg-background), - 0 0 0 4px var(--sg-primary); - } - } + overflow-wrap: normal; } .card-footer { diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 02e5a109..a9ad0e50 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -5,6 +5,8 @@ import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; import { SkTextDirective } from '../../custom-directives/sk-text.directive'; +import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; +import { topicHierarchyColor } from '../../shared/utils/topic-colors'; @Component({ selector: 'app-person-card', @@ -15,6 +17,7 @@ import { SkTextDirective } from '../../custom-directives/sk-text.directive'; MatIconModule, SkTextDirective, MatTooltipModule, + TopicChipComponent, ], templateUrl: './person-card.component.html', styleUrl: './person-card.component.scss', @@ -117,17 +120,29 @@ export class PersonCardComponent { return 'possible'; } - getTopicTooltip(topic: WorkTopic): string { - const parts: string[] = []; - if (topic.domain?.display_name) parts.push(topic.domain.display_name); - if (topic.field?.display_name) parts.push(topic.field.display_name); - if (topic.subfield?.display_name) parts.push(topic.subfield.display_name); + isTopicSelected(topic: WorkTopic): boolean { + return this.selectedTopics().has(topic.display_name || ''); + } - const path = parts.join(' - '); - if (topic.display_name) { - return path ? `${topic.display_name}\n(${path})` : topic.display_name; + getTopicColor(topic: WorkTopic): string { + return topicHierarchyColor({ + id: topic.id, + name: topic.display_name, + field_id: topic.field?.id, + field_name: topic.field?.display_name, + domain_id: topic.domain?.id, + domain_name: topic.domain?.display_name, + }); + } + + handleTopicClick(topic: WorkTopic): void { + const topicName = topic.display_name || ''; + + if (!topicName) { + return; } - return path; + + this.topicClick.emit(topicName); } getCareerStageTooltip(careerStage: string): string { diff --git a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss index e9d57cd5..fb757f9d 100644 --- a/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss +++ b/webapp/src/app/shared/ui/topic-chip/topic-chip.component.scss @@ -67,6 +67,7 @@ :host(.topic-chip--active.topic-chip--mini) .topic-chip__button { background: color-mix(in srgb, var(--topic-color) 24%, #ffffff); color: var(--topic-text); + box-shadow: 0 0 0 1.5px var(--topic-color); } .topic-chip__label { From 309fecf0086833c3ef1923ce6923688c266d7860 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 26 Jun 2026 13:35:06 +0200 Subject: [PATCH 02/41] use topic chips for active topic filters --- .../custom-directives/sk-text.directive.ts | 14 +++++ .../person-list/person-list.component.html | 51 +++++++++++++---- .../person-list/person-list.component.scss | 39 ++++++++++++- .../person-list/person-list.component.ts | 57 ++++++++++++++++++- 4 files changed, 148 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/custom-directives/sk-text.directive.ts b/webapp/src/app/custom-directives/sk-text.directive.ts index ade9c10b..e7173238 100644 --- a/webapp/src/app/custom-directives/sk-text.directive.ts +++ b/webapp/src/app/custom-directives/sk-text.directive.ts @@ -35,6 +35,7 @@ export class SkTextDirective implements OnChanges { // measure natural width before blanking text const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60); const height = 20; + this.renderer.addClass(el, 'sk-text-loading'); this.renderer.setStyle(el, 'color', 'transparent'); this.renderer.setStyle( el, @@ -47,10 +48,17 @@ export class SkTextDirective implements OnChanges { this.renderer.setStyle(el, 'min-width', `${width}px`); this.renderer.setStyle(el, 'max-height', `${height}px`); this.renderer.setStyle(el, 'display', 'inline-block'); + this.renderer.setStyle(el, 'overflow', 'hidden'); + this.renderer.setStyle(el, 'pointer-events', 'none'); + + Array.from(el.children).forEach((child) => { + this.renderer.setStyle(child, 'visibility', 'hidden'); + }); } private hideSkeleton() { const el: HTMLElement = this.el.nativeElement; + this.renderer.removeClass(el, 'sk-text-loading'); this.renderer.removeStyle(el, 'color'); this.renderer.removeStyle(el, 'background'); this.renderer.removeStyle(el, 'background-size'); @@ -59,5 +67,11 @@ export class SkTextDirective implements OnChanges { this.renderer.removeStyle(el, 'min-width'); this.renderer.removeStyle(el, 'max-height'); this.renderer.removeStyle(el, 'display'); + this.renderer.removeStyle(el, 'overflow'); + this.renderer.removeStyle(el, 'pointer-events'); + + Array.from(el.children).forEach((child) => { + this.renderer.removeStyle(child, 'visibility'); + }); } } diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 3dba668f..e3d4fcc8 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -32,16 +32,47 @@
Aktive Filter:
- @for (filter of activeFilters; track filter.value) { - - {{ filter.label }} - - + @for ( + filter of activeFilters; + track filter.category + filter.value + ) { + @if (filter.category === 'topic') { + + Thema: + + + + + } @else { + + {{ filter.label }} + + + } } - + matTooltipPosition="above" + (click)="toggleSubfield(group, item)"> {{ item.name }} - +
diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.scss b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.scss index fa9fca76..666ca903 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.scss +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.scss @@ -110,11 +110,39 @@ background: #fbfdff; } +.topic-legend-group-active { + border-color: var(--legend-color, var(--topic-legend-accent)); + background: color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 10%, + #fbfdff + ); + box-shadow: + inset 0 0 0 1px + color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 55%, + transparent + ), + 0 0 0 2px + color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 22%, + transparent + ); +} + .topic-legend-field { flex: 0 1 auto; min-width: 0; gap: 5px; + padding: 2px 4px; + appearance: none; + border: 0; + border-radius: 999px; + background: transparent; color: #07163d; + font-family: inherit; font-size: 11px; font-weight: 800; line-height: 1.2; @@ -143,13 +171,87 @@ } .topic-legend-item { + display: inline-flex; + align-items: center; + padding: 2px 4px; + appearance: none; + border: 0; + border-radius: 999px; + background: transparent; color: #53617e; + font-family: inherit; font-size: 11px; font-weight: 600; line-height: 1.25; cursor: help; } +.topic-legend-selectable { + .topic-legend-field, + .topic-legend-item { + cursor: pointer; + } + + .topic-legend-field:hover, + .topic-legend-item:hover { + background: color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 8%, + #ffffff + ); + } +} + +.topic-legend-field:focus-visible, +.topic-legend-item:focus-visible { + outline: 2px solid var(--topic-legend-accent); + outline-offset: 2px; +} + +.topic-legend-entry-active { + background: color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 24%, + #ffffff + ); + box-shadow: + inset 0 0 0 1px + color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 75%, + transparent + ), + 0 1px 3px rgba(15, 23, 42, 0.12); +} + +.topic-legend-field.topic-legend-entry-active { + color: color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 34%, + #07163d + ); +} + +.topic-legend-field.topic-legend-entry-active .topic-legend-dot { + box-shadow: + 0 0 0 2px #ffffff, + 0 0 0 4px + color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 82%, + transparent + ); +} + +.topic-legend-item.topic-legend-entry-active { + color: color-mix( + in srgb, + var(--legend-color, var(--topic-legend-accent)) 34%, + #07163d + ); + font-weight: 800; +} + .topic-legend-more-toggle { flex: 0 0 auto; padding: 0; diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts index 171ac204..e28a0311 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.ts @@ -2,7 +2,11 @@ import { CommonModule } from '@angular/common'; import { Component, EventEmitter, Input, Output } from '@angular/core'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; -import { TopicLegendGroup, TopicLegendItem } from '../../utils/topic-legend'; +import { + TopicLegendGroup, + TopicLegendItem, + TopicLegendSubfieldSelection, +} from '../../utils/topic-legend'; export type TopicLegendVariant = 'default' | 'compact'; @@ -24,9 +28,14 @@ export class TopicLegendComponent { @Input() showVisibilityToggle = true; @Input() collapsedGroupLimit = 3; @Input() variant: TopicLegendVariant = 'default'; + @Input() selectable = false; + @Input() activeFieldIds: ReadonlySet | readonly string[] = []; + @Input() activeSubfieldIds: ReadonlySet | readonly string[] = []; @Output() visibleChange = new EventEmitter(); @Output() expandedChange = new EventEmitter(); + @Output() fieldToggle = new EventEmitter(); + @Output() subfieldToggle = new EventEmitter(); get hasGroups(): boolean { return this.groups.length > 0; @@ -66,6 +75,37 @@ export class TopicLegendComponent { this.expandedChange.emit(!this.expanded); } + toggleField(group: TopicLegendGroup): void { + if (!this.selectable) { + return; + } + + this.fieldToggle.emit(group); + } + + toggleSubfield(group: TopicLegendGroup, item: TopicLegendItem): void { + if (!this.selectable) { + return; + } + + this.subfieldToggle.emit({ group, item }); + } + + isFieldActive(group: TopicLegendGroup): boolean { + return this.isActiveLegendId(this.activeFieldIds, group.id); + } + + isSubfieldActive(item: TopicLegendItem): boolean { + return this.isActiveLegendId(this.activeSubfieldIds, item.id); + } + + isGroupActive(group: TopicLegendGroup): boolean { + return ( + this.isFieldActive(group) || + group.items.some((item) => this.isSubfieldActive(item)) + ); + } + trackByGroup(_: number, group: TopicLegendGroup): string { return group.id; } @@ -73,4 +113,15 @@ export class TopicLegendComponent { trackByItem(_: number, item: TopicLegendItem): string { return item.id; } + + private isActiveLegendId( + activeIds: ReadonlySet | readonly string[], + id: string, + ): boolean { + if ('has' in activeIds) { + return activeIds.has(id); + } + + return activeIds.includes(id); + } } diff --git a/webapp/src/app/shared/utils/topic-legend.ts b/webapp/src/app/shared/utils/topic-legend.ts index a54779c3..d297cba3 100644 --- a/webapp/src/app/shared/utils/topic-legend.ts +++ b/webapp/src/app/shared/utils/topic-legend.ts @@ -26,6 +26,40 @@ export interface TopicLegendGroup { items: TopicLegendItem[]; } +export interface TopicLegendSubfieldSelection { + group: TopicLegendGroup; + item: TopicLegendItem; +} + +export function getTopicLegendFieldId(topic: TopicLegendTopic): string { + const fieldName = normalizeLegendValue(topic.field_name) ?? 'Ohne Fachgebiet'; + + return topic.field_id ?? normalizeLegendKey(fieldName); +} + +export function getTopicLegendSubfieldId(topic: TopicLegendTopic): string { + const subfieldName = normalizeLegendValue(topic.subfield_name); + + return ( + topic.subfield_id ?? (subfieldName ? normalizeLegendKey(subfieldName) : '') + ); +} + +export function toggleTopicLegendSelection( + currentSelection: ReadonlySet, + id: string, +): Set { + const nextSelection = new Set(currentSelection); + + if (nextSelection.has(id)) { + nextSelection.delete(id); + return nextSelection; + } + + nextSelection.add(id); + return nextSelection; +} + export function buildTopicLegendGroups( topics: readonly TopicLegendTopic[], ): TopicLegendGroup[] { @@ -47,8 +81,8 @@ export function buildTopicLegendGroups( normalizeLegendValue(topic.domain_description) ?? ''; const subfieldDescription = normalizeLegendValue(topic.subfield_description) ?? ''; - const fieldKey = topic.field_id ?? normalizeLegendKey(fieldName); - const subfieldKey = topic.subfield_id ?? normalizeLegendKey(subfieldName); + const fieldKey = getTopicLegendFieldId(topic); + const subfieldKey = getTopicLegendSubfieldId(topic); if (!groups.has(fieldKey)) { groups.set(fieldKey, { From f2cf83f63b34ebee7d63d75968d257bbb831d871 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 26 Jun 2026 14:16:56 +0200 Subject: [PATCH 04/41] topic-legend: select fields and subfields separately --- .../person-interesting.component.ts | 24 +++++++---- .../research-timeline.component.ts | 19 ++++++--- .../topic-legend/topic-legend.component.html | 2 +- .../ui/topic-legend/topic-legend.component.ts | 9 +---- webapp/src/app/shared/utils/topic-legend.ts | 40 +++++++++++++++++++ 5 files changed, 72 insertions(+), 22 deletions(-) diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.ts b/webapp/src/app/modules/person-interesting/person-interesting.component.ts index ced9f9d0..a5f690c2 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.ts +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.ts @@ -23,7 +23,8 @@ import { getTopicLegendSubfieldId, TopicLegendGroup, TopicLegendSubfieldSelection, - toggleTopicLegendSelection, + toggleTopicLegendFieldSelection, + toggleTopicLegendSubfieldSelection, } from '../../shared/utils/topic-legend'; interface InterestTag { @@ -154,18 +155,25 @@ export class PersonInterestingComponent implements OnInit { } onLegendFieldToggle(group: TopicLegendGroup): void { - this.activeLegendFieldIds.set( - toggleTopicLegendSelection(this.activeLegendFieldIds(), group.id), + const selection = toggleTopicLegendFieldSelection( + this.activeLegendFieldIds(), + this.activeLegendSubfieldIds(), + group, ); + + this.activeLegendFieldIds.set(selection.fieldIds); + this.activeLegendSubfieldIds.set(selection.subfieldIds); } onLegendSubfieldToggle(selection: TopicLegendSubfieldSelection): void { - this.activeLegendSubfieldIds.set( - toggleTopicLegendSelection( - this.activeLegendSubfieldIds(), - selection.item.id, - ), + const nextSelection = toggleTopicLegendSubfieldSelection( + this.activeLegendFieldIds(), + this.activeLegendSubfieldIds(), + selection, ); + + this.activeLegendFieldIds.set(nextSelection.fieldIds); + this.activeLegendSubfieldIds.set(nextSelection.subfieldIds); } isTagActive(tag: InterestTag): boolean { diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts index 09392acc..cd0f382f 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.ts @@ -21,7 +21,8 @@ import { getTopicLegendSubfieldId, TopicLegendGroup, TopicLegendSubfieldSelection, - toggleTopicLegendSelection, + toggleTopicLegendFieldSelection, + toggleTopicLegendSubfieldSelection, } from '../../../../shared/utils/topic-legend'; import { buildTopicHierarchyTooltip } from '../../../../shared/utils/topic-tooltip'; @@ -430,17 +431,25 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked { } onLegendFieldToggle(group: TopicLegendGroup): void { - this.activeLegendFieldIds = toggleTopicLegendSelection( + const selection = toggleTopicLegendFieldSelection( this.activeLegendFieldIds, - group.id, + this.activeLegendSubfieldIds, + group, ); + + this.activeLegendFieldIds = selection.fieldIds; + this.activeLegendSubfieldIds = selection.subfieldIds; } onLegendSubfieldToggle(selection: TopicLegendSubfieldSelection): void { - this.activeLegendSubfieldIds = toggleTopicLegendSelection( + const nextSelection = toggleTopicLegendSubfieldSelection( + this.activeLegendFieldIds, this.activeLegendSubfieldIds, - selection.item.id, + selection, ); + + this.activeLegendFieldIds = nextSelection.fieldIds; + this.activeLegendSubfieldIds = nextSelection.subfieldIds; } isTopicActiveByLegend(topic: TopicTimelineTopic): boolean { diff --git a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html index 115a8e3a..330ccc2b 100644 --- a/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html +++ b/webapp/src/app/shared/ui/topic-legend/topic-legend.component.html @@ -47,7 +47,7 @@
@for (topic of publication.topics ?? []; track topic.id) { - - {{ topic.display_name }} - + + } @for (keyword of publication.keywords ?? []; track keyword.id) { {{ keyword.display_name }} diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.scss b/webapp/src/app/modules/publication-detail/publication-detail.component.scss index ae20315b..a5238714 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.scss +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.scss @@ -268,12 +268,6 @@ aside { font-size: 11px; } -.tags .topic-tag { - border-color: #cbd8f1; - background: #f5f8ff; - color: var(--sg-text); -} - .source-list, .compact-list, .link-list { diff --git a/webapp/src/app/modules/publication-detail/publication-detail.component.ts b/webapp/src/app/modules/publication-detail/publication-detail.component.ts index c2850656..4c2e0ce9 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -13,7 +13,10 @@ import { Location as ApiLocation, Work, WorksService, + WorkTopic, } from '../../api'; +import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; +import { topicHierarchyColor } from '../../shared/utils/topic-colors'; interface DetailLink { label: string; @@ -36,6 +39,7 @@ interface InstitutionDetail { MatIconModule, MatProgressSpinnerModule, RouterLink, + TopicChipComponent, UpperCasePipe, ], templateUrl: './publication-detail.component.html', @@ -71,6 +75,17 @@ export class PublicationDetailComponent implements OnInit { this.location.back(); } + getTopicColor(topic: WorkTopic): string { + return topicHierarchyColor({ + id: topic.id, + name: topic.display_name, + field_id: topic.field?.id, + field_name: topic.field?.display_name, + domain_id: topic.domain?.id, + domain_name: topic.domain?.display_name, + }); + } + abstractText(): string | null { const index = this.publication?.abstract_inverted_index; if (!index || typeof index !== 'object') return null; From 495c7d34e5c4d0b2498c26d039b6ead0f1f5cf85 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 29 Jun 2026 23:40:05 +0200 Subject: [PATCH 09/41] timeline legend across full width --- .../research-timeline.component.html | 10 ++++----- .../research-timeline.component.scss | 21 +++++++++---------- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html index a478142c..2d2a289e 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.html @@ -63,6 +63,10 @@
Zeitraum + + {{ selectedStartYear }} bis {{ selectedEndYear }} + +
-
- {{ selectedStartYear }} - bis - {{ selectedEndYear }} -
-
Date: Mon, 29 Jun 2026 23:52:26 +0200 Subject: [PATCH 10/41] Publication overview filter design updated --- .../research-timeline.component.scss | 3 - .../person-publications.component.html | 68 +++++----- .../person-publications.component.scss | 117 ++++++++++++------ .../person-publications.component.ts | 4 - 4 files changed, 122 insertions(+), 70 deletions(-) diff --git a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss index 67d79f6a..98072adf 100644 --- a/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss +++ b/webapp/src/app/modules/person-overview/components/research-timeline/research-timeline.component.scss @@ -73,9 +73,6 @@ grid-row: 2; min-width: 0; - // Standard-Cap (760px) aufheben, damit die Fachgebiete die volle - // Breite nutzen und weniger Zeilen umbrechen; eigener Abstand der - // Legende entfällt, da der Grid-Row-Gap bereits Platz schafft ::ng-deep .topic-legend { width: 100%; margin-top: 0; diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 52dacc28..274b4eb3 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -113,34 +113,46 @@ @if (selectedInstitutions.length || selectedTopics.length) { -
- @for (institution of selectedInstitutions; track institution.id) { - - {{ institution.display_name }} - - - } - @for (topic of selectedTopics; track topic.id) { - - - - - - } +
+ Aktive Filter: +
+ @for (topic of selectedTopics; track topic.id) { + + Thema: + + + + + } + @for (institution of selectedInstitutions; track institution.id) { + + Institution: {{ institution.display_name }} + + + } +
}
diff --git a/webapp/src/app/modules/person-publications/person-publications.component.scss b/webapp/src/app/modules/person-publications/person-publications.component.scss index ead85589..67adb843 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.scss +++ b/webapp/src/app/modules/person-publications/person-publications.component.scss @@ -48,7 +48,10 @@ h2 { .publication-filters .institution-filter, .publication-filters .topic-filter { - width: 320px; + flex: 1 1 200px; + width: auto; + min-width: 180px; + max-width: 320px; } .publication-filters .reset-filter-btn { @@ -115,52 +118,97 @@ h2 { line-height: 1.2; } -.selected-filter-chips { +.active-filters-row { display: flex; + align-items: center; flex-wrap: wrap; - justify-content: flex-end; - gap: 6px; - max-width: 900px; - margin: 0; + gap: 10px; + padding: 8px 16px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface); + font-size: 13px; } -.selected-filter-chip { +.active-filters-label { + font-weight: 600; + color: var(--sg-text-muted); +} + +.chips-container { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; +} + +.filter-chip, +.active-topic-filter { display: inline-flex; align-items: center; - max-width: 320px; - min-height: 26px; - padding: 3px 4px 3px 9px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; +} + +.filter-chip { + gap: 4px; + padding: 2px 8px; + border: 1px solid var(--sg-border-strong); + border-radius: 12px; + background: var(--sg-surface-soft); color: var(--sg-text); font-size: 11px; - line-height: 1.2; + font-weight: 600; } -.selected-filter-chip--topic { - padding: 0; - border: 0; - background: transparent; +.active-topic-filter { + gap: 5px; + max-width: 100%; + padding: 2px 6px 2px 8px; + border: 1px solid var(--sg-border-strong); + border-radius: 12px; + background: var(--sg-surface-soft); } -.selected-filter-chip button { - display: inline-grid; - place-items: center; - width: 20px; - height: 20px; - margin-left: 3px; - padding: 0; - border: 0; - background: transparent; +.active-topic-filter__prefix { + flex: 0 0 auto; color: var(--sg-text-muted); - cursor: pointer; + font-size: 11px; + font-weight: 700; } -.selected-filter-chip mat-icon { - width: 14px; - height: 14px; - font-size: 14px; +app-topic-chip.active-filter-topic-chip { + max-width: min(320px, 48vw); +} + +::ng-deep app-topic-chip.active-filter-topic-chip .topic-chip__button { + min-height: 22px; + padding: 2px 6px; +} + +::ng-deep app-topic-chip.active-filter-topic-chip .topic-chip__label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.filter-chip button, +.active-topic-filter button { + display: flex; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-soft); + cursor: pointer; + + &:hover { + color: var(--sg-text); + } +} + +.filter-chip button mat-icon, +.active-topic-filter button mat-icon { + width: 12px; + height: 12px; + font-size: 12px; } .table-wrap { @@ -335,8 +383,7 @@ mat-paginator { width: 100%; } - .selected-filter-chips { - justify-content: flex-start; - max-width: none; + .active-filters-row { + align-self: stretch; } } diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index e55918ff..32f3f250 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -324,8 +324,6 @@ export class PersonPublicationsComponent implements OnInit { const topic = event.option.value as TopicAutocompleteOption; if (!topic.id) return; if (!this.selectedTopics.some((item) => item.id === topic.id)) { - // Das Autocomplete liefert die Hierarchie nur im hint ("Feld · Subfeld - // · Domain"); für die Chip-Farbe das Fachgebiet daraus ableiten. const enrichedTopic: TopicAutocompleteOption = { ...topic, field_name: topic.field_name ?? this.fieldNameFromHint(topic.hint), @@ -555,8 +553,6 @@ export class PersonPublicationsComponent implements OnInit { const topicNames = this.selectedTopics .map((topic) => topic.display_name) .filter((name): name is string => !!name); - // Index-aligned mit topicIds, damit die Hierarchie-Farbe nach einem - // Reload erhalten bleibt (leerer String = keine Angabe). const topicFields = this.selectedTopics.map( (topic) => topic.field_name ?? '', ); From 5d13b07c73fa13cf4c4fa0b020a347c2a2ecf1f6 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 30 Jun 2026 00:09:37 +0200 Subject: [PATCH 11/41] Add field-based color indicators to person search cards filtering --- .../topic-hierarchy/topic-hierarchy.component.html | 9 ++++++++- .../topic-hierarchy/topic-hierarchy.component.scss | 12 ++++++++++++ .../topic-hierarchy/topic-hierarchy.component.ts | 8 ++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html index 330b076f..3df414de 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.html @@ -67,6 +67,10 @@ matTooltipPosition="above" (focusin)="tooltip.show()" (focusout)="tooltip.hide()"> + {{ topic.name }} {{ @@ -112,7 +116,10 @@ : 'chevron_right' }} - folder + {{ field.name }} diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss index abfa99bc..c42fbac7 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.scss @@ -93,6 +93,18 @@ flex-direction: column; } +.field-dot { + flex: 0 0 auto; + display: inline-block; + vertical-align: middle; + width: 9px; + height: 9px; + margin-right: 7px; + border-radius: 50%; + border: 1px solid rgba(255, 255, 255, 0.85); + box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2); +} + .node-header { display: flex; align-items: center; diff --git a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts index eb7af86a..1877b3c0 100644 --- a/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts +++ b/webapp/src/app/modules/topic-hierarchy/topic-hierarchy.component.ts @@ -6,6 +6,7 @@ import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatRadioModule } from '@angular/material/radio'; import { MatTooltipModule } from '@angular/material/tooltip'; import { TopicsService } from '../../api/api/topics.service'; +import { topicHierarchyColor } from '../../shared/utils/topic-colors'; import { combineLatest, of } from 'rxjs'; import { toObservable } from '@angular/core/rxjs-interop'; import { @@ -39,6 +40,7 @@ interface FlatTopic { id: string; name: string; path: string; + fieldName: string; } @Component({ @@ -120,6 +122,7 @@ export class TopicHierarchyComponent implements OnInit { name: topic.display_name || '', path: parts.length > 0 ? parts.join(' > ') : topic.description || '', + fieldName: topic.field?.display_name || '', }; }); } @@ -151,6 +154,7 @@ export class TopicHierarchyComponent implements OnInit { id: topic.id, name: topic.name, path: `${domain.name} > ${field.name} > ${subfield.name}`, + fieldName: field.name, }); } }); @@ -164,6 +168,10 @@ export class TopicHierarchyComponent implements OnInit { this.searchType.set(type); } + getFieldColor(fieldName: string | null | undefined): string { + return topicHierarchyColor({ field_name: fieldName }); + } + toggleTopic(name: string): void { const nextSelection = new Set(this.selectedTopics()); if (nextSelection.has(name)) { From 95ce3a47fc06624e066261457169140c7dfb0cd1 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 3 Jul 2026 12:21:39 +0200 Subject: [PATCH 12/41] publications overview: make table cells clickable filters with active state --- .../person-publications.component.html | 72 +++++++-- .../person-publications.component.scss | 138 ++++++++++++++++-- .../person-publications.component.ts | 73 ++++++++- 3 files changed, 259 insertions(+), 24 deletions(-) diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 274b4eb3..20b9481c 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -179,7 +179,19 @@ Jahr - {{ publication.publication_year || '-' }} + @if (publication.publication_year) { + + } @else { + - + } @@ -187,9 +199,17 @@ Typ @if (publication.type) { - - {{ publication.type }} - + } @else { - } @@ -199,7 +219,19 @@ Sprache / Quelle - {{ publication.language || '-' }} + @if (publication.language) { + + } @else { + - + } @@ -212,11 +244,33 @@ institution of publicationInstitutions.slice(0, 3); track institution.id ) { - - {{ institution.name }} - + [class.active]="isInstitutionActive(institution.id)" + [matTooltip]="institution.name" + matTooltipPosition="above" + [attr.aria-label]=" + 'Nach Institution ' + institution.name + ' filtern' + " + (click)="filterByInstitution(institution)"> + apartment + {{ institution.name }} + @if (institution.country) { + + {{ + institution.country.toUpperCase() + }} + } + } @empty { - } diff --git a/webapp/src/app/modules/person-publications/person-publications.component.scss b/webapp/src/app/modules/person-publications/person-publications.component.scss index 67adb843..3874f75f 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.scss +++ b/webapp/src/app/modules/person-publications/person-publications.component.scss @@ -267,6 +267,61 @@ a.title:hover { color: rgba(0, 0, 0, 0.54); } +.cell-filter-pill { + display: inline-flex; + align-items: center; + margin: 0; + padding: 3px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: #fff; + color: var(--sg-text); + font-family: inherit; + font-size: 12px; + line-height: 1.2; + cursor: pointer; + transition: all 0.2s ease; + + &:hover, + &:focus-visible { + border-color: var(--sg-primary); + background: var(--sg-surface-soft); + outline: none; + } + + &.active { + border-color: var(--sg-primary); + color: var(--sg-primary); + font-weight: 600; + box-shadow: + 0 0 0 1px #ffffff, + 0 0 0 3px var(--sg-primary); + } +} + +.type-filter-btn { + display: inline-flex; + margin: 0; + padding: 0; + border: 0; + border-radius: 7px; + background: transparent; + cursor: pointer; + transition: box-shadow 0.2s ease; + + &:hover, + &:focus-visible { + outline: none; + box-shadow: 0 0 0 1px var(--sg-primary); + } + + &.active { + box-shadow: + 0 0 0 1px #ffffff, + 0 0 0 3px var(--sg-primary); + } +} + .topic-chips { display: flex; flex-wrap: wrap; @@ -295,31 +350,88 @@ a.title:hover { max-width: 280px; } -.publication-institution-tag, +.publication-institution-tag { + display: inline-flex; + align-items: center; + max-width: 200px; + margin: 0; + padding: 2px 6px; + border: 1px solid var(--sg-primary-border, var(--sg-border)); + border-radius: 4px; + background: var(--sg-primary-soft); + color: var(--sg-primary); + font-family: inherit; + font-size: 10px; + font-weight: 600; + line-height: normal; + cursor: pointer; + transition: all 0.2s ease; + + &:hover, + &:focus-visible { + background: var(--sg-primary); + color: #fff; + border-color: var(--sg-primary); + outline: none; + box-shadow: + 0 0 0 2px var(--sg-background), + 0 0 0 4px var(--sg-primary); + } + + &.active { + border-color: var(--sg-primary); + box-shadow: + 0 0 0 1px #ffffff, + 0 0 0 3px var(--sg-primary); + } + + &.active:hover, + &.active:focus-visible { + background: var(--sg-primary); + color: #fff; + } +} + +.publication-institution-tag .institution-icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-right: 4px; + font-size: 12px; +} + +.publication-institution-tag .institution-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; +} + +.publication-institution-tag .flag-img { + flex-shrink: 0; + margin-left: 6px; + border: 1px solid; +} + +.publication-institution-tag .country-code { + flex-shrink: 0; + margin-left: 2px; + font-size: 9px; +} + .publication-institution-more { display: inline-flex; align-items: center; - max-width: 180px; min-height: 24px; padding: 3px 8px; border: 1px solid var(--sg-border); border-radius: var(--sg-radius-sm); background: #fff; - color: var(--sg-text); + color: var(--sg-text-muted); font-size: 11px; line-height: 1.2; } -.publication-institution-tag { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.publication-institution-more { - color: var(--sg-text-muted); -} - ::ng-deep .mat-mdc-header-cell { color: var(--sg-text-muted); font-size: 12px; diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index 32f3f250..4d9f1fb0 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -25,6 +25,7 @@ import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, @@ -100,6 +101,7 @@ interface PublicationFilterQueryState { MatSelectModule, MatSnackBarModule, MatTableModule, + MatTooltipModule, ReactiveFormsModule, RouterLink, TopicChipComponent, @@ -316,6 +318,67 @@ export class PersonPublicationsComponent implements OnInit { this.applyFilters(); } + filterByInstitution(institution: { id: string; name: string }): void { + if (!institution.id) return; + if (this.selectedInstitutions.some((item) => item.id === institution.id)) { + return; + } + this.selectedInstitutions = [ + ...this.selectedInstitutions, + { id: institution.id, display_name: institution.name }, + ]; + this.applyFilters(); + } + + isInstitutionActive(id: string): boolean { + return !!id && this.selectedInstitutions.some((item) => item.id === id); + } + + toggleYearFilter(year: number): void { + const control = this.filterForm.controls.publicationYears; + const current = control.value; + control.setValue( + current.includes(year) + ? current.filter((value) => value !== year) + : [...current, year], + ); + this.applyFilters(); + } + + toggleTypeFilter(type: string): void { + const control = this.filterForm.controls.types; + const current = control.value; + control.setValue( + current.includes(type) + ? current.filter((value) => value !== type) + : [...current, type], + ); + this.applyFilters(); + } + + toggleLanguageFilter(language: string): void { + const control = this.filterForm.controls.languages; + const current = control.value; + control.setValue( + current.includes(language) + ? current.filter((value) => value !== language) + : [...current, language], + ); + this.applyFilters(); + } + + isYearActive(year: number): boolean { + return this.filterForm.controls.publicationYears.value.includes(year); + } + + isTypeActive(type: string): boolean { + return this.filterForm.controls.types.value.includes(type); + } + + isLanguageActive(language: string): boolean { + return this.filterForm.controls.languages.value.includes(language); + } + displayTopic(option: string | TopicAutocompleteOption): string { return typeof option === 'string' ? option : (option.display_name ?? ''); } @@ -420,8 +483,13 @@ export class PersonPublicationsComponent implements OnInit { return 'info'; } - institutions(publication: Work): Array<{ id: string; name: string }> { - const institutionsById = new Map(); + institutions( + publication: Work, + ): Array<{ id: string; name: string; country: string | null }> { + const institutionsById = new Map< + string, + { id: string; name: string; country: string | null } + >(); for (const authorship of publication.authorships ?? []) { for (const institution of authorship.institutions ?? []) { @@ -430,6 +498,7 @@ export class PersonPublicationsComponent implements OnInit { institutionsById.set(institution.id, { id: institution.id, name: institution.display_name, + country: institution.country_code ?? null, }); } } From 116492baca6e8c22251a6a5133c365367d7953bb Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 3 Jul 2026 13:02:09 +0200 Subject: [PATCH 13/41] person list: style active institution filter as person-card chip --- .../person-list/person-list.component.html | 32 +++++++++++ .../person-list/person-list.component.scss | 55 ++++++++++++++++++- .../person-list/person-list.component.ts | 42 +++++++++++++- 3 files changed, 125 insertions(+), 4 deletions(-) diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index e3d4fcc8..b0ccca88 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -61,6 +61,38 @@ close + } @else if (filter.category === 'institutionName') { + + + apartment + {{ + institutionFilterLabel(filter) + }} + @if (filter.countryCode) { + + {{ + filter.countryCode.toUpperCase() + }} + } + + + } @else { {{ filter.label }} diff --git a/webapp/src/app/modules/person-list/person-list.component.scss b/webapp/src/app/modules/person-list/person-list.component.scss index 92e7225d..7aa6e880 100644 --- a/webapp/src/app/modules/person-list/person-list.component.scss +++ b/webapp/src/app/modules/person-list/person-list.component.scss @@ -165,9 +165,58 @@ app-topic-chip.active-filter-topic-chip { white-space: nowrap; } -// Shared button resets +.active-institution-filter { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; +} + +.filter-institution-chip { + display: inline-flex; + align-items: center; + max-width: min(280px, 46vw); + padding: 2px 6px; + border: 1px solid var(--sg-primary-border, var(--sg-border)); + border-radius: 4px; + background: var(--sg-primary-soft); + color: var(--sg-primary); + font-size: 11px; + font-weight: 600; +} + +.filter-institution-chip__icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-right: 4px; + font-size: 12px; +} + +.filter-institution-chip__name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; +} + +.filter-institution-chip__flag { + flex-shrink: 0; + margin-left: 6px; + border: 1px solid var(--sg-primary-border, var(--sg-border)); + vertical-align: middle; +} + +.filter-institution-chip__country { + flex-shrink: 0; + margin-left: 2px; + font-size: 9px; + white-space: nowrap; +} + .filter-chip button, .active-topic-filter button, +.active-institution-filter button, .clear-topic-search, .clear-all-btn { border: none; @@ -177,6 +226,7 @@ app-topic-chip.active-filter-topic-chip { .filter-chip button, .active-topic-filter button, +.active-institution-filter button, .clear-topic-search { padding: 0; display: flex; @@ -188,7 +238,8 @@ app-topic-chip.active-filter-topic-chip { } .filter-chip button mat-icon, -.active-topic-filter button mat-icon { +.active-topic-filter button mat-icon, +.active-institution-filter button mat-icon { font-size: 12px; width: 12px; height: 12px; diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index c20c0207..d1ad59a8 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -15,6 +15,7 @@ import { ResolverStateService } from '../../shared/services/resolver-state.servi import { CustomAuthor, + DehydratedInstitution, PersonsService, InstitutionsService, WorkTopic, @@ -289,13 +290,18 @@ export class PersonListComponent { this.applySidebarFilters(); } - // Active filters tags row get activeFilters(): Array<{ category: string; value: string; label: string; + countryCode?: string | null; }> { - const list: Array<{ category: string; value: string; label: string }> = []; + const list: Array<{ + category: string; + value: string; + label: string; + countryCode?: string | null; + }> = []; this.selectedTopics().forEach((t) => { list.push({ category: 'topic', value: t, label: `Thema: ${t}` }); }); @@ -309,11 +315,43 @@ export class PersonListComponent { category: 'institutionName', value: this.appliedInstitutionName, label: label, + countryCode: this.findInstitutionCountryCode( + this.appliedInstitutionName, + ), }); } return list; } + institutionFilterLabel(filter: { label: string }): string { + return filter.label.replace(/^Institution:\s*/, ''); + } + + private findInstitutionCountryCode(institutionName: string): string | null { + const normalized = institutionName.trim().toLowerCase(); + if (!normalized) { + return null; + } + + for (const person of this.persons) { + const candidates: Array = [ + ...(person.last_known_institutions ?? []), + ...(person.affiliations ?? []).map((a) => a.institution ?? undefined), + ]; + + for (const inst of candidates) { + if ( + inst?.country_code && + (inst.display_name ?? '').trim().toLowerCase() === normalized + ) { + return inst.country_code; + } + } + } + + return null; + } + removeFilter(filter: { category: string; value: string }): void { if (filter.category === 'topic') { this.selectedTopics.update((set) => { From 6fa5792e5eb5c0b74fd91dcf4ffc9b899356051e Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 3 Jul 2026 13:10:13 +0200 Subject: [PATCH 14/41] publication overview: show institution filter as person-card chip with flag --- .../person-publications.component.html | 22 +++++++- .../person-publications.component.scss | 54 ++++++++++++++++++- .../person-publications.component.ts | 16 ++++++ 3 files changed, 88 insertions(+), 4 deletions(-) diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 20b9481c..375842a1 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -141,8 +141,26 @@ } @for (institution of selectedInstitutions; track institution.id) { - - Institution: {{ institution.display_name }} + @let instCountry = selectedInstitutionCountry(institution); + + + apartment + {{ + institution.display_name + }} + @if (instCountry) { + + {{ + instCountry.toUpperCase() + }} + } + - @if (selectedInstitutions.length || selectedTopics.length) { + @let selectedYears = filterForm.controls.publicationYears.value; + @let selectedTypes = filterForm.controls.types.value; + @let selectedLanguages = filterForm.controls.languages.value; + @if ( + selectedInstitutions.length || + selectedTopics.length || + selectedYears.length || + selectedTypes.length || + selectedLanguages.length + ) {
Aktive Filter:
+ @for (year of selectedYears; track year) { + + + calendar_today + {{ year }} + + + + } + @for (type of selectedTypes; track type) { + + + category + {{ type }} + + + + } + @for (language of selectedLanguages; track language) { + + + translate + {{ + languageLabel(language) + }} + + + + } @for (topic of selectedTopics; track topic.id) { Thema: diff --git a/webapp/src/app/modules/person-publications/person-publications.component.scss b/webapp/src/app/modules/person-publications/person-publications.component.scss index 1f30a182..bf67b546 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.scss +++ b/webapp/src/app/modules/person-publications/person-publications.component.scss @@ -43,7 +43,7 @@ h2 { } .publication-filters mat-form-field { - width: 150px; + width: 175px; } .publication-filters .institution-filter, @@ -77,8 +77,17 @@ h2 { ::ng-deep .publication-filters .mat-mdc-text-field-wrapper { height: 42px; - background: #fff; + background: var(--sg-surface-soft); + border: 1px solid var(--sg-border); border-radius: var(--sg-radius-sm); + transition: + border-color 0.15s, + box-shadow 0.15s; +} + +::ng-deep .publication-filters .mat-focused .mat-mdc-text-field-wrapper { + border-color: var(--sg-primary); + box-shadow: 0 0 0 2px var(--sg-primary-soft); } ::ng-deep .publication-filters .mat-mdc-form-field-infix { @@ -90,7 +99,19 @@ h2 { ::ng-deep .publication-filters .mdc-notched-outline__leading, ::ng-deep .publication-filters .mdc-notched-outline__notch, ::ng-deep .publication-filters .mdc-notched-outline__trailing { - border-color: #d9e2f0; + border: none; +} + +.filter-prefix-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: var(--sg-text-soft); +} + +::ng-deep .publication-filters .mat-mdc-form-field-icon-prefix { + padding: 0 4px 0 10px; + color: var(--sg-text-soft); } ::ng-deep .publication-filters .mat-mdc-select-value, @@ -118,6 +139,44 @@ h2 { line-height: 1.2; } +::ng-deep .select-search { + position: sticky; + top: 0; + z-index: 1; + display: flex; + align-items: center; + gap: 6px; + min-width: 200px; + padding: 8px 12px; + background: var(--sg-surface, #fff); + border-bottom: 1px solid var(--sg-border); +} + +::ng-deep .select-search__icon { + flex-shrink: 0; + width: 16px; + height: 16px; + font-size: 16px; + color: var(--sg-text-soft); +} + +::ng-deep .select-search__input { + flex: 1; + min-width: 0; + border: none; + outline: none; + background: transparent; + color: var(--sg-text); + font-family: inherit; + font-size: 13px; +} + +::ng-deep .select-search__empty { + padding: 10px 14px; + color: var(--sg-text-muted); + font-size: 13px; +} + .active-filters-row { display: flex; align-items: center; @@ -185,7 +244,7 @@ h2 { .filter-institution-chip { display: inline-flex; align-items: center; - max-width: 220px; + max-width: 340px; padding: 2px 6px; border: 1px solid var(--sg-primary-border, var(--sg-border)); border-radius: 4px; @@ -204,10 +263,13 @@ h2 { } .institution-name { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; min-width: 0; + white-space: normal; + overflow-wrap: anywhere; } .flag-img { @@ -223,6 +285,41 @@ h2 { } } +.active-meta-filter { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; +} + +.filter-meta-chip { + display: inline-flex; + align-items: center; + padding: 2px 8px; + border: 1px solid var(--sg-border-strong); + border-radius: 4px; + background: var(--sg-surface-soft); + color: var(--sg-text); + font-size: 11px; + font-weight: 600; +} + +.filter-meta-chip__icon { + flex-shrink: 0; + width: 12px; + height: 12px; + margin-right: 4px; + font-size: 12px; + color: var(--sg-text-soft); +} + +.filter-meta-chip__label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; +} + app-topic-chip.active-filter-topic-chip { max-width: min(320px, 48vw); } @@ -240,7 +337,8 @@ app-topic-chip.active-filter-topic-chip { .filter-chip button, .active-topic-filter button, -.active-institution-filter button { +.active-institution-filter button, +.active-meta-filter button { display: flex; padding: 0; border: 0; @@ -255,7 +353,8 @@ app-topic-chip.active-filter-topic-chip { .filter-chip button mat-icon, .active-topic-filter button mat-icon, -.active-institution-filter button mat-icon { +.active-institution-filter button mat-icon, +.active-meta-filter button mat-icon { width: 12px; height: 12px; font-size: 12px; @@ -397,6 +496,7 @@ table.is-hidden { .institution-tags { display: flex; flex-wrap: wrap; + align-items: flex-start; gap: 6px; max-width: 280px; } @@ -404,7 +504,7 @@ table.is-hidden { .publication-institution-tag { display: inline-flex; align-items: center; - max-width: 200px; + max-width: 100%; margin: 0; padding: 2px 6px; border: 1px solid var(--sg-primary-border, var(--sg-border)); @@ -452,10 +552,13 @@ table.is-hidden { } .publication-institution-tag .institution-name { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; min-width: 0; + white-space: normal; + overflow-wrap: anywhere; } .publication-institution-tag .flag-img { @@ -521,6 +624,17 @@ table.is-hidden { .mat-column-citations { text-align: center; } + + .mat-mdc-header-cell.mat-column-title, + .mat-mdc-header-cell.mat-column-institutions, + .mat-mdc-header-cell.mat-column-topics { + text-align: center; + } + + .mat-mdc-cell:not(:last-child), + .mat-mdc-header-cell:not(:last-child) { + border-right: 1px solid var(--sg-border); + } } mat-paginator { diff --git a/webapp/src/app/modules/person-publications/person-publications.component.ts b/webapp/src/app/modules/person-publications/person-publications.component.ts index d689e672..e0efcbf2 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.ts +++ b/webapp/src/app/modules/person-publications/person-publications.component.ts @@ -139,6 +139,9 @@ export class PersonPublicationsComponent implements OnInit { >('', { nonNullable: true, }); + readonly yearSearchControl = new FormControl('', { nonNullable: true }); + readonly typeSearchControl = new FormControl('', { nonNullable: true }); + readonly languageSearchControl = new FormControl('', { nonNullable: true }); readonly filterForm = new FormGroup({ publicationYears: new FormControl([], { nonNullable: true }), @@ -547,6 +550,68 @@ export class PersonPublicationsComponent implements OnInit { return Array.from(institutionsById.values()); } + yearSelectionSummary(): string { + return this.summarizeSelection( + this.filterForm.controls.publicationYears.value.map((year) => + String(year), + ), + ); + } + + typeSelectionSummary(): string { + return this.summarizeSelection(this.filterForm.controls.types.value); + } + + languageSelectionSummary(): string { + const labels = this.filterForm.controls.languages.value.map( + (value) => + this.languageOptions.find((option) => option.value === value)?.label ?? + value, + ); + return this.summarizeSelection(labels); + } + + private summarizeSelection(labels: string[]): string { + if (labels.length === 0) return ''; + if (labels.length === 1) return labels[0]; + return `+${labels.length}`; + } + + languageLabel(value: string): string { + return ( + this.languageOptions.find((option) => option.value === value)?.label ?? + value + ); + } + + filteredYearOptions(): number[] { + const term = this.yearSearchControl.value.trim(); + if (!term) return this.publicationYearOptions; + return this.publicationYearOptions.filter((year) => + String(year).includes(term), + ); + } + + filteredTypeOptions(): { value: string; label: string }[] { + const term = this.typeSearchControl.value.trim().toLowerCase(); + if (!term) return this.typeOptions; + return this.typeOptions.filter((type) => + type.label.toLowerCase().includes(term), + ); + } + + filteredLanguageOptions(): { value: string; label: string }[] { + const term = this.languageSearchControl.value.trim().toLowerCase(); + if (!term) return this.languageOptions; + return this.languageOptions.filter((language) => + language.label.toLowerCase().includes(term), + ); + } + + focusSelectSearch(input: HTMLInputElement): void { + setTimeout(() => input.focus()); + } + private filters() { return { publicationYears: this.filterForm.controls.publicationYears.value, From c1cba4bd4cace89e96a4baaafd60d59f0c494454 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 3 Jul 2026 15:54:24 +0200 Subject: [PATCH 20/41] person cards: limit topic display if too large --- webapp/src/app/modules/person-card/person-card.component.scss | 3 +++ 1 file changed, 3 insertions(+) diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index 582fca20..c8b2db5a 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -263,6 +263,7 @@ } app-topic-chip.person-topic-chip { + min-width: 0; max-width: 100%; } @@ -271,6 +272,8 @@ app-topic-chip.person-topic-chip { } :host ::ng-deep app-topic-chip.person-topic-chip .topic-chip__label { + justify-self: stretch; + min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; From 1297f85124a914cccfbfa1bd3c99db3a2a373adf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 3 Jul 2026 16:56:17 +0200 Subject: [PATCH 21/41] feat(auth): started auth restructure --- webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/auth.service.ts | 10 +- webapp/src/app/api/model/models.ts | 1 + webapp/src/app/api/model/otkResponse.ts | 22 + webapp/src/app/app.routes.ts | 10 + .../app/modules/account/account.component.ts | 25 +- .../modules/accounts/accounts.component.html | 189 +++----- .../modules/accounts/accounts.component.scss | 5 + .../modules/accounts/accounts.component.ts | 122 ++++- .../modules/app-login/app-login.component.ts | 137 +++--- .../app-register/app-register.component.ts | 36 +- .../app/resolvers/accounts-page.resolver.ts | 19 + webapp/src/app/shared/guards/admin.guard.ts | 51 +- .../app/shared/guards/super-admin.guard.ts | 49 +- webapp/src/app/shared/guards/user.guard.ts | 37 +- .../authentication.interceptor.ts | 125 +++-- .../app/shared/services/credential.service.ts | 447 ++++++++---------- .../ui/app-layout/app-layout.component.html | 4 +- .../ui/app-layout/app-layout.component.ts | 27 +- .../ui/app-menu/app-menu.component.html | 14 +- .../shared/ui/app-menu/app-menu.component.ts | 12 +- 21 files changed, 664 insertions(+), 679 deletions(-) create mode 100644 webapp/src/app/api/model/otkResponse.ts create mode 100644 webapp/src/app/resolvers/accounts-page.resolver.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index f9eb4ffa..bc570cfd 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -139,6 +139,7 @@ model/newsArticleDetail.ts model/newsPage.ts model/openAccess.ts model/organizationPage.ts +model/otkResponse.ts model/patentEntry.ts model/patentsByAuthorResponse.ts model/personBio.ts diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 6beb60cc..ef111294 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -41,6 +41,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco // @ts-ignore import { LoginResponse } from '../model/loginResponse'; // @ts-ignore +import { OtkResponse } from '../model/otkResponse'; +// @ts-ignore import { UpdateAccountRequest } from '../model/updateAccountRequest'; // @ts-ignore @@ -738,9 +740,9 @@ export class AuthService extends BaseService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (bodyRequestOtk === null || bodyRequestOtk === undefined) { throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.'); @@ -782,7 +784,7 @@ export class AuthService extends BaseService { let localVarPath = `/api/auth/v2/request-otk`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, + return this.httpClient.request('post', `${basePath}${localVarPath}`, { context: localVarHttpContext, body: bodyRequestOtk, diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 6876bbeb..6d485f3d 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -115,6 +115,7 @@ export * from './newsArticleDetail'; export * from './newsPage'; export * from './openAccess'; export * from './organizationPage'; +export * from './otkResponse'; export * from './patentEntry'; export * from './patentsByAuthorResponse'; export * from './personBio'; diff --git a/webapp/src/app/api/model/otkResponse.ts b/webapp/src/app/api/model/otkResponse.ts new file mode 100644 index 00000000..7d956289 --- /dev/null +++ b/webapp/src/app/api/model/otkResponse.ts @@ -0,0 +1,22 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface OtkResponse { + /** + * The status of the one-time code (OTC) request. + */ + status: string; + /** + * The unique identifier of the account for which the OTC was requested. + */ + account_id: string; +} + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index efc1388d..c515ba70 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -21,6 +21,7 @@ import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu- import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'; import { publicationResolver } from './resolvers/publication-resolver'; import { accountResolver } from './resolvers/account.resolver'; +import { accountsPageResolver } from './resolvers/accounts-page.resolver'; export const routes: Routes = [ { @@ -107,6 +108,15 @@ export const routes: Routes = [ import('./modules/accounts/accounts.component').then( (mod) => mod.AccountsComponent, ), + resolve: { + accountPage: accountsPageResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = ['page', 'size', 'search', 'organization_id']; + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, }, { path: 'organizations', diff --git a/webapp/src/app/modules/account/account.component.ts b/webapp/src/app/modules/account/account.component.ts index 8b3eec70..647e5a99 100644 --- a/webapp/src/app/modules/account/account.component.ts +++ b/webapp/src/app/modules/account/account.component.ts @@ -145,18 +145,19 @@ export class AccountComponent { if (!oldPassword || !newPassword) { return; } - this._credentialService - .changePassword(oldPassword, newPassword) - .subscribe({ - error: (error) => { - console.error('Error changing password:', error); - this._snackBar.open( - 'Das alte Passwort ist nicht korrekt. Bitte versuchen Sie es erneut.', - 'OK', - { duration: 7000 }, - ); - }, - }); + try { + await this._credentialService.changePassword( + oldPassword, + newPassword, + ); + } catch (error) { + console.error('Error changing password:', error); + this._snackBar.open( + 'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.', + 'OK', + { duration: 7000 }, + ); + } }, }, }, diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 6a5fdb83..f8b2263f 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -14,133 +14,64 @@ -
- - Name oder E-Mail - - - - @if (credentialService.isEffectiveSuperAdmin()) { - - Organisation - - Alle Organisationen - @for (organization of organizations; track organization.id) { - - {{ organization.name }} - - } - - - } - -
- - -
-
- -
-
- {{ total }} Accounts - @if (isLoading) { - Wird geladen... - } -
- -
- - - - - - - - - - - - - @for (account of accounts; track account.id) { - - - - - - - - - } @empty { - - - - } - -
NameE-MailOrganisationRolleStatusAktionen
- - {{ account.email }}{{ account.organization_name }} - {{ account.role | role }} - - - {{ account.deleted ? 'deleted' : 'active' }} - - -
- - - -
-
Keine Accounts gefunden.
-
- - -
+
+ + +
+ + + + + + + + + {{ row.role | role }} + + + + + {{ row.deleted ? 'deleted' : 'active' }} + + + + +
+ + + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component.scss b/webapp/src/app/modules/accounts/accounts.component.scss index 53149e49..d06f840b 100644 --- a/webapp/src/app/modules/accounts/accounts.component.scss +++ b/webapp/src/app/modules/accounts/accounts.component.scss @@ -145,3 +145,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index f02fa6da..17b62579 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -1,5 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit, inject } from '@angular/core'; +import { + Component, + OnInit, + TemplateRef, + effect, + inject, + input, + viewChild, +} from '@angular/core'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; @@ -10,9 +18,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { finalize } from 'rxjs'; -import { AccountManagementService } from '../../shared/services/account-management.service'; -import type { - AccountProfile, +import { + AccountManagementService, AccountRole, OrganizationProfile, } from '../../shared/services/account-management.service'; @@ -22,6 +29,18 @@ import type { AccountDialogResult, } from './account-dialog.component'; import { RolePipe } from '../../shared/pipes/role.pipe'; +import { + GenericColumn, + DataTableComponent, +} from '../../shared/ui/data-table/data-table.component'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { MatCardModule } from '@angular/material/card'; +import { AccountPage, AccountProfile } from '../../api'; @Component({ selector: 'app-accounts', @@ -36,6 +55,11 @@ import { RolePipe } from '../../shared/pipes/role.pipe'; MatSnackBarModule, MatDialogModule, RolePipe, + DataTableComponent, + QueryParamPaginatorComponent, + QueryParamInputComponent, + QueryParamSelectorComponent, + MatCardModule, ], templateUrl: './accounts.component.html', styleUrl: './accounts.component.scss', @@ -67,9 +91,63 @@ export class AccountsComponent implements OnInit { organizationId: new FormControl(''), }); + accountColumns: GenericColumn[] = []; + accountRoleTmp = viewChild.required>('accountRoleTmp'); + accountStatusTmp = viewChild.required>('accountStatusTmp'); + accountActionsTmp = viewChild.required>('accountActionsTmp'); + + selectorOptions: SelectorOption[] = []; + + accountPage = input.required(); + + constructor() { + effect(() => { + console.log('accountPage changed:', this.accountPage()); + }); + } + ngOnInit(): void { this.loadOrganizations(); this.loadAccounts(); + this.accountColumns = [ + { + id: 'name', + header: 'Name', + type: 'accessor', + accessorKey: 'name', + }, + { + id: 'email', + header: 'E-Mail', + type: 'accessor', + accessorKey: 'email', + }, + { + id: 'organization_name', + header: 'Organisation', + type: 'accessor', + accessorKey: 'organization_name', + }, + { + id: 'role', + header: 'Rolle', + type: 'accessor', + accessorKey: 'role', + cellTemplate: this.accountRoleTmp(), + }, + { + id: 'status', + header: 'Status', + type: 'display', + cellTemplate: this.accountStatusTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.accountActionsTmp(), + }, + ]; } protected loadAccounts(page = this.page): void { @@ -101,6 +179,10 @@ export class AccountsComponent implements OnInit { this.accountService.listOrganizations().subscribe({ next: (organizations) => { this.organizations = organizations; + this.selectorOptions = organizations.map((org) => ({ + value: org.id, + display_name: org.name, + })); }, }); } @@ -199,28 +281,24 @@ export class AccountsComponent implements OnInit { }); } - protected impersonate(account: AccountProfile): void { + protected async impersonate(account: AccountProfile): Promise { if (!this.canImpersonate(account)) { return; } - this.credentialService.impersonateAccount(account.id).subscribe({ - next: () => { - this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { - duration: 4000, - }); - this.router.navigate(['/dashboard']); - }, - error: () => { - this.snackBar.open( - 'Impersonation konnte nicht gestartet werden.', - 'OK', - { - duration: 5000, - }, - ); - }, - }); + try { + await this.credentialService.impersonateAccount(account.id); + this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { + duration: 4000, + }); + this.router.navigate(['/dashboard']); + } catch (error) { + console.error('Impersonation failed:', error); + this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', { + duration: 5000, + }); + return; + } } protected get canPageBack(): boolean { diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 7d3b0cf7..916c5a33 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -1,4 +1,4 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component, effect, OnDestroy } from '@angular/core'; import { FormControl, FormGroup, @@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input'; import { CredentialService } from '../../shared/services/credential.service'; import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; -import { finalize, Subscription } from 'rxjs'; +import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; import { HttpErrorResponse } from '@angular/common/http'; @@ -34,7 +34,7 @@ type LoginStep = 'credentials' | 'otk'; styleUrl: './app-login.component.scss', standalone: true, }) -export class AppLoginComponent implements OnInit, OnDestroy { +export class AppLoginComponent implements OnDestroy { credentialsForm = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ @@ -64,28 +64,21 @@ export class AppLoginComponent implements OnInit, OnDestroy { protected credentialService: CredentialService, protected router: Router, protected snackBar: MatSnackBar, - ) {} - - ngOnInit(): void { - this.subscription = this.credentialService.validating.subscribe( - (validating) => { - if (validating) { - this.credentialsForm.disable(); - this.otkForm.disable(); - } else { - this.credentialsForm.enable(); - this.otkForm.enable(); - this.checkEnter(); - } - }, - ); - if (!this.credentialService.validating.value) { - this.checkEnter(); - } + ) { + effect(() => { + if (this.credentialService.isValidating()) { + this.credentialsForm.disable(); + this.otkForm.disable(); + } else { + this.credentialsForm.enable(); + this.otkForm.enable(); + this.checkEnter(); + } + }); } checkEnter(): void { - if (this.credentialService.isAuthenticated.value) { + if (this.credentialService.isAuthenticated()) { this.router.navigate(['/dashboard']); } } @@ -98,7 +91,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.stopCountdown(); } - requestOtk() { + async requestOtk() { if (this.credentialsForm.invalid || this.isSubmitting) { this.credentialsForm.markAllAsTouched(); return; @@ -110,39 +103,36 @@ export class AppLoginComponent implements OnInit, OnDestroy { const email = this.credentialsForm.controls.email.value ?? ''; const password = this.credentialsForm.controls.password.value ?? ''; - this.credentialService - .requestOtk(email, password) - .pipe( - finalize(() => { - this.isSubmitting = false; - this.credentialsForm.enable(); - }), - ) - .subscribe({ - next: (accountId) => { - if (!accountId) { - return; - } - - this.accountId = accountId; - this.currentStep = 'otk'; - this.otkForm.reset(); - this.startCountdown(); - this.snackBar.open( - 'OTK-Code wurde an die E-Mail-Adresse gesendet.', - 'OK', - { - duration: 4000, - }, - ); + try { + const otkResponse = await this.credentialService.requestOtk( + email, + password, + ); + const accountId = otkResponse.account_id; + this.accountId = accountId; + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open( + 'OTK-Code wurde an die E-Mail-Adresse gesendet.', + 'OK', + { + duration: 4000, }, - error: (error: HttpErrorResponse) => { - this.credentialService.clearLocalAuthState(); - this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { - duration: 5000, - }); + ); + } catch (error: unknown) { + this.credentialService.clearLocalAuthState(); + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, }, - }); + ); + } finally { + this.isSubmitting = false; + this.credentialsForm.enable(); + } } resendCode() { @@ -153,7 +143,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.requestOtk(); } - login() { + async login() { if (this.otkForm.invalid || this.isSubmitting) { this.otkForm.markAllAsTouched(); return; @@ -178,29 +168,25 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.isSubmitting = true; this.otkForm.disable(); - const email = this.credentialsForm.controls.email.value ?? ''; const code = this.otkForm.controls.code.value ?? ''; - this.credentialService - .loginWithOtk(this.accountId, email, code) - .pipe( - finalize(() => { - this.isSubmitting = false; - this.otkForm.enable(); - }), - ) - .subscribe({ - next: () => { - this.stopCountdown(); - this.router.navigate(['/dashboard']); + try { + await this.credentialService.loginWithOtk(this.accountId, code); + this.stopCountdown(); + this.router.navigate(['/dashboard']); + } catch (error: unknown) { + this.credentialService.clearLocalAuthState(); + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, }, - error: (error: HttpErrorResponse) => { - this.credentialService.clearLocalAuthState(); - this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { - duration: 5000, - }); - }, - }); + ); + } finally { + this.isSubmitting = false; + this.otkForm.enable(); + } } editCredentials() { @@ -240,6 +226,7 @@ export class AppLoginComponent implements OnInit, OnDestroy { } private getLoginErrorMessage(error: HttpErrorResponse): string { + console.error('Login error:', error); if (error.status === 401) { return 'E-Mail, Passwort oder OTK-Code ist ungültig.'; } diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts index d4169732..ff05c039 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -5,6 +5,7 @@ import { signal, DestroyRef, OnInit, + effect, } from '@angular/core'; import { CommonModule } from '@angular/common'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @@ -54,7 +55,7 @@ import { InstitutionsService } from '../../api'; templateUrl: './app-register.component.html', styleUrl: './app-register.component.scss', }) -export class AppRegisterComponent implements OnDestroy, OnInit { +export class AppRegisterComponent implements OnDestroy { private readonly fb = inject(FormBuilder); protected readonly credentialService = inject(CredentialService); private readonly router = inject(Router); @@ -73,42 +74,37 @@ export class AppRegisterComponent implements OnDestroy, OnInit { showPassword = false; constructor() { + effect(() => { + if (this.credentialService.isValidating()) { + this.registerForm.disable(); + } else { + this.registerForm.enable(); + this.checkEnter(); + } + }); + this.setupInstitutionAutocomplete(); } - ngOnInit(): void { - this.subscription = this.credentialService.validating.subscribe( - (validating) => { - if (validating) { - this.registerForm.disable(); - } else { - this.registerForm.enable(); - this.checkEnter(); - } - }, - ); - if (!this.credentialService.validating) { - this.checkEnter(); - } - } + ngOnDestroy(): void { this.subscription?.unsubscribe(); } checkEnter(): void { - if (this.credentialService.isAuthenticated.value) { + if (this.credentialService.isAuthenticated()) { this.router.navigate(['/dashboard']); } } submit() { if (this.registerForm.valid) { - this.credentialService.validating.next(true); + this.credentialService.isValidating.set(true); this.registerForm.disable(); this.subscription = this.credentialService .registerAccount(this.registerForm.value) .subscribe({ next: () => { - this.credentialService.validating.next(false); + this.credentialService.isValidating.set(false); this.snackBar.open( 'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.', 'OK', @@ -117,7 +113,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit { this.router.navigate(['/login']); }, error: (err) => { - this.credentialService.validating.next(false); + this.credentialService.isValidating.set(false); this.registerForm.enable(); const message = err.error?.message || diff --git a/webapp/src/app/resolvers/accounts-page.resolver.ts b/webapp/src/app/resolvers/accounts-page.resolver.ts new file mode 100644 index 00000000..1d4be85d --- /dev/null +++ b/webapp/src/app/resolvers/accounts-page.resolver.ts @@ -0,0 +1,19 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { AccountPage, AuthService } from '../api'; + +export const accountsPageResolver: ResolveFn = (route, state) => { + const page = Number(route.queryParamMap.get('page') ?? '0'); + const size = Number(route.queryParamMap.get('size') ?? '10'); + const search = route.queryParamMap.get('search') || undefined; + const organizationId = + route.queryParamMap.get('organization_id') || undefined; + + return inject(AuthService).listAccounts( + page, + size, + undefined, + search, + organizationId, + ); +}; diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index 55e18ca8..a8876ced 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -1,35 +1,36 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const adminGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - switchMap(() => { - if ( - !credentialService.isEffectiveSuperAdmin() && - !credentialService.isEffectiveAdmin() - ) { - void router.navigate(['/dashboard']); - return of(false); - } + ref.destroy(); - return of(true); - }), - catchError(() => of(false)), - ); - }), - ); + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + if (!credentialService.isEffectiveAdmin()) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/super-admin.guard.ts b/webapp/src/app/shared/guards/super-admin.guard.ts index b1936483..993f00a5 100644 --- a/webapp/src/app/shared/guards/super-admin.guard.ts +++ b/webapp/src/app/shared/guards/super-admin.guard.ts @@ -1,31 +1,36 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const superAdminGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - switchMap(() => { - if (!credentialService.isEffectiveSuperAdmin()) { - void router.navigate(['/dashboard']); - return of(false); - } - return of(true); - }), - catchError(() => of(false)), - ); - }), - ); + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + if (!credentialService.isEffectiveSuperAdmin()) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index 190780ae..7145e5ea 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -1,25 +1,30 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, map, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const userGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - map(() => true), - catchError(() => of(false)), - ); - }), - ); + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 130e6c94..194799a2 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -1,86 +1,73 @@ -import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; +import { + HttpErrorResponse, + HttpInterceptorFn, + HttpRequest, +} from '@angular/common/http'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; -import { MatSnackBar } from '@angular/material/snack-bar'; -import { catchError, switchMap, tap, throwError } from 'rxjs'; +import { catchError, throwError } from 'rxjs'; import { CredentialService } from '../services/credential.service'; -import { UiFocusService } from '../services/ui-focus.service'; + +const UNAUTHENTICATED_POST_ENDPOINTS = [ + '/api/auth/v2/request-otk', + '/api/auth/v2/login', + '/institutions/autocomplete', +]; + +const isUnauthenticatedPostRequest = (req: any) => { + const url = req.url.split('?')[0]; + return ( + req.method === 'POST' && + UNAUTHENTICATED_POST_ENDPOINTS.some((endpoint) => url.endsWith(endpoint)) + ); +}; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { const url = req.url.split('?')[0]; - const uiFocusService = inject(UiFocusService); - const isPublicAuthRequest = - req.method === 'POST' && - (url.endsWith('/api/auth/v2/request-otk') || - url.endsWith('/api/auth/v2/login') || - url.endsWith('/api/auth/v2/access') || - url.endsWith('/api/auth/v2/refresh')); - - if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) { + if (isUnauthenticatedPostRequest(req)) { return next(req); } const credentialService = inject(CredentialService); const router = inject(Router); - const snackBar = inject(MatSnackBar); - const tokenProvider = credentialService.getBearerToken(); - const isLogoutRequest = url.endsWith('/api/auth/v2/logout'); - return tokenProvider.pipe( - switchMap((response) => { - if (response == undefined) { - credentialService.clearLocalAuthState(); + if (!credentialService.isActiveIdentityToken()) { + void router.navigate(['/login']); + return throwError(() => new Error('No valid identity token')); + } + const idToken = credentialService.identityToken(); + let bearerToken: string; + if (url.endsWith('/api/auth/v2/access')) { + bearerToken = idToken?.raw_token ?? ''; + } else { + if (!credentialService.isActiveAccessToken()) { + credentialService.refreshAccessToken(idToken!); + } + const accessToken = credentialService.accessToken(); + if (!accessToken) { + void router.navigate(['/login']); + return throwError(() => new Error('No valid access token')); + } + return next(attachToken(req, accessToken.raw_token)); + } + const authorizedRequest = req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + bearerToken), + }); - snackBar.open( - 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/login']); - - return throwError( - () => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), - ); - } - - const authorizedRequest = req.clone({ - headers: req.headers.set('Authorization', 'Bearer ' + response), - }); - - return next(authorizedRequest).pipe( - catchError((error: HttpErrorResponse) => { - if (error.status === 401 && !isLogoutRequest) { - return credentialService.handleUnauthorized().pipe( - tap((result) => { - uiFocusService.blurActiveElement(); - - if (result === 'stopped-impersonating') { - snackBar.open( - 'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/accounts']); - } else if (result === 'logged-out') { - snackBar.open( - 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/login']); - } - }), - switchMap(() => throwError(() => error)), - ); - } - - return throwError(() => error); - }), - ); + return next(authorizedRequest).pipe( + catchError((error: HttpErrorResponse) => { + console.error('Authentication error:', error); + return throwError(() => error); }), ); }; + +const attachToken = ( + req: HttpRequest, + token: string, +): HttpRequest => { + return req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + token), + }); +}; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index f276073c..e578e992 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,56 +1,50 @@ -import { Injectable, computed, inject, signal } from '@angular/core'; -import { filter, take, map, catchError, finalize } from 'rxjs/operators'; -import { - BehaviorSubject, - Observable, - of, - switchMap, - tap, - throwError, -} from 'rxjs'; +import { Injectable, computed, effect, inject, signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { firstValueFrom, Observable, of, switchMap, throwError } from 'rxjs'; import { AccessResponse, AccessToken, AuthService, - Configuration, IdToken, - LoginResponse, AccountProfile, + RefreshToken, + OtkResponse, } from '../../api'; -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import { Router } from '@angular/router'; -type LogoutResult = 'logged-out' | 'stopped-impersonating'; -type UnauthorizedRecoveryResult = - | 'logged-out' - | 'stopped-impersonating' - | 'already-handling'; +import { Router } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class CredentialService { private readonly authService = inject(AuthService); - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - private handlingUnauthorized = false; - private static readonly KEY_GRANT = 'grant'; + private static readonly KEY_IDENTITY_TOKEN = 'identity_token'; + private static readonly KEY_REFRESH_TOKEN = 'refresh_token'; + private static readonly KEY_ACCESS_TOKEN = 'access_token'; - public readonly validating = new BehaviorSubject(false); - public readonly isAuthenticated = new BehaviorSubject(false); + public readonly isValidating = signal(false); + public readonly isAuthenticated = computed( + () => this.accessToken() !== undefined, + ); public readonly isEffectiveSuperAdmin = computed( () => this.accessToken()?.effective_role === 'SUPER_ADMIN', ); public readonly isEffectiveAdmin = computed( - () => this.accessToken()?.effective_role === 'ADMIN', + () => + this.accessToken()?.effective_role === 'ADMIN' || + this.isEffectiveSuperAdmin(), ); public readonly effectiveOrganizationId = computed( () => this.accessToken()?.effective_organization_id, ); - public readonly login = new BehaviorSubject(''); - public readonly email = new BehaviorSubject(''); - public readonly organizationName = new BehaviorSubject(''); + public readonly login = computed( + () => this.accountProfile()?.name ?? this.accountProfile()?.email ?? '', + ); + public readonly email = computed(() => this.accountProfile()?.email ?? ''); + public readonly organizationName = computed( + () => this.accountProfile()?.organization_name ?? '', + ); public readonly realAccountId = computed( () => this.accessToken()?.real_account_id ?? '', @@ -62,298 +56,247 @@ export class CredentialService { () => this.realAccountId() !== this.effectiveAccountId(), ); - private readonly identityToken = signal(undefined); - private readonly accessToken = signal(undefined); + public readonly identityToken = signal(undefined); + public readonly refreshToken = signal(undefined); + public readonly accessToken = signal(undefined); + + public readonly isActiveIdentityToken = computed(() => { + const idToken = this.identityToken(); + return ( + idToken !== undefined && + new Date(idToken.expires_at).getTime() >= Date.now() + ); + }); + + public readonly isActiveAccessToken = computed(() => { + const accessToken = this.accessToken(); + return ( + accessToken !== undefined && + new Date(accessToken.expires_at).getTime() >= Date.now() + ); + }); + + public readonly accountProfile = toSignal( + toObservable(this.isAuthenticated).pipe( + switchMap((isAuthenticated) => + isAuthenticated + ? this.authService.getCurrentAccount() + : of(undefined), + ), + ), + { initialValue: undefined }, + ); private request = 0; + loadTokensFromStorage(): void { + const idTokenData = localStorage.getItem( + CredentialService.KEY_IDENTITY_TOKEN, + ); + const refreshTokenData = localStorage.getItem( + CredentialService.KEY_REFRESH_TOKEN, + ); + const accessTokenData = localStorage.getItem( + CredentialService.KEY_ACCESS_TOKEN, + ); + + if (idTokenData) { + this.identityToken.set(JSON.parse(idTokenData) as IdToken); + } + if (refreshTokenData) { + this.refreshToken.set(JSON.parse(refreshTokenData) as RefreshToken); + } + if (accessTokenData) { + this.accessToken.set(JSON.parse(accessTokenData) as AccessToken); + } + } + + storeIdentityToken(idToken: IdToken): void { + this.identityToken.set(idToken); + localStorage.setItem( + CredentialService.KEY_IDENTITY_TOKEN, + JSON.stringify(idToken), + ); + } + + storeRefreshToken(refreshToken: RefreshToken): void { + this.refreshToken.set(refreshToken); + localStorage.setItem( + CredentialService.KEY_REFRESH_TOKEN, + JSON.stringify(refreshToken), + ); + } + + storeAccessToken(accessToken: AccessToken): void { + this.accessToken.set(accessToken); + localStorage.setItem( + CredentialService.KEY_ACCESS_TOKEN, + JSON.stringify(accessToken), + ); + } + + clearTokensFromStorage(): void { + localStorage.removeItem(CredentialService.KEY_IDENTITY_TOKEN); + localStorage.removeItem(CredentialService.KEY_REFRESH_TOKEN); + localStorage.removeItem(CredentialService.KEY_ACCESS_TOKEN); + } + constructor(private readonly router: Router) { - const data = localStorage.getItem(CredentialService.KEY_GRANT); - const id = data ? (JSON.parse(data) as AccessToken) : undefined; + this.loadTokensFromStorage(); + effect(() => { + console.log('IdToken', this.identityToken()); + console.log('RefreshToken', this.refreshToken()); + console.log('AccessToken', this.accessToken()); + }); + const id = this.identityToken(); if (id && new Date(id.expires_at).getTime() >= Date.now()) { - this.identityToken.set(id); - this.validating.next(true); + this.isValidating.set(true); setTimeout(() => this.refreshAccessToken(id), 0); } } - public validateCurrentSession(): Observable { - return this.loadCurrentProfile(); - } - - public requestOtk(email: string, password: string): Observable { - const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); + public async requestOtk( + email: string, + password: string, + ): Promise { + this.isValidating.set(true); this.identityToken.set(undefined); this.accessToken.set(undefined); - return this.authService - .requestOtk({ email: email.trim().toLowerCase(), password }) - .pipe( - map((response: { account_id?: string }) => { - if (this.request !== request) { - return ''; - } + const otkResponse: OtkResponse = await firstValueFrom( + this.authService.requestOtk({ + email: email.trim().toLowerCase(), + password, + }), + ); - return response.account_id ?? ''; - }), - finalize(() => { - if (this.request === request) { - this.validating.next(false); - } - }), - ); + this.isValidating.set(false); + return otkResponse; } - public loginWithOtk( + public async loginWithOtk( accountId: string, - email: string, emailCode: string, - ): Observable { + ): Promise { const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); + this.isValidating.set(true); - return this.authService - .login({ account_id: accountId, email_code: emailCode.trim() }) - .pipe( - switchMap((response: LoginResponse) => { - if (this.request != request) return of(undefined); + const loginResponse = await firstValueFrom( + this.authService.login({ + account_id: accountId, + email_code: emailCode.trim(), + }), + ); - const idToken = response.id_token; + const idToken = loginResponse.id_token; + this.identityToken.set(idToken); + this.storeIdentityToken(idToken); - this.identityToken.set(idToken); - localStorage.setItem( - CredentialService.KEY_GRANT, - JSON.stringify(idToken), - ); - return this.getAccessGrantForIdentity(idToken, request); - }), - ); + this.isValidating.set(false); + await this.getAccessToken(idToken, request); } - public refreshAccessToken(identityToken: IdToken) { + public async refreshAccessToken(identityToken: IdToken) { const request = ++this.request; - this.validating.next(true); + this.isValidating.set(true); this.accessToken.set(undefined); - this.getAccessGrantForIdentity(identityToken, request).subscribe({ - error: () => { - if (this.request != request) return; + + await this.getAccessToken(identityToken, request).catch((err) => { + if (this.request === request) { this.clearLocalAuthState(); - }, + } + throw err; }); + + this.isValidating.set(false); } - public impersonateAccount(accountId: string): Observable { + public async impersonateAccount(accountId: string): Promise { const idToken = this.identityToken(); if (!idToken) { - return throwError(() => new Error('No identity token available.')); + throw new Error('No identity token available.'); } const request = ++this.request; - this.validating.next(true); + this.isValidating.set(true); this.accessToken.set(undefined); - return this.getAccessGrantForIdentity(idToken, request, accountId).pipe( - tap({ error: () => this.validating.next(false) }), - ); + await this.getAccessToken(idToken, request, accountId).catch((err) => { + if (this.request === request) { + this.clearLocalAuthState(); + } + throw err; + }); + this.isValidating.set(false); } - public stopImpersonating(): Observable { + public async stopImpersonating(): Promise { const idToken = this.identityToken(); if (!idToken) { - return throwError(() => new Error('No identity token available.')); + throw new Error('No identity token available.'); } const request = ++this.request; - this.validating.next(true); + this.isValidating.set(true); this.accessToken.set(undefined); - return this.getAccessGrantForIdentity(idToken, request).pipe( - tap({ error: () => this.validating.next(false) }), - ); + await this.getAccessToken(idToken, request); + this.isValidating.set(false); } - public logoutAccount(): Observable { - const wasImpersonating = this.isImpersonating(); - - return this.authService - .logout('body', false, { transferCache: false }) - .pipe( - catchError((error) => { - console.error('Backend logout failed', error); - return of(null); - }), - switchMap(() => { - if (!wasImpersonating) { - this.clearLocalAuthState(); - return of('logged-out' as const); - } - - return this.stopImpersonating().pipe( - map(() => 'stopped-impersonating' as const), - catchError((error) => { - console.error('Stop impersonating after logout failed', error); - this.clearLocalAuthState(); - return of('logged-out' as const); - }), - ); - }), - ); + public async logoutAccount() { + await firstValueFrom(this.authService.logout()); + this.clearLocalAuthState(); } public clearLocalAuthState(): void { this.request += 1; - localStorage.removeItem(CredentialService.KEY_GRANT); + this.clearTokensFromStorage(); this.identityToken.set(undefined); this.accessToken.set(undefined); - this.isAuthenticated.next(false); - this.validating.next(false); - this.login.next(''); - this.email.next(''); - this.organizationName.next(''); + this.isValidating.set(false); this.router.navigate(['/login'], { replaceUrl: true }); } - public handleUnauthorized(): Observable { - if (this.handlingUnauthorized) { - return of('already-handling' as const); - } - - this.handlingUnauthorized = true; - - const isImpersonating = this.isImpersonating(); - const identityToken = this.identityToken(); - - const recovery$ = - isImpersonating && identityToken - ? this.stopImpersonating().pipe( - map(() => 'stopped-impersonating' as const), - catchError((error) => { - console.error('Failed to stop impersonation after 401', error); - this.clearLocalAuthState(); - return of('logged-out' as const); - }), - ) - : of(null).pipe( - tap(() => this.clearLocalAuthState()), - map(() => 'logged-out' as const), - ); - - return recovery$.pipe( - finalize(() => { - this.handlingUnauthorized = false; - }), - ); - } - - public changePassword( + public async changePassword( currentPassword: string, newPassword: string, - ): Observable { - return this.httpClient - .post( - `${this.apiBasePath}/api/auth/v2/change-password`, - { - current_password: currentPassword, - new_password: newPassword, - }, - { withCredentials: true }, - ) - .pipe( - tap(() => { - this.clearLocalAuthState(); - }), - map(() => undefined), - catchError((err) => { - throw err; - }), - ); + ): Promise { + this.isValidating.set(true); + await firstValueFrom( + this.authService.changePassword({ + current_password: currentPassword, + new_password: newPassword, + }), + ); + this.clearLocalAuthState(); + this.isValidating.set(false); } public registerAccount(_data: unknown): Observable { return throwError(() => new Error('Registration is temporarily disabled.')); } - //review: arman (generated fix) - public getBearerToken(): Observable { - const accessToken = this.accessToken(); - const identityToken = this.identityToken(); - - // 1. If we have a valid access token, return it immediately and complete. - if ( - accessToken && - Date.now() < new Date(accessToken.expires_at).getTime() - ) { - return of(accessToken.raw_token); - } - - // 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh. - if (!this.validating.value) { - if (!identityToken) { - return of(undefined); // No identity token to refresh with. - } - this.refreshAccessToken(identityToken); - } - - // 3. Wait for the validation to finish, then return the resulting token. - return this.validating.pipe( - filter((isValidating) => !isValidating), // Wait until validating becomes false - take(1), // Take exactly 1 emission and then automatically complete() - map(() => this.accessToken()?.raw_token), - ); - } - - private getAccessGrantForIdentity( + private async getAccessToken( idToken: IdToken, request: number, effectiveAccountId?: string, - ): Observable { + ): Promise { + if (this.request !== request) { + return; + } + const realAccountId = idToken.real_account_id; - const headers = new HttpHeaders({ - Authorization: `Bearer ${idToken.raw_token}`, - }); - const payload = { - real_account_id: realAccountId, - effective_account_id: effectiveAccountId ?? realAccountId, - }; - return this.httpClient - .post(`${this.apiBasePath}/api/auth/v2/access`, payload, { - headers, - withCredentials: true, - }) - .pipe( - tap((result: AccessResponse) => { - if (this.request != request) return; + const result: AccessResponse = await firstValueFrom( + this.authService.getAccessToken({ + real_account_id: realAccountId, + effective_account_id: effectiveAccountId ?? realAccountId, + }), + ); - const accessToken = result.access_token; - - this.accessToken.set(accessToken); - this.isAuthenticated.next(true); - this.validating.next(false); - }), - map(() => undefined), - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } - - private loadCurrentProfile(): Observable { - return this.httpClient - .get(`${this.apiBasePath}/api/accounts/me`, { - withCredentials: true, - }) - .pipe( - tap((profile) => { - this.login.next(profile.name ?? profile.email ?? ''); - this.email.next(profile.email ?? ''); - this.organizationName.next(profile.organization_name ?? ''); - }), - map(() => undefined), - ); + this.accessToken.set(result.access_token); + this.refreshToken.set(result.refresh_token); + this.isValidating.set(false); } } diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index f4ae841c..7be187a0 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -3,7 +3,7 @@ - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { } - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { @if (credentialService.isImpersonating()) {
switch_account diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 127f842d..bee7ed7c 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -102,22 +102,21 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.mediaQuery.removeEventListener('change', this.mediaQueryListener); } - logout() { - this.credentialService.logoutAccount().subscribe({ - next: (result) => { - if (result === 'stopped-impersonating') { - this.router.navigate(['/accounts']); - } else { - this.router.navigate(['/login']); - } - }, - }); + async logout() { + const isImpersonating = this.credentialService.isImpersonating(); + + await this.credentialService.stopImpersonating(); + + if (isImpersonating) { + this.router.navigate(['/accounts']); + } else { + this.router.navigate(['/login']); + } } - stopImpersonating(): void { - this.credentialService.stopImpersonating().subscribe({ - next: () => this.router.navigate(['/accounts']), - }); + async stopImpersonating(): Promise { + await this.credentialService.stopImpersonating(); + this.router.navigate(['/accounts']); } navigateBack() { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index b80e7271..a917f40b 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -101,13 +101,13 @@ } @else { @@ -115,13 +115,11 @@ diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 96f2bd12..8d2bea96 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -68,7 +68,7 @@ export class AppMenuComponent { icon: 'groups', route: '/persons', queryParams: { - institutionName: this.credentialService.organizationName.value, + institutionName: this.credentialService.organizationName(), }, disabled: false, }, @@ -166,14 +166,8 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAccount().subscribe({ - next: (result) => { - if (result === 'stopped-impersonating') { - this.router.navigate(['/accounts']); - } else { - this.router.navigate(['/login']); - } - }, + this.credentialService.logoutAccount().then(() => { + this.router.navigate(['/login']); }); }); } From 7b4c459fd89f8bb6be249f3bc8f775bc55b452a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 3 Jul 2026 17:00:19 +0200 Subject: [PATCH 22/41] fix(frontend/register): fixed wrong variable name --- .../src/app/modules/app-register/app-register.component.html | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webapp/src/app/modules/app-register/app-register.component.html b/webapp/src/app/modules/app-register/app-register.component.html index e6349bc5..a9e758c6 100644 --- a/webapp/src/app/modules/app-register/app-register.component.html +++ b/webapp/src/app/modules/app-register/app-register.component.html @@ -84,9 +84,7 @@ mat-raised-button class="button" (click)="submit()" - [disabled]=" - !registerForm.valid || (credentialService.validating | async) - "> + [disabled]="!registerForm.valid || credentialService.isValidating()"> Registrieren From e648ea1ec460d5f23abfc38712aba041b0699759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sat, 4 Jul 2026 22:37:34 +0200 Subject: [PATCH 23/41] feat(backend/auth): added otk response model --- service/src/main/inse/auth/model.py | 7 +++++++ service/src/main/inse/auth/router.py | 3 ++- service/src/main/inse/auth/service.py | 5 +++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index a79aa113..21d7d706 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -210,3 +210,10 @@ class AccessResponse(BaseModel): refresh_token: RefreshToken = Field( description="The refresh token issued alongside the access token for obtaining new access tokens." ) + + +class OtkResponse(BaseModel): + status: str = Field(description="The status of the one-time code (OTC) request.") + account_id: uuid.UUID = Field( + description="The unique identifier of the account for which the OTC was requested." + ) diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 2ce4f52a..e80612bb 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -14,6 +14,7 @@ from inse.auth.model import ( AccessToken, IdToken, LoginResponse, + OtkResponse, RefreshToken, ) @@ -40,7 +41,7 @@ async def request_otk( session: SessionDep, email: Annotated[str, Body(description="User's email address")], password: Annotated[str, Body(description="User's password")], -): +) -> OtkResponse: return auth_service.request_otk(session=session, email=email, password=password) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 0af15a4b..dfaa1bf3 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -18,6 +18,7 @@ from inse.auth.model import ( IdToken, LoginResponse, Organization, + OtkResponse, RefreshToken, Secret, TokenType, @@ -155,7 +156,7 @@ def _verify_password(password: str, password_hash: str) -> bool: return False -def request_otk(session: Session, email: str, password: str): +def request_otk(session: Session, email: str, password: str) -> OtkResponse: """Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid. Args: @@ -236,7 +237,7 @@ def request_otk(session: Session, email: str, password: str): else: logger.info("OTK generated for account %s", account.id) - return {"status": "ok", "account_id": str(account.id)} + return OtkResponse(status="success", account_id=account.id) def login( From a464a95c4e430990d1caad61102ded24f1848416 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 5 Jul 2026 00:19:06 +0200 Subject: [PATCH 24/41] fix(frontend/organizations): unfucked everything (again) --- webapp/src/app/app.routes.ts | 10 +- .../organization-dialog.component.ts | 28 ++-- .../organizations.component.html | 123 +++++----------- .../organizations.component.scss | 82 +---------- .../organizations/organizations.component.ts | 137 ++++++++++++------ ....ts => accounts-organizations.resolver.ts} | 2 +- .../organizations-organizations.resolver.ts | 12 ++ .../organization-management.service.ts | 75 ---------- 8 files changed, 171 insertions(+), 298 deletions(-) rename webapp/src/app/resolvers/{organizations.resolver.ts => accounts-organizations.resolver.ts} (85%) create mode 100644 webapp/src/app/resolvers/organizations-organizations.resolver.ts delete mode 100644 webapp/src/app/shared/services/organization-management.service.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 940130e3..ac603aae 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -20,7 +20,8 @@ import { publicationResolver } from './resolvers/publication-resolver'; import { accountResolver } from './resolvers/account.resolver'; import { accountViewerGuard } from './shared/guards/account-viewer.guard'; import { accountsPageResolver } from './resolvers/accounts-page.resolver'; -import { organizationsResolver } from './resolvers/organizations.resolver'; +import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver'; +import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver'; export const routes: Routes = [ { @@ -117,7 +118,7 @@ export const routes: Routes = [ ), resolve: { accountPage: accountsPageResolver, - organizations: organizationsResolver, + organizations: accountsOrganizationResolver, }, runGuardsAndResolvers: 'always', }, @@ -128,7 +129,12 @@ export const routes: Routes = [ import('./modules/organizations/organizations.component').then( (mod) => mod.OrganizationsComponent, ), + resolve: { + organizationPage: organizationsOrganizationsResolver, + }, + runGuardsAndResolvers: 'always', }, + { path: 'news/:id', canActivate: [userGuard], diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts index 6348c11f..a192c306 100644 --- a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts @@ -16,15 +16,22 @@ import { import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; -import type { - CreateOrganizationPayload, - OrganizationProfile, - UpdateOrganizationPayload, -} from '../../../shared/services/organization-management.service'; +import { InseOrganizationManagementModelOrganizationProfile } from '../../../api'; + +export interface CreateOrganizationPayload { + name: string; + other_inst_id?: string | null; +} + +export interface UpdateOrganizationPayload { + name?: string; + other_inst_id?: string | null; + deleted?: boolean; +} export interface OrganizationDialogData { mode: 'create' | 'edit'; - organization?: OrganizationProfile; + organization?: InseOrganizationManagementModelOrganizationProfile; } export type OrganizationDialogResult = @@ -66,10 +73,9 @@ export class OrganizationDialogComponent { nonNullable: true, validators: [Validators.required], }), - otherInstId: new FormControl( - this.data.organization?.other_inst_id ?? '', - { nonNullable: true }, - ), + otherInstId: new FormControl(this.data.organization?.other_inst_id ?? '', { + nonNullable: true, + }), deleted: new FormControl(this.data.organization?.deleted ?? false, { nonNullable: true, }), @@ -100,6 +106,6 @@ export class OrganizationDialogComponent { } protected close(): void { - this.dialogRef.close(undefined); + this.dialogRef.close(); } } diff --git a/webapp/src/app/modules/organizations/organizations.component.html b/webapp/src/app/modules/organizations/organizations.component.html index a6486b74..14853ec0 100644 --- a/webapp/src/app/modules/organizations/organizations.component.html +++ b/webapp/src/app/modules/organizations/organizations.component.html @@ -3,6 +3,7 @@

Organisationen

Mandanten, externe Institutions-IDs und Status verwalten.

+
- Seite {{ page + 1 }} - -
- + + + + + + + + + + {{ (row.deleted ? 'inactive' : 'active') | status }} + + + + +
+ + +
+
diff --git a/webapp/src/app/modules/organizations/organizations.component.scss b/webapp/src/app/modules/organizations/organizations.component.scss index b558f858..e455d7e3 100644 --- a/webapp/src/app/modules/organizations/organizations.component.scss +++ b/webapp/src/app/modules/organizations/organizations.component.scss @@ -5,15 +5,9 @@ padding: 24px; } -.page-header, -.table-header, -.pagination, -.row-actions { +.page-header { display: flex; align-items: center; -} - -.page-header { justify-content: space-between; gap: 16px; } @@ -32,60 +26,6 @@ p { margin-top: 6px; } -.table-panel { - overflow: hidden; - border: 1px solid #d7dde6; - border-radius: 8px; - background: #fff; -} - -.table-header { - justify-content: space-between; - padding: 16px; - border-bottom: 1px solid #e5e7eb; -} - -.table-wrap { - overflow-x: auto; -} - -table { - width: 100%; - border-collapse: collapse; -} - -th, -td { - padding: 12px 16px; - text-align: left; - border-bottom: 1px solid #edf1f7; - white-space: nowrap; -} - -th { - color: #475569; - font-weight: 700; - background: #f8fafc; -} - -tr.deleted { - color: #94a3b8; -} - -.identifier { - font-family: monospace; - font-size: 12px; -} - -.link-button { - border: 0; - background: transparent; - color: #1d4ed8; - padding: 0; - font: inherit; - cursor: pointer; -} - .status { display: inline-flex; align-items: center; @@ -103,21 +43,6 @@ tr.deleted { color: #991b1b; } -.row-actions { - gap: 4px; -} - -.empty { - color: #64748b; - text-align: center; -} - -.pagination { - justify-content: flex-end; - gap: 8px; - padding: 12px 16px; -} - @media (max-width: 640px) { .organizations-page { padding: 16px; @@ -128,3 +53,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/organizations/organizations.component.ts b/webapp/src/app/modules/organizations/organizations.component.ts index 0d061c50..6cbaecb4 100644 --- a/webapp/src/app/modules/organizations/organizations.component.ts +++ b/webapp/src/app/modules/organizations/organizations.component.ts @@ -1,19 +1,34 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit, inject } from '@angular/core'; +import { + Component, + inject, + input, + OnInit, + TemplateRef, + viewChild, +} from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; -import { finalize } from 'rxjs'; -import { - OrganizationManagementService, - OrganizationProfile, -} from '../../shared/services/organization-management.service'; import type { OrganizationDialogComponent, OrganizationDialogData, OrganizationDialogResult, } from './organization-dialog/organization-dialog.component'; +import { + InseOrganizationManagementModelOrganizationProfile, + OrganizationPage, + OrganizationService, +} from '../../api'; +import { + GenericColumn, + DataTableComponent, +} from '../../shared/ui/data-table/data-table.component'; +import { MatCardModule } from '@angular/material/card'; +import { StatusPipe } from '../../shared/pipes/status.pipe'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { Router } from '@angular/router'; @Component({ selector: 'app-organizations', @@ -23,50 +38,81 @@ import type { MatDialogModule, MatIconModule, MatSnackBarModule, + DataTableComponent, + MatCardModule, + StatusPipe, + QueryParamPaginatorComponent, ], templateUrl: './organizations.component.html', styleUrl: './organizations.component.scss', standalone: true, }) export class OrganizationsComponent implements OnInit { - private readonly organizationService = inject(OrganizationManagementService); + private readonly router = inject(Router); private readonly dialog = inject(MatDialog); private readonly snackBar = inject(MatSnackBar); + private readonly organizationService = inject(OrganizationService); - protected organizations: OrganizationProfile[] = []; - protected total = 0; - protected page = 0; - protected readonly pageSize = 10; - protected isLoading = false; + organizationPage = input.required(); + organizationColumns: GenericColumn[] = + []; + + organizationStatusTmp = viewChild.required>( + 'organizationStatusTmp', + ); + organizationActionsTmp = viewChild.required>( + 'organizationActionsTmp', + ); ngOnInit(): void { - this.loadOrganizations(); - } - - protected loadOrganizations(page = this.page): void { - this.page = page; - this.isLoading = true; - this.organizationService - .getOrganizations(page, this.pageSize) - .pipe(finalize(() => (this.isLoading = false))) - .subscribe({ - next: (result) => { - this.organizations = result.items; - this.total = result.total; - }, - error: () => this.showError('Organisationen konnten nicht geladen werden.'), - }); + this.organizationColumns = [ + { + id: 'name', + header: 'Name', + type: 'accessor', + accessorKey: 'name', + }, + { + id: 'other_inst_id', + header: 'Externe ID', + type: 'accessor', + accessorKey: 'other_inst_id', + }, + { + id: 'member_count', + header: 'Mitglieder', + type: 'accessor', + accessorKey: 'member_count', + }, + { + id: 'deleted', + header: 'Status', + type: 'accessor', + accessorKey: 'deleted', + cellTemplate: this.organizationStatusTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.organizationActionsTmp(), + }, + ]; } protected startCreate(): void { this.openDialog({ mode: 'create' }); } - protected startEdit(organization: OrganizationProfile): void { + protected startEdit( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { this.openDialog({ mode: 'edit', organization }); } - protected deleteOrganization(organization: OrganizationProfile): void { + protected deleteOrganization( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { if (organization.deleted) return; import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( @@ -87,26 +133,24 @@ export class OrganizationsComponent implements OnInit { ); } - private softDeleteOrganization(organization: OrganizationProfile): void { - this.organizationService.deleteOrganization(organization.id).subscribe({ + private softDeleteOrganization( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { + this.organizationService.deleteOrganisation(organization.id).subscribe({ next: () => { this.snackBar.open('Organisation wurde deaktiviert.', 'OK', { duration: 3000, }); - this.loadOrganizations(); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, - error: () => this.showError('Organisation konnte nicht deaktiviert werden.'), + error: () => + this.showError('Organisation konnte nicht deaktiviert werden.'), }); } - protected get canPageBack(): boolean { - return this.page > 0; - } - - protected get canPageForward(): boolean { - return (this.page + 1) * this.pageSize < this.total; - } - private openDialog(data: OrganizationDialogData): void { import('./organization-dialog/organization-dialog.component').then( ({ OrganizationDialogComponent }) => { @@ -130,8 +174,8 @@ export class OrganizationsComponent implements OnInit { private save(result: OrganizationDialogResult): void { const request = result.mode === 'create' - ? this.organizationService.createOrganization(result.payload) - : this.organizationService.updateOrganization( + ? this.organizationService.createOrganisation(result.payload) + : this.organizationService.updateOrganisation( result.organizationId, result.payload, ); @@ -141,7 +185,10 @@ export class OrganizationsComponent implements OnInit { this.snackBar.open('Organisation wurde gespeichert.', 'OK', { duration: 3000, }); - this.loadOrganizations(0); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, error: (error) => this.showError( diff --git a/webapp/src/app/resolvers/organizations.resolver.ts b/webapp/src/app/resolvers/accounts-organizations.resolver.ts similarity index 85% rename from webapp/src/app/resolvers/organizations.resolver.ts rename to webapp/src/app/resolvers/accounts-organizations.resolver.ts index 258d646c..8fb026c9 100644 --- a/webapp/src/app/resolvers/organizations.resolver.ts +++ b/webapp/src/app/resolvers/accounts-organizations.resolver.ts @@ -5,7 +5,7 @@ import { InseAccountManagementModelOrganizationProfile, } from '../api'; -export const organizationsResolver: ResolveFn< +export const accountsOrganizationResolver: ResolveFn< InseAccountManagementModelOrganizationProfile[] > = (route, state) => { return inject(AuthService).listAccountOrganizations(); diff --git a/webapp/src/app/resolvers/organizations-organizations.resolver.ts b/webapp/src/app/resolvers/organizations-organizations.resolver.ts new file mode 100644 index 00000000..70297dee --- /dev/null +++ b/webapp/src/app/resolvers/organizations-organizations.resolver.ts @@ -0,0 +1,12 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { OrganizationPage, OrganizationService } from '../api'; + +export const organizationsOrganizationsResolver: ResolveFn< + OrganizationPage +> = (route, state) => { + const page = Number(route.queryParamMap.get('page') ?? '0'); + const size = Number(route.queryParamMap.get('size') ?? '10'); + + return inject(OrganizationService).getOrganisations(page, size); +}; diff --git a/webapp/src/app/shared/services/organization-management.service.ts b/webapp/src/app/shared/services/organization-management.service.ts deleted file mode 100644 index 9597a005..00000000 --- a/webapp/src/app/shared/services/organization-management.service.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { HttpClient, HttpParams } from '@angular/common/http'; -import { Injectable, inject } from '@angular/core'; -import { Observable } from 'rxjs'; -import { Configuration } from '../../api'; - -export interface OrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; -} - -export interface OrganizationPage { - items: OrganizationProfile[]; - total: number; - page: number; - page_size: number; -} - -export interface CreateOrganizationPayload { - name: string; - other_inst_id?: string | null; -} - -export interface UpdateOrganizationPayload { - name?: string; - other_inst_id?: string | null; - deleted?: boolean; -} - -@Injectable({ providedIn: 'root' }) -export class OrganizationManagementService { - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - - getOrganizations(page: number, pageSize: number): Observable { - const params = new HttpParams() - .set('page', page) - .set('page_size', pageSize); - return this.httpClient.get( - `${this.apiBasePath}/api/organizations`, - { params }, - ); - } - - createOrganization( - payload: CreateOrganizationPayload, - ): Observable { - return this.httpClient.post( - `${this.apiBasePath}/api/organizations`, - payload, - ); - } - - updateOrganization( - organizationId: string, - payload: UpdateOrganizationPayload, - ): Observable { - return this.httpClient.put( - `${this.apiBasePath}/api/organizations/${organizationId}`, - payload, - ); - } - - deleteOrganization(organizationId: string): Observable { - return this.httpClient.delete( - `${this.apiBasePath}/api/organizations/${organizationId}`, - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } -} From 73315457a6403c927998dea98ccd138dd6034d78 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 02:19:38 +0200 Subject: [PATCH 25/41] fixed resonsiveness issue --- .../ui/topic-autocomplete/topic-autocomplete.component.html | 1 + .../ui/topic-autocomplete/topic-autocomplete.component.scss | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html index e7a2f20f..d23c2dc0 100644 --- a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html @@ -9,6 +9,7 @@ (click)="$event.preventDefault()" (keydown.enter)="submitCurrentValue(); $event.preventDefault()" (keydown.tab)="onKeydownTab($any($event))" /> + Füge ein Keyword hinzu @if (searchControl.value.trim()) { + } @else { + + } +
+
+ + + + text_fields + Extrahierte Keywords + + + account_tree + Topic Mapping + + +
+ +
+ +
+
+
+ +
+
+ } +
Breite Keywords
Coarse Keywords
-
Fine Keywords
+
+ Fine Keywords +
Eigene Keywords
@@ -70,121 +151,146 @@
@if (broadKeywords().length > 0) { - - @for (keyword of broadKeywords(); track keyword) { - - {{ keyword }} - +
+ + @for ( + keyword of broadKeywords(); + track keyword.llm_keyword.keyword + ) { + + } - +
} @else { -

–

+

Nichts extrahiert

}
@if (coarseKeywords().length > 0) { - - @for (keyword of coarseKeywords(); track keyword) { - - {{ keyword }} - +
+ @for ( + keyword of coarseKeywords(); + track keyword.llm_keyword.keyword + ) { + + } - +
} @else { -

–

+

Nichts extrahiert

}
@if (fineKeywords().length > 0) { - - @for (keyword of fineKeywords(); track keyword) { - - {{ keyword }} - +
+ @for ( + keyword of fineKeywords(); + track keyword.llm_keyword.keyword + ) { + + } - +
} @else { -

–

+

Nichts extrahiert

}
-
- - +
@if (manualKeywords().length > 0) { - @for (keyword of manualKeywords(); track keyword) { - - {{ keyword }} - cancel - + @for ( + keyword of manualKeywords(); + track keyword.llm_keyword.keyword + ) { +
+ + + +
} + } @else if (loadingNewKeyword()) { +
+ + +
+ } @else { +

Nichts hinzugefügt

} - +
- - @if (extractedKeywordsExist()) { -
- @if (areAllExtractedSelected()) { - - } @else { - - } - -
- } - @if (isExtracting()) {
search diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index 3162536f..d92e54be 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -6,25 +6,135 @@ } .tab-content { - padding: 0.5rem 0; display: grid; + margin-top: 0.5rem; grid-template-columns: 5fr 1fr; gap: 0.5rem; + align-items: start; } - .full-width { width: 100%; } +.extract-btn { + white-space: nowrap; +} + .actions { display: flex; justify-content: center; } +.keywords-toolbar { + display: flex; + flex-direction: column; + background: var(--sg-background-muted, #f4f5f7); + + ::ng-deep app-topic-legend .topic-legend { + width: 100%; + margin: 0; + } +} + +.toolbar-controls { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + flex-wrap: wrap; + padding: 0.5rem 0.75rem; + background: var(--sg-background-muted, #f4f5f7); +} +.toolbar-wrapper { + display: grid; + grid-template-columns: 3fr 1.3fr; + border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); +} +.toolbar-group { + display: flex; + align-items: center; + gap: 0.6rem; +} + +.toolbar-group--select button { + display: flex; + align-items: center; + gap: 0.35rem; + font-size: 0.8rem; + line-height: 30px; + border-radius: 20px; + padding: 0 14px; + + mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } +} + +.toolbar-divider { + width: 1px; + align-self: stretch; + background: var(--sg-divider, rgba(0, 0, 0, 0.12)); + display: none; +} + +@media (min-width: 640px) { + .toolbar-divider { + display: block; + } +} + +mat-button-toggle-group { + border-radius: 20px; + overflow: hidden; +} + +/* Tablet / phone: stack the toolbar and go full-width */ +@media (max-width: 768px) { + .toolbar-controls { + flex-direction: column; + align-items: stretch; + } + + .toolbar-group { + justify-content: center; + } + + .toolbar-group--select button { + width: 100%; + justify-content: center; + } + + .toolbar-group--view { + justify-content: center; + } +} + +/* Phone: icon-only buttons to save space */ +@media (max-width: 480px) { + .btn-label { + display: none; + } + + .toolbar-group--select button { + width: auto; + padding: 0 10px; + } +} +mat-button-toggle-group { + flex-wrap: wrap; +} + +.toggle-text { + margin-left: 0.35rem; +} + .extraction-grid { display: grid; grid-template-columns: 1fr; gap: 1rem; + border: 0; } .keyword-card { @@ -44,22 +154,23 @@ .keyword-table { display: flex; flex-direction: column; - gap: 0.5rem; - margin: 0.5rem 0; } .table-head { + border-top: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); + padding-top: 0.5rem; display: grid; grid-template-columns: repeat(3, 1fr) 1.3fr; grid-template-rows: auto; column-gap: 1rem; border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); padding-bottom: 0.5rem; + background: var(--sg-background-muted, #f4f5f7); } .head-cell { min-width: 0; - text-align: center; /* Center header text */ + text-align: center; } .extracted-header { @@ -71,21 +182,6 @@ align-self: end; } -.own-header { - grid-column: 4; - grid-row: 1 / span 2; - display: flex; - flex-direction: column; - gap: 0.35rem; -} - -.own-header-title { - font-size: 0.95rem; - font-weight: 600; - color: var(--sg-text-primary); - text-align: center; /* Center own header title */ -} - .sub-cell { font-weight: 500; color: var(--sg-text-secondary); @@ -94,7 +190,7 @@ letter-spacing: 0.05em; align-self: end; grid-row: 2; - text-align: center; /* Center sub-cell text */ + text-align: center; } .broad-sub { @@ -109,6 +205,7 @@ .manual-sub { grid-column: 4; } + .keyword-input-row { margin-left: 0.5rem; width: 100%; @@ -121,30 +218,23 @@ &.compact { .small-field { flex: 10; - // collapse the outline field to a compact, chip-like height ::ng-deep .mat-mdc-text-field-wrapper { padding: 0 0.6rem; } - ::ng-deep .mat-mdc-form-field-flex { min-height: 8px; align-items: center; } - ::ng-deep .mat-mdc-form-field-infix { min-height: 8px; padding: 1rem 0; } - - // hide the hint/error subscript strip to remove extra height ::ng-deep .mat-mdc-form-field-subscript-wrapper { display: none; } - ::ng-deep input.mat-mdc-input-element { font-size: 0.8rem; } - ::ng-deep .mat-mdc-form-field-label, ::ng-deep mat-label { font-size: 1rem; @@ -159,15 +249,10 @@ flex: 1; .mat-icon { - font-size: 18px; - width: 18px; - height: 18px; - line-height: 18px; - } - - ::ng-deep .mat-mdc-button-touch-target { - width: 28px; - height: 28px; + font-size: 26px; + width: 26px; + height: 26px; + line-height: 26px; } } } @@ -179,10 +264,10 @@ column-gap: 1rem; row-gap: 0.4rem; align-items: start; - border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); /* Left border for columns */ + border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + //background: var(--sg-background-muted, #f4f5f7); } -/* Add vertical separators between columns */ .table-col { display: flex; flex-direction: column; @@ -195,16 +280,44 @@ border-right: none; } &:nth-child(3) { - border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)); } - mat-chip-listbox { + ::ng-deep app-topic-chip { width: 100%; - margin-top: 0.5rem; + } + + ::ng-deep app-topic-chip:not(.topic-chip--active) { + width: 100%; + opacity: 0.4; + } +} +.thick-border { + border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)); +} +.keyword-chip-stack { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin-top: 0.5rem; + width: 100%; +} + +.manual-chip-row { + display: flex; + align-items: center; + width: 100%; + + app-topic-chip { + flex: 1 1 auto; + min-width: 0; + } + + button[mat-icon-button] { + flex: 0 0 auto; } } -/* Make chips removable and add hover effect */ .compact-chip { font-size: 1rem; padding: 0.2rem 0.6rem; @@ -215,11 +328,9 @@ animation: popIn 0.2s ease-in-out; cursor: default; - // Add removable indicator and hover effect &.mat-mdc-chip-option { .mat-mdc-chip-action { padding: 0 4px; - .mat-mdc-chip-action-label { padding: 0 4px; display: flex; @@ -227,8 +338,6 @@ gap: 4px; } } - - // Show remove button on hover for removable chips &:hover { ::ng-deep .mat-mdc-chip-remove { opacity: 1; @@ -236,7 +345,6 @@ } } - // Style for removable chips ::ng-deep .mat-mdc-chip-remove { opacity: 0; transition: opacity 0.2s ease; @@ -287,17 +395,19 @@ display: flex; flex-wrap: wrap; gap: 0.5rem; - justify-content: flex-end; + justify-content: space-between; margin-top: 0.5rem; button { + display: flex; + justify-content: center; font-size: 0.75rem; padding: 0 12px; line-height: 30px; mat-icon { - font-size: 18px; - width: 18px; - height: 18px; + font-size: 26px; + width: 26px; + height: 26px; } } } @@ -308,13 +418,77 @@ margin-top: 0.5rem; } -/* Responsive: stack columns on small screens */ +/* ============================================================ + RESPONSIVE BREAKPOINTS + ============================================================ */ + +/* Tablet: soften columns, keep 4 columns but tighter */ +@media (max-width: 1024px) { + .table-head, + .table-body { + column-gap: 0.5rem; + } + + .table-col { + padding: 0.4rem; + } + + .compact-chip { + width: 100%; + } +} + +/* Small tablet / large phone: stack columns */ @media (max-width: 768px) { + .content { + padding: 0.75rem; + } + + .tab-content { + grid-template-columns: 1fr; + } + + .extract-btn { + width: 100%; + justify-content: center; + } + .table-head, .table-body { grid-template-columns: 1fr; } + .table-head { + display: none; /* labels are redundant once stacked; see column titles below */ + } + + .table-col { + border-right: none; + border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + padding: 0.75rem 0.25rem; + + &:nth-child(3) { + border-right: none; + border-bottom: 3px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + } + + &:last-child { + border-bottom: none; + } + + /* Re-introduce a column label since .table-head is hidden */ + &::before { + content: attr(data-col-label); + font-weight: 500; + font-size: 0.85rem; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--sg-text-secondary); + margin-bottom: 0.35rem; + display: block; + } + } + .extracted-header { grid-column: 1; grid-row: 1; @@ -325,37 +499,66 @@ grid-row: 2; } - .broad-sub { - grid-column: 1; - grid-row: 3; - } - .coarse-sub { - grid-column: 1; - grid-row: 4; - } - .fine-sub { - grid-column: 1; - grid-row: 5; - } - .actions { align-self: center; justify-content: flex-start; } - .search-container { - justify-content: flex-start; + .search-container, + .select-all-container { + justify-content: stretch; + flex-direction: column; } - .table-col { - border-right: none; /* Remove column borders on mobile */ - border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + .search-btn, + .select-all-container button { + width: 100%; + } - &:last-child { - border-bottom: none; + .view-toggle-row { + justify-content: center; + text-align: center; + } + + mat-button-toggle-group { + width: 100%; + + ::ng-deep .mat-button-toggle { + flex: 1; } } } + +/* Phone: tighten further, reduce chip/font sizes */ +@media (max-width: 480px) { + .content { + padding: 0.5rem; + gap: 0.5rem; + } + + .keyword-card { + padding: 0.35rem; + } + + .sub-cell, + .toggle-text { + font-size: 0.8rem; + } + + .compact-chip { + font-size: 0.85rem; + min-height: 24px; + } + + .empty-state { + font-size: 0.8rem; + } + + .status-message { + font-size: 0.8rem; + } +} + /* Source expansion panel */ .source-expansion { margin: 0.75rem 0; @@ -406,22 +609,19 @@ background: rgba(0, 0, 0, 0.03); } } + .progress-container { margin-top: 1rem; padding: 0.5rem 0; - // Make the progress bar container relative for the shimmer overlay mat-progress-bar { position: relative; - overflow: hidden; // keeps the shimmer inside the bar + overflow: hidden; - // --- Set the bar fill to a constant blue --- - // Using the primary blue (adjust to your preferred "hell blue") ::ng-deep .mat-progress-bar-fill::after { - background-color: #2196f3; // bright blue + background-color: #2196f3; } - // --- Shimmer overlay (a moving highlight) --- &::after { content: ''; position: absolute; @@ -429,7 +629,7 @@ left: 0; width: 100%; height: 100%; - pointer-events: none; // allow clicks to pass through + pointer-events: none; background: linear-gradient( 105deg, transparent 0%, diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 03a02061..e2dcc526 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -9,7 +9,6 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; -import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; import { MatDividerModule } from '@angular/material/divider'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; @@ -28,10 +27,27 @@ import { TopicsService } from '../../api/api/topics.service'; import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest'; import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component'; - +import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; +import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component'; +import { Topic } from '../../api/model/topic'; +import { + MatButtonToggleModule, + MatButtonToggleGroup, +} from '@angular/material/button-toggle'; +import { + topicHierarchyColor, + TopicHierarchyColorInput, +} from '../../resolvers/utils/topic-colors'; +import { + buildTopicLegendGroups, + TopicLegendGroup, + TopicLegendTopic, +} from '../../resolvers/utils/topic-legend'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { A11yModule } from '@angular/cdk/a11y'; type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; - +type KeywordView = 'llm' | 'topic'; @Component({ selector: 'app-keywords-search', imports: [ @@ -41,12 +57,17 @@ type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; MatInputModule, MatButtonModule, MatIconModule, - MatChipsModule, MatDividerModule, MatCardModule, MatExpansionModule, MatProgressBarModule, TopicAutocompleteComponent, + TopicChipComponent, + TopicLegendComponent, + MatButtonToggleModule, + MatButtonToggleGroup, + MatTooltipModule, + A11yModule, ], templateUrl: './keywords-search.component.html', styleUrl: './keywords-search.component.scss', @@ -67,50 +88,16 @@ export class KeywordsSearchComponent { private readonly fineKeywordEntries = signal([]); private readonly manualKeywordEntries = signal([]); - readonly broadKeywords = computed(() => - this.broadKeywordEntries().map((item) => this.getKeywordLabel(item)), - ); - readonly coarseKeywords = computed(() => - this.coarseKeywordEntries().map((item) => this.getKeywordLabel(item)), - ); - readonly fineKeywords = computed(() => - this.fineKeywordEntries().map((item) => this.getKeywordLabel(item)), - ); - readonly manualKeywords = computed(() => - this.manualKeywordEntries().map((item) => this.getKeywordLabel(item)), - ); + readonly broadKeywords = computed(() => this.broadKeywordEntries()); + readonly coarseKeywords = computed(() => this.coarseKeywordEntries()); + readonly fineKeywords = computed(() => this.fineKeywordEntries()); + readonly manualKeywords = computed(() => this.manualKeywordEntries()); readonly selectedKeywords = signal([]); readonly isExtracting = signal(false); + readonly loadingNewKeyword = signal(false); readonly extractionSource = signal(null); - // Single place mapping a category name to its label signal and its - // backing entries signal. Replaces four near-identical computed()s and - // a category switch statement that used to live below. - private readonly categoryKeywordsMap: Record< - KeywordCategory, - Signal - > = { - broad: this.broadKeywords, - coarse: this.coarseKeywords, - fine: this.fineKeywords, - manual: this.manualKeywords, - }; - private readonly categoryEntriesMap: Record< - KeywordCategory, - WritableSignal - > = { - broad: this.broadKeywordEntries, - coarse: this.coarseKeywordEntries, - fine: this.fineKeywordEntries, - manual: this.manualKeywordEntries, - }; - - readonly selectedBroadKeywords = this.selectedInCategory('broad'); - readonly selectedCoarseKeywords = this.selectedInCategory('coarse'); - readonly selectedFineKeywords = this.selectedInCategory('fine'); - readonly selectedManualKeywords = this.selectedInCategory('manual'); - readonly extractedKeywordsExist = computed( () => this.broadKeywords().length > 0 || @@ -133,6 +120,23 @@ export class KeywordsSearchComponent { readonly progress = signal(0); readonly statusMessage = signal(''); + readonly keywordView = signal('llm'); + readonly subfieldLegendVisible = signal(true); + readonly subfieldLegendExpanded = signal(false); + + get topicLegendGroups(): TopicLegendGroup[] { + const topics = [ + ...this.broadKeywordEntries(), + ...this.coarseKeywordEntries(), + ...this.fineKeywordEntries(), + ...this.manualKeywordEntries(), + ] + .map((entry) => entry.topic_mapping?.topic) + .filter((topic): topic is Topic => Boolean(topic)) + .map((topic) => this.toTopicLegendTopic(topic)); + + return buildTopicLegendGroups(topics); + } constructor( private readonly formBuilder: FormBuilder, @@ -188,6 +192,7 @@ export class KeywordsSearchComponent { this.handleStatusEvent(event); break; case 'keywords': + console.log(event.keywords); if (event.keywords) this.addExtractedKeyword(event.keywords); break; case 'completed': @@ -220,9 +225,12 @@ export class KeywordsSearchComponent { this.fineKeywordEntries.set([]); this.websocketService.close(); this.isExtracting.set(false); + this.loadingNewKeyword.set(false); // Keep manual, but remove selected that are not in manual this.selectedKeywords.set( - this.selectedKeywords().filter((k) => this.manualKeywords().includes(k)), + this.selectedKeywords().filter((k) => + this.getKeywordLabels(this.manualKeywords()).includes(k), + ), ); this.updateQueryParams(); } @@ -295,15 +303,17 @@ export class KeywordsSearchComponent { private keywordExists(keyword: string): boolean { const normalized = this.normalizeKeyword(keyword); return [ - ...this.broadKeywords(), - ...this.coarseKeywords(), - ...this.fineKeywords(), - ...this.manualKeywords(), + ...this.getKeywordLabels(this.broadKeywords()), + ...this.getKeywordLabels(this.coarseKeywords()), + ...this.getKeywordLabels(this.fineKeywords()), + ...this.getKeywordLabels(this.manualKeywords()), ].some((k) => this.normalizeKeyword(k) === normalized); } // Add manually from Keywords tab addKeywordFromInput(keyword: string): void { + this.loadingNewKeyword.set(true); + const normalizedKeyword = keyword.trim(); if (!normalizedKeyword) return; @@ -335,7 +345,7 @@ export class KeywordsSearchComponent { ...this.selectedKeywords(), normalizedKeyword, ]); - + this.loadingNewKeyword.set(false); // Explicit enrichment trigger for new keywords this.enrichManualKeywordsWithTopics([normalizedKeyword]); this.updateQueryParams(); @@ -350,29 +360,40 @@ export class KeywordsSearchComponent { this.updateQueryParams(); } - onCategoryChange( - category: KeywordCategory, - event: MatChipListboxChange, - ): void { - const newSelection = (event.value as string[]) || []; - const otherCategories = ( - Object.keys(this.categoryKeywordsMap) as KeywordCategory[] - ).filter((c) => c !== category); - const otherSelected = otherCategories.flatMap((c) => { - const keywords = this.categoryKeywordsMap[c](); - return this.selectedKeywords().filter((k) => keywords.includes(k)); - }); - const updated = [...otherSelected, ...newSelection]; - this.selectedKeywords.set(this.uniqueKeywords(updated)); + toggleKeywordSelection(keyword: KeywordEntryWithTopic): void { + const label = this.getKeywordLabel(keyword); + const nextSelection = this.selectedKeywords().includes(label) + ? this.selectedKeywords().filter((value) => value !== label) + : [...this.selectedKeywords(), label]; + + this.selectedKeywords.set(this.uniqueKeywords(nextSelection)); + this.updateQueryParams(); + } + + isKeywordSelected(keyword: KeywordEntryWithTopic): boolean { + const normalized = this.normalizeKeyword(this.getKeywordLabel(keyword)); + return this.selectedKeywords().some( + (value) => this.normalizeKeyword(value) === normalized, + ); + } + + removeManualKeyword(keyword: KeywordEntryWithTopic): void { + const label = this.getKeywordLabel(keyword); + this.manualKeywordEntries.set( + this.filterKeywordEntries(this.manualKeywordEntries(), label), + ); + this.selectedKeywords.set( + this.selectedKeywords().filter((value) => value !== label), + ); this.updateQueryParams(); } selectAllExtracted(): void { const all = [ - ...this.selectedManualKeywords(), - ...this.broadKeywords(), - ...this.coarseKeywords(), - ...this.fineKeywords(), + ...this.getKeywordLabels(this.manualKeywords()), + ...this.getKeywordLabels(this.broadKeywords()), + ...this.getKeywordLabels(this.coarseKeywords()), + ...this.getKeywordLabels(this.fineKeywords()), ]; this.selectedKeywords.set(this.uniqueKeywords(all)); this.updateQueryParams(); @@ -380,7 +401,7 @@ export class KeywordsSearchComponent { deselectAllExtracted(): void { this.selectedKeywords.set( - this.uniqueKeywords(this.selectedManualKeywords()), + this.uniqueKeywords(this.getKeywordLabels(this.manualKeywords())), ); this.updateQueryParams(); } @@ -393,7 +414,7 @@ export class KeywordsSearchComponent { this.sourceUrl.set(null); // Keep only selected keywords that are in the manual list - const manualSet = new Set(this.manualKeywords()); + const manualSet = new Set(this.getKeywordLabels(this.manualKeywords())); this.selectedKeywords.set( this.selectedKeywords().filter((k) => manualSet.has(k)), ); @@ -409,9 +430,9 @@ export class KeywordsSearchComponent { areAllExtractedSelected(): boolean { const allExtracted = [ - ...this.broadKeywords(), - ...this.coarseKeywords(), - ...this.fineKeywords(), + ...this.getKeywordLabels(this.broadKeywords()), + ...this.getKeywordLabels(this.coarseKeywords()), + ...this.getKeywordLabels(this.fineKeywords()), ]; return allExtracted.every((k) => this.selectedKeywords().includes(k)); } @@ -432,16 +453,6 @@ export class KeywordsSearchComponent { this.applyExtractedKeywords(keywords); } - onKeywordRemoved(category: KeywordCategory, keyword: string): void { - const entries = this.categoryEntriesMap[category]; - entries.set(this.filterKeywordEntries(entries(), keyword)); - - this.selectedKeywords.set( - this.selectedKeywords().filter((k) => k !== keyword), - ); - this.updateQueryParams(); - } - processExtractedKeywords(result: ExtractedKeywordsResponse): void { if (result === undefined || !result.results) return; @@ -454,10 +465,10 @@ export class KeywordsSearchComponent { // Keep only selected keywords that still exist in any category (including manual) const allExtracted = [ - ...this.broadKeywords(), - ...this.coarseKeywords(), - ...this.fineKeywords(), - ...this.manualKeywords(), + ...this.getKeywordLabels(this.broadKeywords()), + ...this.getKeywordLabels(this.coarseKeywords()), + ...this.getKeywordLabels(this.fineKeywords()), + ...this.getKeywordLabels(this.manualKeywords()), ]; this.selectedKeywords.set( this.selectedKeywords().filter((k) => allExtracted.includes(k)), @@ -516,17 +527,11 @@ export class KeywordsSearchComponent { // --- Helpers -------------------------------------------------------------- - private selectedInCategory(category: KeywordCategory): Signal { - return computed(() => - this.selectedKeywords().filter((k) => - this.categoryKeywordsMap[category]().includes(k), - ), - ); - } - private applyExtractedKeywords(keywords: ExtractedKeywords): void { const seenKeywords = new Set( - this.manualKeywords().map((keyword) => this.normalizeKeyword(keyword)), + this.getKeywordLabels(this.manualKeywords()).map((keyword) => + this.normalizeKeyword(keyword), + ), ); this.broadKeywordEntries.set( this.uniqueKeywordEntries(keywords.broad_keywords, seenKeywords), @@ -572,8 +577,93 @@ export class KeywordsSearchComponent { ); } + onViewToggleChange(value: KeywordView): void { + if (this.keywordView() !== value) { + this.keywordView.set(value); + } + this.updateQueryParams(); + } + + onSubfieldLegendVisibleChange(visible: boolean): void { + this.subfieldLegendVisible.set(visible); + this.updateQueryParams(); + } + + onSubfieldLegendExpandedChange(expanded: boolean): void { + this.subfieldLegendExpanded.set(expanded); + this.updateQueryParams(); + } + + // Use this instead of directly binding keyword.topic_mapping?.topic?.display_name + getChipLabel(keyword: KeywordEntryWithTopic): string { + if (this.keywordView() == 'llm') { + return keyword.llm_keyword?.keyword ?? ''; + } + return ( + keyword.topic_mapping?.topic?.display_name ?? + keyword.llm_keyword?.keyword ?? + '' + ); + } private getKeywordLabel(item: KeywordEntryWithTopic): string { - return item.llm_keyword.keyword.trim(); + return item.llm_keyword.keyword; + } + + private getKeywordLabels(items: KeywordEntryWithTopic[]): string[] { + return items.map((item) => this.getKeywordLabel(item)); + } + + private getTopic(item: KeywordEntryWithTopic) { + return item.topic_mapping?.topic ?? null; + } + + getChipDescription(item: KeywordEntryWithTopic): string | null { + return this.getTopic(item)?.description ?? null; + } + + getChipSubfieldName(item: KeywordEntryWithTopic): string | null { + return this.getTopic(item)?.subfield?.display_name ?? null; + } + + getChipFieldName(item: KeywordEntryWithTopic): string | null { + return this.getTopic(item)?.field?.display_name ?? null; + } + + getChipDomainName(item: KeywordEntryWithTopic): string | null { + return this.getTopic(item)?.domain?.display_name ?? null; + } + + getChipCount(item: KeywordEntryWithTopic): number | null { + const topic = this.getTopic(item); + return topic?.works_count ?? null; + } + + private toTopicLegendTopic(topic: Topic): TopicLegendTopic { + return { + id: topic.id ?? topic.display_name ?? '', + name: topic.display_name ?? '', + field_id: topic.field?.id ?? null, + field_name: topic.field?.display_name ?? null, + field_description: null, + domain_id: topic.domain?.id ?? null, + domain_name: topic.domain?.display_name ?? null, + domain_description: null, + subfield_id: topic.subfield?.id ?? null, + subfield_name: topic.subfield?.display_name ?? null, + subfield_description: null, + }; + } + + getTopicColor(topic: Topic | undefined | null): string { + const topicInput: TopicHierarchyColorInput = { + id: topic?.id ?? null, + name: topic?.display_name ?? null, + field_id: topic?.field?.id ?? null, + field_name: topic?.field?.display_name ?? null, + domain_id: topic?.domain?.id ?? null, + domain_name: topic?.domain?.display_name ?? null, + }; + return topicHierarchyColor(topicInput); } private keywordEntriesFromStrings( @@ -621,6 +711,9 @@ export class KeywordsSearchComponent { const manual = this.parseKeywordList(queryParams.get('manual')); 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'; this.isRestoringState = true; @@ -628,7 +721,9 @@ export class KeywordsSearchComponent { { selectedInputType: mode, urlInput, textInput }, { emitEvent: false }, ); - + this.keywordView.set(view as KeywordView); + this.subfieldLegendVisible.set(legend === 'on'); + this.subfieldLegendExpanded.set(legendExpanded === 'on'); this.extractionSource.set(source as InputMode); this.restoreSourceFromSession(); @@ -649,16 +744,24 @@ export class KeywordsSearchComponent { // clean up the selection to only include keywords that actually exist in const manualKeywordSet = new Set( - this.manualKeywords().map((k) => this.normalizeKeyword(k)), + this.getKeywordLabels(this.manualKeywords()).map((k) => + this.normalizeKeyword(k), + ), ); const broadKeywordSet = new Set( - this.broadKeywords().map((k) => this.normalizeKeyword(k)), + this.getKeywordLabels(this.broadKeywords()).map((k) => + this.normalizeKeyword(k), + ), ); const coarseKeywordSet = new Set( - this.coarseKeywords().map((k) => this.normalizeKeyword(k)), + this.getKeywordLabels(this.coarseKeywords()).map((k) => + this.normalizeKeyword(k), + ), ); const fineKeywordSet = new Set( - this.fineKeywords().map((k) => this.normalizeKeyword(k)), + this.getKeywordLabels(this.fineKeywords()).map((k) => + this.normalizeKeyword(k), + ), ); const validSelected = selected.filter( (k) => @@ -684,10 +787,19 @@ export class KeywordsSearchComponent { mode: this.form.controls.selectedInputType.value, url: this.toNullableParam(this.form.controls.urlInput.value), text: this.toNullableParam(this.form.controls.textInput.value), - broad: this.serializeKeywords(this.broadKeywords()), - coarse: this.serializeKeywords(this.coarseKeywords()), - fine: this.serializeKeywords(this.fineKeywords()), - manual: this.serializeKeywords(this.manualKeywords()), + view: this.keywordView(), + legend: this.subfieldLegendVisible() ? 'on' : 'off', + legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off', + broad: this.serializeKeywords( + this.getKeywordLabels(this.broadKeywords()), + ), + coarse: this.serializeKeywords( + this.getKeywordLabels(this.coarseKeywords()), + ), + fine: this.serializeKeywords(this.getKeywordLabels(this.fineKeywords())), + manual: this.serializeKeywords( + this.getKeywordLabels(this.manualKeywords()), + ), selected: this.serializeKeywords(this.selectedKeywords()), }; @@ -806,7 +918,6 @@ export class KeywordsSearchComponent { seenKeywords.add(normalized); uniqueValues.push(value.trim()); } - return uniqueValues; } From 0e80cc3fc36e631b7f6942ed98287184593ab9b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 5 Jul 2026 15:59:34 +0200 Subject: [PATCH 31/41] feat(auth): completed auth restructure --- .../main/inse/account_management/router.py | 48 +- .../main/inse/account_management/service.py | 18 +- service/src/main/inse/auth/model.py | 67 +- service/src/main/inse/auth/router.py | 18 +- service/src/main/inse/auth/service.py | 372 ++--- .../src/main/inse/auth/test_auth_service.py | 229 +-- .../inse/organization_management/router.py | 10 +- .../inse/organization_management/service.py | 12 +- webapp/src/app/api/.openapi-generator/FILES | 3 +- webapp/src/app/api/api/api.ts | 17 +- webapp/src/app/api/api/auth.service.ts | 96 +- webapp/src/app/api/api/iNSEService.service.ts | 498 +++--- .../src/app/api/api/organization.service.ts | 36 +- webapp/src/app/api/api/patents.service.ts | 955 ++++-------- webapp/src/app/api/api/topics.service.ts | 1339 ++++++----------- webapp/src/app/api/api/works.service.ts | 980 ++++-------- webapp/src/app/api/configuration.ts | 368 +++-- webapp/src/app/api/model/accessResponse.ts | 5 - webapp/src/app/api/model/accessToken.ts | 18 +- webapp/src/app/api/model/accountProfile.ts | 1 + webapp/src/app/api/model/bodyRequestOtk.ts | 22 +- .../api/model/createOrganizationRequest.ts | 10 +- .../api/model/extractedKeywordsResponse.ts | 30 +- .../model/{idToken.ts => idTokenMetadata.ts} | 16 +- ...countManagementModelOrganizationProfile.ts | 12 +- ...ationManagementModelOrganizationProfile.ts | 16 +- webapp/src/app/api/model/keywordTopicMatch.ts | 10 +- .../app/api/model/keywordsTopicsRequest.ts | 14 +- .../app/api/model/keywordsTopicsResponse.ts | 14 +- webapp/src/app/api/model/loginResponse.ts | 16 +- webapp/src/app/api/model/matchedAuthor.ts | 10 +- webapp/src/app/api/model/models.ts | 3 +- webapp/src/app/api/model/refreshToken.ts | 55 - webapp/src/app/api/model/tokenType.ts | 6 +- .../src/app/api/model/updateAccountRequest.ts | 1 + .../api/model/updateOrganizationRequest.ts | 12 +- .../modules/app-login/app-login.component.ts | 104 +- .../authentication.interceptor.ts | 151 +- .../app/shared/services/credential.service.ts | 462 +++--- .../ui/app-layout/app-layout.component.ts | 5 +- .../shared/ui/app-menu/app-menu.component.ts | 8 +- 41 files changed, 2434 insertions(+), 3633 deletions(-) rename webapp/src/app/api/model/{idToken.ts => idTokenMetadata.ts} (72%) delete mode 100644 webapp/src/app/api/model/refreshToken.ts diff --git a/service/src/main/inse/account_management/router.py b/service/src/main/inse/account_management/router.py index 82781fb0..81b22593 100644 --- a/service/src/main/inse/account_management/router.py +++ b/service/src/main/inse/account_management/router.py @@ -1,12 +1,11 @@ import uuid -from typing import Optional +from typing import Annotated, Optional -from fastapi import APIRouter, Depends, Query, Response, status -from sqlmodel import Session +from fastapi import APIRouter, Query, Response, status from inse.auth import service as auth_service -from inse.auth.model import AccessToken -from inse.database import get_session +from inse.auth.model import AccessTokenMetadata +from inse.database import SessionDep from inse.tags import Tags from . import service @@ -24,11 +23,10 @@ router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH]) @router.get( "/me", operation_id="getCurrentAccount", - response_model=AccountProfile, ) async def get_current_account( - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.get_current_account(session=session, access_token=access_token) @@ -36,16 +34,15 @@ async def get_current_account( @router.get( "", operation_id="listAccounts", - response_model=AccountPage, ) async def list_accounts( - page: int = Query(default=0, ge=0), - page_size: int = Query(default=25, ge=1, le=100), - offset: Optional[int] = Query(default=None, ge=0), - search: Optional[str] = Query(default=None), - organization_id: Optional[uuid.UUID] = Query(default=None), - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + page: Annotated[int, Query(ge=0)] = 0, + page_size: Annotated[int, Query(ge=1, le=100)] = 10, + offset: Annotated[int, Query(ge=0)] = 0, + search: Annotated[Optional[str], Query()] = None, + organization_id: Annotated[Optional[uuid.UUID], Query()] = None, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountPage: return service.list_accounts( session=session, @@ -61,13 +58,12 @@ async def list_accounts( @router.post( "", operation_id="createAccount", - response_model=AccountProfile, status_code=status.HTTP_201_CREATED, ) async def create_account( payload: CreateAccountRequest, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.create_account( session=session, @@ -79,11 +75,10 @@ async def create_account( @router.get( "/organizations", operation_id="listAccountOrganizations", - response_model=list[OrganizationProfile], ) async def list_organizations( - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> list[OrganizationProfile]: return service.list_organizations(session=session, access_token=access_token) @@ -91,13 +86,12 @@ async def list_organizations( @router.put( "/{account_id}", operation_id="updateAccount", - response_model=AccountProfile, ) async def update_account( account_id: uuid.UUID, payload: UpdateAccountRequest, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.update_account( session=session, @@ -114,8 +108,8 @@ async def update_account( ) async def delete_account( account_id: uuid.UUID, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> Response: service.delete_account( session=session, diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py index 9e0362ad..b9d9dfda 100644 --- a/service/src/main/inse/account_management/service.py +++ b/service/src/main/inse/account_management/service.py @@ -5,7 +5,7 @@ from fastapi import HTTPException, status from sqlmodel import Session, func, or_, select from inse.auth import service as auth_service -from inse.auth.model import AccessToken, Account, Organization, UserRole +from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole from .model import ( AccountPage, @@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool: return False -def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: +def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile: organization_name = account.organization.name if account.organization else "" return AccountProfile( id=account.id, @@ -55,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account: return account -def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None: +def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata) -> None: if token.effective_role == UserRole.SUPER_ADMIN: return if ( @@ -95,14 +95,14 @@ def _ensure_email_available( ) -def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile: +def get_current_account(session: Session, access_token: AccessTokenMetadata) -> AccountProfile: account = _get_account_or_404(session, access_token.effective_account_id) return _account_to_profile(account, access_token) def list_accounts( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, page: int, page_size: int, offset: Optional[int] = None, @@ -157,7 +157,7 @@ def list_accounts( def create_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, payload: CreateAccountRequest, ) -> AccountProfile: if not _is_admin(access_token.effective_role): @@ -207,7 +207,7 @@ def create_account( def list_organizations( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, ) -> list[OrganizationProfile]: if access_token.effective_role == UserRole.SUPER_ADMIN: organizations = session.exec( @@ -233,7 +233,7 @@ def list_organizations( def update_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, account_id: uuid.UUID, payload: UpdateAccountRequest, ) -> AccountProfile: @@ -307,7 +307,7 @@ def update_account( def delete_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, account_id: uuid.UUID, ) -> None: account = _get_account_or_404(session, account_id) diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 30888c03..fdd687a2 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -15,9 +15,9 @@ class UserRole(StrEnum): class TokenType(StrEnum): - ID_TOKEN = "ID" - REFRESH_TOKEN = "REFRESH" - ACCESS_TOKEN = "ACCESS" + ID_TOKEN = "ID_TOKEN" + REFRESH_TOKEN = "REFRESH_TOKEN" + ACCESS_TOKEN = "ACCESS_TOKEN" class Durable(SQLModel): @@ -129,37 +129,20 @@ class Secret(SQLModel, table=True): ) -class Token(BaseModel): - token_type: TokenType = Field( - description="The type of the token (ID, Refresh, or Access).", - ) +class BaseTokenData(BaseModel): real_account_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the real account associated with this token.", ) expires_at: datetime = Field( - index=True, - nullable=False, description="The timestamp indicating when the token will expire.", ) epoch: int = Field( default=0, - nullable=False, description="The epoch value for the token. Used for versioning of tokens.", ) - user_fingerprint_hash: str = Field( - index=True, - nullable=False, - description="A hash of the user's fingerprint to ensure the token is used by the same user.", - ) - raw_token: str = Field( - index=False, - nullable=False, - description="The raw token string.", - ) -class IdToken(Token): +class IdTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.ID_TOKEN, const=True, @@ -167,24 +150,23 @@ class IdToken(Token): ) -class AccessToken(Token): +class AccessTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.ACCESS_TOKEN, const=True, description="The type of the token, which is always ACCESS_TOKEN for this class.", ) + user_fingerprint_hash: str = Field( + description="A unique fingerprint of the user, used for additional security checks.", + ) effective_account_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", ) effective_role: UserRole = Field( default=UserRole.USER, - index=True, - nullable=False, description="The specific role this access token grants within its organization.", ) effective_organization_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the organization associated with this access token.", ) @@ -197,25 +179,46 @@ class AccessToken(Token): return self.effective_account_id != self.real_account_id -class RefreshToken(AccessToken): +class AccessToken(AccessTokenMetadata): + raw_token: str = Field( + description="The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.", + ) + + +class RefreshTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.REFRESH_TOKEN, const=True, description="The type of the token, which is always REFRESH_TOKEN for this class.", ) + effective_account_id: uuid.UUID = Field( + description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", + ) + effective_role: UserRole = Field( + default=UserRole.USER, + description="The specific role this access token grants within its organization.", + ) + effective_organization_id: uuid.UUID = Field( + description="The unique identifier of the organization associated with this access token.", + ) + + +class RefreshToken(RefreshTokenMetadata): + raw_token: str = Field( + description="The raw string representation of the refresh token. This is the actual token that can be used to obtain new access tokens.", + ) class LoginResponse(BaseModel): - id_token: IdToken = Field(description="The ID token issued upon successful login.") + id_token: IdTokenMetadata = Field( + description="The ID token issued upon successful login." + ) class AccessResponse(BaseModel): access_token: AccessToken = Field( description="The access token issued upon successful authentication." ) - refresh_token: RefreshToken = Field( - description="The refresh token issued alongside the access token for obtaining new access tokens." - ) class OtkResponse(BaseModel): diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index e80612bb..9c15079f 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -12,10 +12,11 @@ from inse.database import SessionDep, get_session from inse.auth.model import ( AccessResponse, AccessToken, - IdToken, + AccessTokenMetadata, + IdTokenMetadata, LoginResponse, OtkResponse, - RefreshToken, + RefreshTokenMetadata, ) logger = logging.getLogger(__name__) @@ -81,7 +82,7 @@ async def get_action_tokens( effective_account_id: Annotated[ uuid.UUID, Body(description="Effective account ID for the access token") ], - id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], + id_token: Annotated[IdTokenMetadata, auth_service.CurrentUserIdTokenPayloadDep], ) -> AccessResponse: logger.debug( "Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s", @@ -109,11 +110,14 @@ async def get_action_tokens( }, ) async def refresh_access_token( + response: Response, refresh_token: Annotated[ - RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep + RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep ], ) -> AccessToken: - return auth_service.refresh_access_token(refresh_token=refresh_token) + return auth_service.refresh_access_token( + response=response, refresh_token=refresh_token + ) @router.post( @@ -126,7 +130,7 @@ async def refresh_access_token( async def logout( session: Annotated[Session, Depends(get_session)], access_token: Annotated[ - AccessToken, + AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, ], ): @@ -151,7 +155,7 @@ async def change_password( Body(description="New password", min_length=8), ], access_token: Annotated[ - AccessToken, + AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, ], ): diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 7ea4737f..604085ab 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -4,22 +4,23 @@ import json import logging import secrets import uuid -from typing import Annotated, Any, Dict, Literal, Optional +from typing import Annotated, Any, Dict, Optional import jwt from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError -from fastapi import Depends, HTTPException, Request, Response, status +from fastapi import Cookie, Depends, HTTPException, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from inse.auth.model import ( AccessResponse, AccessToken, + AccessTokenMetadata, Account, - IdToken, + IdTokenMetadata, LoginResponse, Organization, OtkResponse, - RefreshToken, + RefreshTokenMetadata, Secret, TokenType, UserRole, @@ -29,9 +30,9 @@ from inse.database import get_session from sqlmodel import Session, select, func from inse.auth.email_service import send_email -ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days -REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes -ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes +ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days +REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day +ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes OTK_EXPIRATION_MINUTES = 15 # 15 minutes @@ -42,8 +43,11 @@ EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id" EPOCH_KEY = "epoch" USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" -ID_FP_COOKIE_KEY = "_Secure-Fgp-ID" -ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act" + +ACCESS_FP_COOKIE_KEY = "_Secure-Fgp-Acc" +ID_TOKEN_COOKIE_KEY = "id_token" +REFRESH_TOKEN_COOKIE_KEY = "refresh_token" + settings = get_settings() @@ -181,11 +185,7 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse: logger.debug("OTK request for email %s: account found: %s", email, account) - if ( - account is None - or account.deleted - or account.id is None - ): + if account is None or account.deleted or account.id is None: logger.warning("OTK request failed for email %s: account not found", email) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -332,9 +332,9 @@ def login( def _get_current_user_access_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> AccessToken: + secure_fgp: Annotated[str | None, Cookie(alias=ACCESS_FP_COOKIE_KEY)] = None, +) -> AccessTokenMetadata: """Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -345,18 +345,22 @@ def _get_current_user_access_token_payload( Returns: AccessToken: The verified access token payload. """ + if secure_fgp is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Access fingerprint cookie is missing", + ) token = credentials.credentials - access_token_payload = _verify_fp_token( - request=request, - cookie_key=ACT_FP_COOKIE_KEY, - token=token, + access_token_payload = _verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=token, session=session, ) # If reaches here, the access token is valid and the fingerprint matches - return AccessToken( + return AccessTokenMetadata( real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( @@ -368,15 +372,13 @@ def _get_current_user_access_token_payload( access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] ), user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) def _get_current_user_refresh_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> RefreshToken: + token: Annotated[str | None, Cookie(alias=REFRESH_TOKEN_COOKIE_KEY)] = None, +) -> RefreshTokenMetadata: """Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -385,18 +387,20 @@ def _get_current_user_refresh_token_payload( credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token. Returns: - RefreshToken: The verified refresh token payload. + RefreshTokenData: The verified refresh token payload. """ - token = credentials.credentials + if token is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Refresh token cookie is missing", + ) - refresh_token_payload = _verify_fp_token( - request=request, - cookie_key=ACT_FP_COOKIE_KEY, - token=token, + refresh_token_payload = _verify_refresh_token( + raw_refresh_token=token, session=session, ) # If reaches here, the refresh token is valid and the fingerprint matches - refresh_token = RefreshToken( + refresh_token = RefreshTokenMetadata( real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( @@ -407,8 +411,6 @@ def _get_current_user_refresh_token_payload( effective_organization_id=uuid.UUID( refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] ), - user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) logger.debug("Extracted refresh token payload: %s", refresh_token) @@ -418,9 +420,8 @@ def _get_current_user_refresh_token_payload( def _get_current_user_id_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> IdToken: + token: Annotated[str | None, Cookie(alias=ID_TOKEN_COOKIE_KEY)] = None, +) -> IdTokenMetadata: """Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -431,30 +432,24 @@ def _get_current_user_id_token_payload( Returns: IdToken: The verified ID token payload. """ - logger.debug( - "Verifying ID token for request %s with credentials %s", - request.url, - credentials, - ) - token = credentials.credentials - logger.debug("Verifying ID token for request %s with token %s", request.url, token) + if token is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="ID token cookie is missing", + ) - id_token_payload = _verify_fp_token( - request=request, - cookie_key=ID_FP_COOKIE_KEY, - token=token, + id_token_payload = _verify_id_token( + raw_id_token=token, session=session, ) # If reaches here, the ID token is valid and the fingerprint matches - return IdToken( + return IdTokenMetadata( real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( id_token_payload["exp"], tz=datetime.timezone.utc ), epoch=id_token_payload[EPOCH_KEY], - user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) @@ -583,26 +578,10 @@ def _is_valid_impersonation( def get_access_token( response: Response, session: Session, - id_token: IdToken, + id_token: IdTokenMetadata, real_account_id: uuid.UUID, effective_account_id: Optional[uuid.UUID] = None, ) -> AccessResponse: - """Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies. - - Args: - request (Request): The FastAPI request object containing the cookies. - response (Response): The FastAPI response object to which the cookies will be added. - id_token (str): The ID token to verify. - real_account_id (uuid.UUID): The unique identifier of the real account associated with this token. - effective_account_id (Optional[uuid.UUID], optional): The unique identifier of the effective account associated with this token. If not provided, it defaults to the real account ID. - - Raises: - HTTPException: If the ID token is invalid, expired, or does not match the real account ID. - HTTPException: If impersonation is not allowed. - - Returns: - AccessResponse: An object containing the generated access and refresh tokens. - """ # IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here. if real_account_id != id_token.real_account_id: @@ -617,16 +596,15 @@ def get_access_token( if effective_account_id is None: effective_account_id = real_account_id - elif effective_account_id != real_account_id: - if not _is_valid_impersonation( - session=session, - real_account_id=real_account_id, - effective_account_id=effective_account_id, - ): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Impersonation not allowed", - ) + elif effective_account_id != real_account_id and not _is_valid_impersonation( + session=session, + real_account_id=real_account_id, + effective_account_id=effective_account_id, + ): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Impersonation not allowed", + ) role = _get_account_role(session=session, account_id=effective_account_id) epoch = _get_account_epoch(account_id=effective_account_id, session=session) @@ -634,7 +612,7 @@ def get_access_token( session=session, account_id=effective_account_id ) - user_fingerprint_hash = _set_act_fp_cookie(response=response) + user_fingerprint_hash = _set_access_fp_cookie(response=response) access_token = _build_access_token( real_account_id=real_account_id, @@ -644,77 +622,96 @@ def get_access_token( epoch=epoch, user_fingerprint_hash=user_fingerprint_hash, ) - refresh_token = _build_refresh_token( + _set_refresh_token( + response=response, real_account_id=real_account_id, effective_account_id=effective_account_id, effective_role=role, effective_organization_id=organization_id, epoch=epoch, - user_fingerprint_hash=user_fingerprint_hash, ) return AccessResponse( access_token=access_token, - refresh_token=refresh_token, ) -def _set_id_fp_cookie(response: Response) -> str: - """Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint. +def _set_id_token_cookie(response: Response, raw_id_token: str) -> None: + """Sets a secure cookie for the ID token. Args: response (Response): The FastAPI response object to which the cookie will be added. - - Returns: - str: The hashed value of the fingerprint. + raw_id_token (str): The raw string representation of the ID token. """ - return _set_fingerprint_cookie( - response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 + _set_token_cookie( + response=response, + cookie_name=ID_TOKEN_COOKIE_KEY, + token=raw_id_token, + max_age=ID_TOKEN_EXPIRATION_MINUTES * 60, ) -def _set_act_fp_cookie(response: Response) -> str: +def _set_refresh_token_cookie(response: Response, raw_refresh_token: str) -> None: + """Sets a secure cookie for the refresh token. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + raw_refresh_token (str): The raw string representation of the refresh token. + """ + _set_token_cookie( + response=response, + cookie_name=REFRESH_TOKEN_COOKIE_KEY, + token=raw_refresh_token, + max_age=REFRESH_TOKEN_EXPIRATION_MINUTES * 60, + ) + + +def _set_token_cookie( + response: Response, cookie_name: str, token: str, max_age: int +) -> None: + """Sets a secure cookie for the specified token. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + cookie_name (str): The name of the cookie to set. + token (str): The raw string representation of the token. + max_age (int): The maximum age of the cookie in seconds. + """ + secure = False if settings.environment == "dev" else True + response.set_cookie( + key=cookie_name, + value=token, + httponly=True, + secure=secure, + samesite="strict", + max_age=max_age, + ) + + +def _set_access_fp_cookie(response: Response) -> str: """Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint. Args: response (Response): The FastAPI response object to which the cookie will be added. - Returns: - str: The hashed value of the fingerprint. - """ - return _set_fingerprint_cookie( - response, ACT_FP_COOKIE_KEY - ) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. - - -def _set_fingerprint_cookie( - response: Response, - key: Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"], - max_age: Optional[int] = None, -) -> str: - """Sets a secure fingerprint cookie and returns the hashed value of the fingerprint. - - Args: - response (Response): The FastAPI response object to which the cookie will be added. - key (Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"]): The name of the cookie to set. - max_age (Optional[int], optional): The maximum age of the cookie in seconds. Defaults to None. - Returns: str: The hashed value of the fingerprint. """ user_fingerprint = secrets.token_hex(50) secure = False if settings.environment == "dev" else True response.set_cookie( - key=key, + key=ACCESS_FP_COOKIE_KEY, value=user_fingerprint, httponly=True, secure=secure, samesite="strict", - max_age=max_age, + max_age=None, # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. ) return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() -def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: +def refresh_access_token( + response: Response, refresh_token: RefreshTokenMetadata +) -> AccessToken: """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. Args: @@ -727,25 +724,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: """ # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. - return _refresh_access_token( - refresh_token=refresh_token, - ) - - -def _refresh_access_token( - refresh_token: RefreshToken, -) -> AccessToken: - """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. - - Args: - request (Request): The FastAPI request object containing the cookies. - refresh_token (RefreshToken): The refresh token to verify. - current_user_epoch (int): The epoch value for the tokens. - - Returns: - AccessToken: The refreshed access token. - """ - # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. + user_fingerprint_hash = _set_access_fp_cookie(response=response) return _build_access_token( real_account_id=refresh_token.real_account_id, @@ -753,7 +732,7 @@ def _refresh_access_token( effective_role=refresh_token.effective_role, effective_organization_id=refresh_token.effective_organization_id, epoch=refresh_token.epoch, - user_fingerprint_hash=refresh_token.user_fingerprint_hash, + user_fingerprint_hash=user_fingerprint_hash, ) @@ -761,7 +740,7 @@ def _build_id_token( response: Response, real_account_id: uuid.UUID, epoch: int, -) -> IdToken: +) -> IdTokenMetadata: """Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie. Args: @@ -776,34 +755,31 @@ def _build_id_token( expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( minutes=ID_TOKEN_EXPIRATION_MINUTES ) - user_fingerprint_hash = _set_id_fp_cookie(response) payload = { REAL_ACCOUNT_ID_KEY: str(real_account_id), EPOCH_KEY: epoch, - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } raw_token = _build_token( payload=payload, expiration_datetime=expires_at, token_type=TokenType.ID_TOKEN, ) - return IdToken( + _set_id_token_cookie(response=response, raw_id_token=raw_token) + return IdTokenMetadata( real_account_id=real_account_id, expires_at=expires_at, epoch=epoch, - user_fingerprint_hash=user_fingerprint_hash, - raw_token=raw_token, ) -def _build_refresh_token( +def _set_refresh_token( + response: Response, real_account_id: uuid.UUID, effective_account_id: uuid.UUID, effective_role: UserRole, effective_organization_id: uuid.UUID, epoch: int, - user_fingerprint_hash: str, -) -> RefreshToken: +) -> RefreshTokenMetadata: """Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. Args: @@ -816,7 +792,7 @@ def _build_refresh_token( user_fingerprint_hash (str): The hashed value of the user's fingerprint. Returns: - RefreshToken: The generated refresh token object. + RefreshTokenMetadata: The generated refresh token object. """ expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( minutes=REFRESH_TOKEN_EXPIRATION_MINUTES @@ -827,7 +803,6 @@ def _build_refresh_token( EFFECTIVE_ROLE_KEY: effective_role.value, EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id), EPOCH_KEY: epoch, - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } raw_token = _build_token( @@ -835,16 +810,14 @@ def _build_refresh_token( expiration_datetime=expires_at, token_type=TokenType.REFRESH_TOKEN, ) - - return RefreshToken( + _set_refresh_token_cookie(response=response, raw_refresh_token=raw_token) + return RefreshTokenMetadata( real_account_id=real_account_id, effective_account_id=effective_account_id, expires_at=expires_at, epoch=epoch, effective_role=effective_role, effective_organization_id=effective_organization_id, - user_fingerprint_hash=user_fingerprint_hash, - raw_token=raw_token, ) @@ -931,18 +904,57 @@ def _build_token( return token -def _verify_fp_token( - request: Request, - cookie_key: str, - token: str, - session: Session, -) -> Dict[str, Any]: - """Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid. +def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]: + """Verifies the provided ID token and returns the decoded payload if valid. Args: - request (Request): The FastAPI request object containing the cookies. - cookie_key (str): The name of the cookie that contains the fingerprint. - token (str): The JWT token to verify. + raw_id_token (str): The JWT ID token to verify. + session (Session): The database session. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT ID token if verification is successful. + """ + payload = _extract_valid_token_payload(session, raw_id_token) + return payload + + +def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]: + """Verifies the provided refresh token and returns the decoded payload if valid. + + Args: + raw_refresh_token (str): The JWT refresh token to verify. + session (Session): The database session. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT refresh token if verification is successful. + """ + payload = _extract_valid_token_payload(session, raw_refresh_token) + return payload + + +def _verify_access_token_fp( + secure_fgp: str, + raw_access_token: str, + session: Session, +) -> Dict[str, Any]: + """Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid. + + Args: + secure_fgp (str): The secure fingerprint value. + raw_access_token (str): The JWT token to verify. + session (Session): The database session. Raises: ValueError: If the token HMAC key is not set in the configuration. @@ -954,19 +966,29 @@ def _verify_fp_token( Returns: Dict[str, Any]: The decoded payload of the JWT token if verification is successful. """ - if not settings.token_hmac_key: - raise ValueError("Token HMAC key is not set in the configuration.") - - secure_fgp = request.cookies.get(cookie_key) - if not secure_fgp: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Fingerprint cookie missing", - ) fingerprint_bytes = secure_fgp.encode("utf-8") expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest() + payload = _extract_valid_token_payload(session, raw_access_token) + + token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) + if ( + not token_fingerprint_hash + or token_fingerprint_hash != expected_fingerprint_hash + ): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid context fingerprint", + ) + + return payload + + +def _extract_valid_token_payload(session: Session, token: str): + if not settings.token_hmac_key: + raise ValueError("Token HMAC key is not set in the configuration.") + try: payload = jwt.decode( token, @@ -975,23 +997,12 @@ def _verify_fp_token( issuer=settings.token_issuer_id, ) - token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) - if ( - not token_fingerprint_hash - or token_fingerprint_hash != expected_fingerprint_hash - ): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid context fingerprint", - ) - real_account_id = payload.get(REAL_ACCOUNT_ID_KEY) if not real_account_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing real account ID", ) - epoch_account_id = uuid.UUID(real_account_id) effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY) @@ -1014,7 +1025,6 @@ def _verify_fp_token( ) return payload - except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -1056,7 +1066,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: return account -def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: +def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]: """Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account. Args: @@ -1080,7 +1090,7 @@ def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: def change_password( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, current_password: str, new_password: str, ) -> Dict[str, str]: diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 0e61130c..728a61ee 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -14,9 +14,10 @@ from inse.auth.model import ( Account, Organization, Secret, - IdToken, AccessToken, - RefreshToken, + IdTokenMetadata, + AccessTokenMetadata, + RefreshTokenMetadata, UserRole, ) @@ -61,6 +62,19 @@ def create_org_and_account( return org, acc +def _get_cookie_value(response: Response, cookie_name: str) -> str: + for header_name, header_value in getattr(response, "raw_headers", []): + if header_name.lower() == b"set-cookie": + cookie_header = header_value.decode("latin-1") + if cookie_header.startswith(f"{cookie_name}="): + return cookie_header.split(";", 1)[0].split("=", 1)[1] + + header = response.headers.get("set-cookie") + assert header is not None + assert header.startswith(f"{cookie_name}=") + return header.split(";", 1)[0].split("=", 1)[1] + + def test_hash_and_verify_password(): pw = "s3cret-password" h = auth_service._hash_password(pw) @@ -80,8 +94,8 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): assert acc.id is not None resp = auth_service.request_otk(in_memory_session, email, password) - assert resp["status"] == "ok" - assert resp["account_id"] == str(acc.id) + assert resp.status == "success" + assert resp.account_id == acc.id secret = in_memory_session.exec( select(Secret).where(Secret.account_id == acc.id) @@ -93,9 +107,12 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): login_result = auth_service.login( in_memory_session, response, acc.id, secret.secret_value ) - assert isinstance(login_result.id_token, IdToken) + assert isinstance(login_result.id_token, IdTokenMetadata) assert login_result.id_token.real_account_id == acc.id - assert login_result.id_token.user_fingerprint_hash is not None + + raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY) + payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session) + assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): @@ -108,35 +125,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - assert isinstance(id_token, IdToken) + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) + assert isinstance(access_token, AccessToken) - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - assert cookie_header is not None - cookie_value = cookie_header.split("=")[1].split(";")[0] - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - - req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}) - payload = auth_service._verify_fp_token( - request=req, - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + payload = auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=access_token.raw_token, session=in_memory_session, ) assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) with pytest.raises(Exception): - auth_service._verify_fp_token( - request=DummyReq({}), - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="bad-fingerprint", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -158,11 +169,30 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): access_response = auth_service.get_access_token( response, in_memory_session, id_token, acc.id ) - assert isinstance(access_response.access_token, AccessToken) - assert isinstance(access_response.refresh_token, RefreshToken) + assert isinstance(access_response.access_token, AccessTokenMetadata) - refreshed = auth_service.refresh_access_token(access_response.refresh_token) - assert isinstance(refreshed, AccessToken) + raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + refresh_payload = auth_service._verify_refresh_token( + raw_refresh_token=raw_refresh_token, + session=in_memory_session, + ) + refresh_token = RefreshTokenMetadata( + real_account_id=uuid.UUID(refresh_payload[auth_service.REAL_ACCOUNT_ID_KEY]), + effective_account_id=uuid.UUID( + refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY] + ), + expires_at=_dt.datetime.fromtimestamp( + refresh_payload["exp"], tz=_dt.timezone.utc + ), + epoch=refresh_payload[auth_service.EPOCH_KEY], + effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]), + effective_organization_id=uuid.UUID( + refresh_payload[auth_service.EFFECTIVE_ORGANIZATION_ID_KEY] + ), + ) + + refreshed = auth_service.refresh_access_token(Response(), refresh_token) + assert isinstance(refreshed, AccessTokenMetadata) assert refreshed.real_account_id == access_response.access_token.real_account_id @@ -233,6 +263,7 @@ def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_sess in_memory_session.add(account) in_memory_session.commit() + assert account.id is not None with pytest.raises(HTTPException) as error: auth_service._get_active_account(in_memory_session, account.id) @@ -268,24 +299,20 @@ def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="badcookie", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -300,28 +327,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) acc.epoch += 1 in_memory_session.add(acc) in_memory_session.commit() with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -336,25 +360,21 @@ def test_invalid_token_signature_raises(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) + secure_fgp = auth_service._set_access_fp_cookie(response) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp, + ) - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - - bad_token = id_token.raw_token + "x" + bad_token = access_token.raw_token + "x" with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=bad_token, + auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=bad_token, session=in_memory_session, ) @@ -391,7 +411,7 @@ def test_impersonation_rules(in_memory_session, settings_backup): real_acc.id, effective_account_id=eff_acc.id, ) - assert isinstance(access_resp.access_token, AccessToken) + assert isinstance(access_resp.access_token, AccessTokenMetadata) def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): @@ -425,7 +445,7 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): login_res = auth_service.login( in_memory_session, Response(), acc.id, secret2.secret_value ) - assert isinstance(login_res.id_token, IdToken) + assert isinstance(login_res.id_token, IdTokenMetadata) def test_otk_deleted_after_login(in_memory_session, settings_backup): @@ -461,7 +481,7 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - raw = auth_service._set_act_fp_cookie(response) + raw_hash = auth_service._set_access_fp_cookie(response) access_token = auth_service._build_access_token( real_account_id=acc.id, @@ -469,18 +489,13 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup): effective_role=acc.role, effective_organization_id=acc.organization_id, epoch=acc.epoch, - user_fingerprint_hash=raw, + user_fingerprint_hash=raw_hash, ) - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore - cookie_key=auth_service.ACT_FP_COOKIE_KEY, - token=access_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="wrongcookie", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -495,34 +510,26 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup): assert acc.id is not None response = Response() - cookie_raw = auth_service._set_id_fp_cookie(response) past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5) + access_fingerprint_hash = auth_service._set_access_fp_cookie(response) payload = { auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EFFECTIVE_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EFFECTIVE_ROLE_KEY: acc.role.value, + auth_service.EFFECTIVE_ORGANIZATION_ID_KEY: str(acc.organization_id), auth_service.EPOCH_KEY: acc.epoch, - auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw, + auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash, } bad_token = auth_service._build_token( payload=payload, expiration_datetime=past, - token_type=auth_service.TokenType.ID_TOKEN, + token_type=auth_service.TokenType.ACCESS_TOKEN, ) - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq( - { - auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"] - .split("=")[1] - .split(";")[0] - } - ), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=bad_token, + auth_service._verify_access_token_fp( + secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY), + raw_access_token=bad_token, session=in_memory_session, ) diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py index 0a8b82ca..5a2db2bd 100644 --- a/service/src/main/inse/organization_management/router.py +++ b/service/src/main/inse/organization_management/router.py @@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Response, status from sqlmodel import Session from inse.auth import service as auth_service -from inse.auth.model import AccessToken +from inse.auth.model import AccessTokenMetadata from inse.database import get_session from inse.tags import Tags @@ -26,7 +26,7 @@ async def get_organizations( page_size: int = Query(default=25, ge=1, le=100), offset: Optional[int] = Query(default=None, ge=0), session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationPage: return service.get_organizations( session=session, @@ -46,7 +46,7 @@ async def get_organizations( async def create_organization( payload: CreateOrganizationRequest, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationProfile: return service.create_organization(session, access_token, payload) @@ -60,7 +60,7 @@ async def update_organization( organization_id: uuid.UUID, payload: UpdateOrganizationRequest, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationProfile: return service.update_organization( session, access_token, organization_id, payload @@ -75,7 +75,7 @@ async def update_organization( async def delete_organization( organization_id: uuid.UUID, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> Response: service.delete_organization(session, access_token, organization_id) return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 80dd88c9..528bcf35 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -4,7 +4,7 @@ from typing import Optional from fastapi import HTTPException, status from sqlmodel import Session, func, select -from inse.auth.model import AccessToken, Account, Organization, UserRole +from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole from .model import ( CreateOrganizationRequest, @@ -14,7 +14,7 @@ from .model import ( ) -def _require_super_admin(access_token: AccessToken) -> None: +def _require_super_admin(access_token: AccessTokenMetadata) -> None: if access_token.effective_role != UserRole.SUPER_ADMIN: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -109,7 +109,7 @@ def _deactivate_organization_accounts( def get_organizations( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, page: int, page_size: int, offset: Optional[int] = None, @@ -145,7 +145,7 @@ def get_organizations( def create_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, payload: CreateOrganizationRequest, ) -> OrganizationProfile: _require_super_admin(access_token) @@ -164,7 +164,7 @@ def create_organization( def update_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, organization_id: uuid.UUID, payload: UpdateOrganizationRequest, ) -> OrganizationProfile: @@ -191,7 +191,7 @@ def update_organization( def delete_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, organization_id: uuid.UUID, ) -> None: _require_super_admin(access_token) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index e59c1083..f9ac2e32 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -113,7 +113,7 @@ model/hEUReportSummary.ts model/hEUTopic.ts model/hEUWebLink.ts model/hTTPValidationError.ts -model/idToken.ts +model/idTokenMetadata.ts model/inseAccountManagementModelOrganizationProfile.ts model/inseOrganizationManagementModelOrganizationProfile.ts model/institution.ts @@ -161,7 +161,6 @@ model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/rankingResponse.ts -model/refreshToken.ts model/score.ts model/sortDirection.ts model/tokenType.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 8ea55e0b..817a3a65 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -26,19 +26,4 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [ - AuthService, - CompanyConnectionsService, - FundingService, - INSEServiceService, - InstitutionsService, - KeywordsService, - NewsService, - OrganizationService, - PatentsService, - PersonNetworkService, - PersonsService, - ProjectsService, - TopicsService, - WorksService, -]; +export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService]; diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index ef111294..086a0e47 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -66,13 +66,14 @@ export class AuthService extends BaseService { * Change the user\'s password and invalidate existing tokens. * @endpoint post /api/auth/v2/change-password * @param bodyChangePassword + * @param secureFgpAcc * @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 changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (bodyChangePassword === null || bodyChangePassword === undefined) { throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.'); } @@ -134,13 +135,14 @@ export class AuthService extends BaseService { * Create Account * @endpoint post /api/accounts * @param createAccountRequest + * @param secureFgpAcc * @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 createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (createAccountRequest === null || createAccountRequest === undefined) { throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.'); } @@ -202,13 +204,14 @@ export class AuthService extends BaseService { * Delete Account * @endpoint delete /api/accounts/{account_id} * @param accountId + * @param secureFgpAcc * @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 deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (accountId === null || accountId === undefined) { throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.'); } @@ -261,22 +264,20 @@ export class AuthService extends BaseService { * Retrieve an access token for the authenticated user. * @endpoint post /api/auth/v2/access * @param bodyGetAccessToken + * @param idToken * @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 getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) { throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.'); } let localVarHeaders = this.defaultHeaders; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -328,13 +329,14 @@ export class AuthService extends BaseService { /** * Get Current Account * @endpoint get /api/accounts/me + * @param secureFgpAcc * @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 getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; @@ -433,13 +435,14 @@ export class AuthService extends BaseService { /** * List Organizations * @endpoint get /api/accounts/organizations + * @param secureFgpAcc * @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 listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; - public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; @@ -492,13 +495,14 @@ export class AuthService extends BaseService { * @param offset * @param search * @param organizationId + * @param secureFgpAcc * @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 listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -626,13 +630,14 @@ export class AuthService extends BaseService { * Logout * Logout the authenticated user. * @endpoint post /api/auth/v2/logout + * @param secureFgpAcc * @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 logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; @@ -681,19 +686,17 @@ export class AuthService extends BaseService { * Refresh Access Token * Refresh the access token using a valid refresh token. * @endpoint post /api/auth/v2/refresh + * @param refreshToken * @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 refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarHeaders = this.defaultHeaders; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ 'application/json' ]); @@ -803,13 +806,14 @@ export class AuthService extends BaseService { * @endpoint put /api/accounts/{account_id} * @param accountId * @param updateAccountRequest + * @param secureFgpAcc * @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 updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (accountId === null || accountId === undefined) { throw new Error('Required parameter accountId was null or undefined when calling updateAccount.'); } diff --git a/webapp/src/app/api/api/iNSEService.service.ts b/webapp/src/app/api/api/iNSEService.service.ts index da26fff7..1149c309 100644 --- a/webapp/src/app/api/api/iNSEService.service.ts +++ b/webapp/src/app/api/api/iNSEService.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,355 +9,205 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class INSEServiceService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @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 buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'page_size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - saveJson, - 'save_json', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); - 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 localVarHeaders = this.defaultHeaders; - let localVarPath = `/api/inse-service/topics/cache`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @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 countTopicHierarchy( - topic: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public countTopicHierarchy( - topic: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling countTopicHierarchy.', - ); - } + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + 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/cache`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - let localVarHeaders = this.defaultHeaders; + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @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 countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } + + 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/count`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * 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; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - 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'; - } + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/count`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns 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; - public getTopicHierarchy( - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - 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( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts index 2af0ed8b..14fb942d 100644 --- a/webapp/src/app/api/api/organization.service.ts +++ b/webapp/src/app/api/api/organization.service.ts @@ -47,13 +47,14 @@ export class OrganizationService extends BaseService { * Create Organization * @endpoint post /api/organizations * @param createOrganizationRequest + * @param secureFgpAcc * @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 createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (createOrganizationRequest === null || createOrganizationRequest === undefined) { throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.'); } @@ -115,13 +116,14 @@ export class OrganizationService extends BaseService { * Delete Organization * @endpoint delete /api/organizations/{organization_id} * @param organizationId + * @param secureFgpAcc * @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 deleteOrganisation(organizationId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (organizationId === null || organizationId === undefined) { throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.'); } @@ -175,13 +177,14 @@ export class OrganizationService extends BaseService { * @param page * @param pageSize * @param offset + * @param secureFgpAcc * @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 getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, @@ -240,13 +243,14 @@ export class OrganizationService extends BaseService { * @endpoint put /api/organizations/{organization_id} * @param organizationId * @param updateOrganizationRequest + * @param secureFgpAcc * @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 updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (organizationId === null || organizationId === undefined) { throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); } diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 904279c3..669a7496 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AllPatentsResponse } from '../model/allPatentsResponse'; @@ -36,657 +30,338 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class PatentsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Get all patents with pagination and search. - * @endpoint get /api/inse-service/patents - * @param page - * @param size - * @param search - * @param source - * @param sortBy - * @param sortDirection - * @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 getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllPatents( - page?: number, - size?: number, - search?: string, - source?: string, - sortBy?: string, - sortDirection?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - search, - 'search', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - source, - 'source', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortBy, - 'sort_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sortDirection, - 'sort_direction', - ); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get all patents with pagination and search. + * @endpoint get /api/inse-service/patents + * @param page + * @param size + * @param search + * @param source + * @param sortBy + * @param sortDirection + * @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 getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + source, 'source'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortDirection, 'sort_direction'); - 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 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/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Get pre-indexed org patents for an institution. + * @endpoint get /api/inse-service/institutions/{id}/org-patents + * @param id + * @param matchType Filter patents by match type. + * @param page + * @param size + * @param source + * @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 getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getOrgPatentsByInstitution.'); + } - /** - * Get pre-indexed org patents for an institution. - * @endpoint get /api/inse-service/institutions/{id}/org-patents - * @param id - * @param matchType Filter patents by match type. - * @param page - * @param size - * @param source - * @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 getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getOrgPatentsByInstitution( - id: string, - matchType?: 'institution' | 'name' | 'both' | 'all', - page?: number, - size?: number, - source?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getOrgPatentsByInstitution.', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + matchType, 'match_type'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + source, 'source'); + + 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/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/org-patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - matchType, - 'match_type', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - source, - 'source', - ); + /** + * Returns one publication by OpenAlex ID or DOI. + * @endpoint get /api/inse-service/patents/{identifier} + * @param identifier + * @param prefix Application Prefix (EP or US) + * @param title Do we want to fallback to title search if ID and DOI dont work? + * @param fillingDate Filling date in YYYY-MM-DD format + * @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 getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (identifier === null || identifier === undefined) { + throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + prefix, 'prefix'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fillingDate, 'filling_date'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + 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/patents/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Get patents matched to an author by name. + * @endpoint get /api/inse-service/authors/{author_id}/patents + * @param authorId + * @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 getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarHeaders = this.defaultHeaders; - 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'; - } + 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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/org-patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Get patents matched to an institution by assignee name. + * @endpoint get /api/inse-service/institutions/{id}/patents + * @param id + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPatentsByInstitution(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPatentsByInstitution(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByInstitution(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPatentsByInstitution(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (id === null || id === undefined) { + throw new Error('Required parameter id was null or undefined when calling getPatentsByInstitution.'); + } - /** - * Returns one publication by OpenAlex ID or DOI. - * @endpoint get /api/inse-service/patents/{identifier} - * @param identifier - * @param prefix Application Prefix (EP or US) - * @param title Do we want to fallback to title search if ID and DOI dont work? - * @param fillingDate Filling date in YYYY-MM-DD format - * @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 getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentByIdOrTitle( - identifier: string, - prefix?: string, - title?: string, - fillingDate?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (identifier === null || identifier === undefined) { - throw new Error( - 'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.', - ); + 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/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - prefix, - 'prefix', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - title, - 'title', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - fillingDate, - 'filling_date', - ); - - 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/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Get patents matched to an author by name. - * @endpoint get /api/inse-service/authors/{author_id}/patents - * @param authorId - * @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 getPatentsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPatentsByAuthor.', - ); - } - - 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/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Get patents matched to an institution by assignee name. - * @endpoint get /api/inse-service/institutions/{id}/patents - * @param id - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getPatentsByInstitution( - id: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getPatentsByInstitution( - id: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByInstitution( - id: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPatentsByInstitution( - id: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (id === null || id === undefined) { - throw new Error( - 'Required parameter id was null or undefined when calling getPatentsByInstitution.', - ); - } - - 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/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 5a51e233..ef7b0c7f 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AutocompleteResponse } from '../model/autocompleteResponse'; @@ -34,929 +28,484 @@ import { KeywordsTopicsResponse } from '../model/keywordsTopicsResponse'; import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class TopicsService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns topic options for autocomplete inputs. - * @endpoint get /api/topics/autocomplete - * @param query Topic search text, for example \'machine learning\'. - * @param domainId Optional OpenAlex domain id filter. - * @param fieldId Optional OpenAlex field id filter. - * @param subfieldId Optional OpenAlex subfield id filter. - * @param limit Maximum number of autocomplete options. - * @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 autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public autocompleteTopics( - query: string, - domainId?: string, - fieldId?: string, - subfieldId?: string, - limit?: number, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling autocompleteTopics.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - domainId, - 'domainId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - fieldId, - 'fieldId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - subfieldId, - 'subfieldId', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); + /** + * Returns topic options for autocomplete inputs. + * @endpoint get /api/topics/autocomplete + * @param query Topic search text, for example \'machine learning\'. + * @param domainId Optional OpenAlex domain id filter. + * @param fieldId Optional OpenAlex field id filter. + * @param subfieldId Optional OpenAlex subfield id filter. + * @param limit Maximum number of autocomplete options. + * @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 autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public autocompleteTopics(query: string, domainId?: string, fieldId?: string, subfieldId?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling autocompleteTopics.'); + } - let localVarHeaders = this.defaultHeaders; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + domainId, 'domainId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + fieldId, 'fieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + subfieldId, 'subfieldId'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - 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'; - } - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarPath = `/api/topics/autocomplete`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - /** - * Builds the topic hierarchy cache. - * @endpoint get /api/inse-service/topics/cache - * @param pageSize Page size for each search page. - * @param saveJson Persist cache JSON to data folder. - * @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 buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public buildTopicCache( - pageSize?: number, - saveJson?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - pageSize, - 'page_size', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - saveJson, - 'save_json', - ); + 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 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/cache`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Counts topic hierarchy occurrences from cache. - * @endpoint get /api/inse-service/topics/count - * @param topic Topic names (repeat parameter). - * @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 countTopicHierarchy( - topic: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public countTopicHierarchy( - topic: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public countTopicHierarchy( - topic: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (topic === null || topic === undefined) { - throw new Error( - 'Required parameter topic was null or undefined when calling countTopicHierarchy.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topic) { - topic.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic', + let localVarPath = `/api/topics/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - let localVarHeaders = this.defaultHeaders; + /** + * Builds the topic hierarchy cache. + * @endpoint get /api/inse-service/topics/cache + * @param pageSize Page size for each search page. + * @param saveJson Persist cache JSON to data folder. + * @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + pageSize, 'page_size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + saveJson, 'save_json'); + + 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/cache`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Counts topic hierarchy occurrences from cache. + * @endpoint get /api/inse-service/topics/count + * @param topic Topic names (repeat parameter). + * @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 countTopicHierarchy(topic: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public countTopicHierarchy(topic: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public countTopicHierarchy(topic: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (topic === null || topic === undefined) { + throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (topic) { + topic.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic'); + }) + } - 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 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/count`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/count`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Returns 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; + public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - /** - * 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; - public getTopicHierarchy( - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicHierarchy( - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + 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('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Returns a list of OpenAlex topics. + * @endpoint get /api/topics + * @param search Full-text search, for example \'machine learning\'. + * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'domain.id\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public listTopics(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + search, 'search'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sort, 'sort'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + groupBy, 'group_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + cursor, 'cursor'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sample, 'sample'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + select, 'select'); - 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 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/topics`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/inse-service/topics/hierarchy`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } + /** + * Semantic / vector search for topics using a keyword/sentence. + * @endpoint get /api/topics/vector-search + * @param query Word or sentence to search by similarity. + * @param limit Maximum number of topics to return. + * @param searchType Search approach: \'hybrid\' or \'semantic\'. + * @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 vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (query === null || query === undefined) { + throw new Error('Required parameter query was null or undefined when calling vectorSearchTopics.'); + } - /** - * Returns a list of OpenAlex topics. - * @endpoint get /api/topics - * @param search Full-text search, for example \'machine learning\'. - * @param filter OpenAlex filter, for example \'domain.id:1,works_count:>1000\'. - * @param sort Sort field, for example \'works_count:desc\'. - * @param groupBy OpenAlex group_by field, for example \'domain.id\'. - * @param perPage Results per page. - * @param page Page number. Use cursor for deep pagination. - * @param cursor Cursor pagination token. Use \'*\' to start. - * @param sample Random sample size. Cannot be combined with sort or page. - * @param select Comma-separated fields to return. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public listTopics( - search?: string, - filter?: string, - sort?: string, - groupBy?: string, - perPage?: number, - page?: number, - cursor?: string, - sample?: number, - select?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - search, - 'search', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - filter, - 'filter', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sort, - 'sort', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - groupBy, - 'group_by', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - perPage, - 'per_page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - cursor, - 'cursor', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - sample, - 'sample', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - select, - 'select', - ); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + query, 'query'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + limit, 'limit'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + searchType, 'searchType'); - let localVarHeaders = this.defaultHeaders; + let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); + 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/topics/vector-search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + /** + * Batch semantic / vector search for multiple keywords. + * @endpoint post /api/topics/vector-search/batch + * @param keywordsTopicsRequest + * @param searchType Search approach: \'hybrid\' or \'semantic\'. + * @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 vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (keywordsTopicsRequest === null || keywordsTopicsRequest === undefined) { + throw new Error('Required parameter keywordsTopicsRequest was null or undefined when calling vectorSearchTopicsBatch.'); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + searchType, 'searchType'); - 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 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; + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + 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/topics/vector-search/batch`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('post', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: keywordsTopicsRequest, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); } - let localVarPath = `/api/topics`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Semantic / vector search for topics using a keyword/sentence. - * @endpoint get /api/topics/vector-search - * @param query Word or sentence to search by similarity. - * @param limit Maximum number of topics to return. - * @param searchType Search approach: \'hybrid\' or \'semantic\'. - * @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 vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopics( - query: string, - limit?: number, - searchType?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (query === null || query === undefined) { - throw new Error( - 'Required parameter query was null or undefined when calling vectorSearchTopics.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - limit, - 'limit', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'searchType', - ); - - 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/topics/vector-search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Batch semantic / vector search for multiple keywords. - * @endpoint post /api/topics/vector-search/batch - * @param keywordsTopicsRequest - * @param searchType Search approach: \'hybrid\' or \'semantic\'. - * @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 vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public vectorSearchTopicsBatch( - keywordsTopicsRequest: KeywordsTopicsRequest, - searchType?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (keywordsTopicsRequest === null || keywordsTopicsRequest === undefined) { - throw new Error( - 'Required parameter keywordsTopicsRequest was null or undefined when calling vectorSearchTopicsBatch.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - searchType, - 'searchType', - ); - - 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; - - // to determine the Content-Type header - const consumes: string[] = ['application/json']; - const httpContentTypeSelected: string | undefined = - this.configuration.selectHeaderContentType(consumes); - if (httpContentTypeSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Content-Type', - httpContentTypeSelected, - ); - } - - 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/topics/vector-search/batch`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'post', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - body: keywordsTopicsRequest, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } } diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index ca494a80..09641dde 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,18 +9,12 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { - HttpClient, - HttpHeaders, - HttpParams, - HttpResponse, - HttpEvent, - HttpParameterCodec, - HttpContext, -} from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -36,664 +30,356 @@ import { WorkPage } from '../model/workPage'; import { WorksListResponse } from '../model/worksListResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; + + @Injectable({ - providedIn: 'root', + providedIn: 'root' }) export class WorksService extends BaseService { - constructor( - protected httpClient: HttpClient, - @Optional() @Inject(BASE_PATH) basePath: string | string[], - @Optional() configuration?: Configuration, - ) { - super(basePath, configuration); - } - /** - * Returns all works for an author. - * @endpoint get /api/works/{author_id}/all - * @param authorId The author id, for example A5023888391. - * @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 getAllAuthorWorks( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAllAuthorWorks( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllAuthorWorks( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAllAuthorWorks( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getAllAuthorWorks.', - ); + constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { + super(basePath, configuration); } - let localVarHeaders = this.defaultHeaders; + /** + * Returns all works for an author. + * @endpoint get /api/works/{author_id}/all + * @param authorId The author id, for example A5023888391. + * @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 getAllAuthorWorks(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAllAuthorWorks(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllAuthorWorks(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAllAuthorWorks(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getAllAuthorWorks.'); + } - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } + let localVarHeaders = this.defaultHeaders; - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - const localVarTransferCache: boolean = options?.transferCache ?? true; + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - 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'; - } - } + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarPath = `/api/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/all`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - /** - * Returns a page of works for an author. - * @endpoint get /api/works/{author_id} - * @param authorId The author id, for example A5023888391. - * @param page The page number. - * @param size The page size. - * @param publicationYear Filter by publication year. Can be repeated. - * @param type Filter by publication type. Can be repeated. - * @param language Filter by language code. Can be repeated. - * @param institutionId Filter by OpenAlex institution id. Can be repeated. - * @param topicId Filter by OpenAlex topic id. Can be repeated. - * @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 getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getAuthorWorks( - authorId: string, - page?: number, - size?: number, - publicationYear?: Array, - type?: Array, - language?: Array, - institutionId?: Array, - topicId?: Array, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getAuthorWorks.', - ); - } + 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 localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - page, - 'page', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - size, - 'size', - ); - if (publicationYear) { - publicationYear.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'publication_year', + let localVarPath = `/api/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/all`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (type) { - type.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'type', + + /** + * Returns a page of works for an author. + * @endpoint get /api/works/{author_id} + * @param authorId The author id, for example A5023888391. + * @param page The page number. + * @param size The page size. + * @param publicationYear Filter by publication year. Can be repeated. + * @param type Filter by publication type. Can be repeated. + * @param language Filter by language code. Can be repeated. + * @param institutionId Filter by OpenAlex institution id. Can be repeated. + * @param topicId Filter by OpenAlex topic id. Can be repeated. + * @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 getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array, type?: Array, language?: Array, institutionId?: Array, topicId?: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + if (publicationYear) { + publicationYear.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_year'); + }) + } + if (type) { + type.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'type'); + }) + } + if (language) { + language.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'language'); + }) + } + if (institutionId) { + institutionId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_id'); + }) + } + if (topicId) { + topicId.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_id'); + }) + } + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (language) { - language.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'language', + + /** + * Returns work counts per primary topic for an author. + * @endpoint get /api/works/{author_id}/primary-topic-counts + * @param authorId The author id, for example A5023888391. + * @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 getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>; + public getPrimaryTopicCountsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.'); + } + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/primary-topic-counts`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (institutionId) { - institutionId.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'institution_id', + + /** + * Returns topics grouped by publication year for an author. + * @endpoint get /api/works/{author_id}/topics-by-time + * @param authorId The author id, for example A5023888391. + * @param maxTopicsPerYear The maximum number of topics per year. + * @param targetPublications Target number of publications used for the timeline. Complete years are always included. + * @param includeAll If true, all publications are used for the timeline. + * @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 getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicsByTimeByAuthor(authorId: string, maxTopicsPerYear?: number, targetPublications?: number, includeAll?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + maxTopicsPerYear, 'max_topics_per_year'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + targetPublications, 'target_publications'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + includeAll, 'include_all'); + + 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/works/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/topics-by-time`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - if (topicId) { - topicId.forEach((element) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - element, - 'topic_id', + + /** + * Returns one publication by OpenAlex ID or DOI. + * @endpoint get /api/works/detail/{identifier} + * @param identifier The OpenAlex work id (e.g., W2741809807) or DOI number of the publication. + * @param title Do we want to fallback to title search if ID and DOI dont work? + * @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 getWork(identifier: string, title?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getWork(identifier: string, title?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(identifier: string, title?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWork(identifier: string, title?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (identifier === null || identifier === undefined) { + throw new Error('Required parameter identifier was null or undefined when calling getWork.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + + 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/works/detail/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } ); - }); } - 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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns work counts per primary topic for an author. - * @endpoint get /api/works/{author_id}/primary-topic-counts - * @param authorId The author id, for example A5023888391. - * @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 getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>>; - public getPrimaryTopicCountsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getPrimaryTopicCountsByAuthor.', - ); - } - - 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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/primary-topic-counts`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request>( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns topics grouped by publication year for an author. - * @endpoint get /api/works/{author_id}/topics-by-time - * @param authorId The author id, for example A5023888391. - * @param maxTopicsPerYear The maximum number of topics per year. - * @param targetPublications Target number of publications used for the timeline. Complete years are always included. - * @param includeAll If true, all publications are used for the timeline. - * @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 getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getTopicsByTimeByAuthor( - authorId: string, - maxTopicsPerYear?: number, - targetPublications?: number, - includeAll?: boolean, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (authorId === null || authorId === undefined) { - throw new Error( - 'Required parameter authorId was null or undefined when calling getTopicsByTimeByAuthor.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - maxTopicsPerYear, - 'max_topics_per_year', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - targetPublications, - 'target_publications', - ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - includeAll, - 'include_all', - ); - - 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/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/topics-by-time`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - - /** - * Returns one publication by OpenAlex ID or DOI. - * @endpoint get /api/works/detail/{identifier} - * @param identifier The OpenAlex work id (e.g., W2741809807) or DOI number of the publication. - * @param title Do we want to fallback to title search if ID and DOI dont work? - * @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 getWork( - identifier: string, - title?: string, - observe?: 'body', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable; - public getWork( - identifier: string, - title?: string, - observe?: 'response', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getWork( - identifier: string, - title?: string, - observe?: 'events', - reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable>; - public getWork( - identifier: string, - title?: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, - ): Observable { - if (identifier === null || identifier === undefined) { - throw new Error( - 'Required parameter identifier was null or undefined when calling getWork.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - title, - 'title', - ); - - 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/works/detail/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); - } } diff --git a/webapp/src/app/api/configuration.ts b/webapp/src/app/api/configuration.ts index 17a7070e..2b8c80f7 100644 --- a/webapp/src/app/api/configuration.ts +++ b/webapp/src/app/api/configuration.ts @@ -1,219 +1,193 @@ -import { - HttpHeaders, - HttpParams, - HttpParameterCodec, -} from '@angular/common/http'; +import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; import { Param } from './param'; export interface ConfigurationParameters { - /** - * @deprecated Since 5.0. Use credentials instead - */ - apiKeys?: { [key: string]: string }; - username?: string; - password?: string; - /** - * @deprecated Since 5.0. Use credentials instead - */ - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; - /** - * Takes care of encoding query- and form-parameters. - */ - encoder?: HttpParameterCodec; - /** - * Override the default method for encoding path parameters in various - * styles. - *

- * See {@link README.md} for more details - *

- */ - encodeParam?: (param: Param) => string; - /** - * The keys are the names in the securitySchemes section of the OpenAPI - * document. They should map to the value used for authentication - * minus any standard prefixes such as 'Basic' or 'Bearer'. - */ - credentials?: { [key: string]: string | (() => string | undefined) }; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; } export class Configuration { - /** - * @deprecated Since 5.0. Use credentials instead - */ - apiKeys?: { [key: string]: string }; - username?: string; - password?: string; - /** - * @deprecated Since 5.0. Use credentials instead - */ - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; - /** - * Takes care of encoding query- and form-parameters. - */ - encoder?: HttpParameterCodec; - /** - * Encoding of various path parameter - * styles. - *

- * See {@link README.md} for more details - *

- */ - encodeParam: (param: Param) => string; - /** - * The keys are the names in the securitySchemes section of the OpenAPI - * document. They should map to the value used for authentication - * minus any standard prefixes such as 'Basic' or 'Bearer'. - */ - credentials: { [key: string]: string | (() => string | undefined) }; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

+ * See {@link README.md} for more details + *

+ */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; - constructor({ - accessToken, - apiKeys, - basePath, - credentials, - encodeParam, - encoder, - password, - username, - withCredentials, - }: ConfigurationParameters = {}) { - if (apiKeys) { - this.apiKeys = apiKeys; - } - if (username !== undefined) { - this.username = username; - } - if (password !== undefined) { - this.password = password; - } - if (accessToken !== undefined) { - this.accessToken = accessToken; - } - if (basePath !== undefined) { - this.basePath = basePath; - } - if (withCredentials !== undefined) { - this.withCredentials = withCredentials; - } - if (encoder) { - this.encoder = encoder; - } - this.encodeParam = - encodeParam ?? ((param) => this.defaultEncodeParam(param)); - this.credentials = credentials ?? {}; +constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) { + if (apiKeys) { + this.apiKeys = apiKeys; + } + if (username !== undefined) { + this.username = username; + } + if (password !== undefined) { + this.password = password; + } + if (accessToken !== undefined) { + this.accessToken = accessToken; + } + if (basePath !== undefined) { + this.basePath = basePath; + } + if (withCredentials !== undefined) { + this.withCredentials = withCredentials; + } + if (encoder) { + this.encoder = encoder; + } + this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param)); + this.credentials = credentials ?? {}; - // init default HTTPBearer credential - if (!this.credentials['HTTPBearer']) { - this.credentials['HTTPBearer'] = () => { - return typeof this.accessToken === 'function' - ? this.accessToken() - : this.accessToken; - }; - } - } - - /** - * Select the correct content-type to use for a request. - * Uses {@link Configuration#isJsonMime} to determine the correct content-type. - * If no content type is found return the first found type if the contentTypes is not empty - * @param contentTypes - the array of content types that are available for selection - * @returns the selected content-type or undefined if no selection could be made. - */ - public selectHeaderContentType(contentTypes: string[]): string | undefined { - if (contentTypes.length === 0) { - return undefined; + // init default HTTPBearer credential + if (!this.credentials['HTTPBearer']) { + this.credentials['HTTPBearer'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } } - const type = contentTypes.find((x: string) => this.isJsonMime(x)); - if (type === undefined) { - return contentTypes[0]; - } - return type; - } + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } - /** - * Select the correct accept content-type to use for a request. - * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. - * If no content type is found return the first found type if the contentTypes is not empty - * @param accepts - the array of content types that are available for selection. - * @returns the selected content-type or undefined if no selection could be made. - */ - public selectHeaderAccept(accepts: string[]): string | undefined { - if (accepts.length === 0) { - return undefined; + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; } - const type = accepts.find((x: string) => this.isJsonMime(x)); - if (type === undefined) { - return accepts[0]; + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; } - return type; - } - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * @param mime - MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public isJsonMime(mime: string): boolean { - const jsonMime: RegExp = new RegExp( - '^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', - 'i', - ); - return ( - mime !== null && - (jsonMime.test(mime) || - mime.toLowerCase() === 'application/json-patch+json') - ); - } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } - public lookupCredential(key: string): string | undefined { - const value = this.credentials[key]; - return typeof value === 'function' ? value() : value; - } + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } - public addCredentialToHeaders( - credentialKey: string, - headerName: string, - headers: HttpHeaders, - prefix?: string, - ): HttpHeaders { - const value = this.lookupCredential(credentialKey); - return value ? headers.set(headerName, (prefix ?? '') + value) : headers; - } + public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders { + const value = this.lookupCredential(credentialKey); + return value + ? headers.set(headerName, (prefix ?? '') + value) + : headers; + } - public addCredentialToQuery( - credentialKey: string, - paramName: string, - query: HttpParams, - ): HttpParams { - const value = this.lookupCredential(credentialKey); - return value ? query.set(paramName, value) : query; - } + public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams { + const value = this.lookupCredential(credentialKey); + return value + ? query.set(paramName, value) + : query; + } - private defaultEncodeParam(param: Param): string { - // This implementation exists as fallback for missing configuration - // and for backwards compatibility to older typescript-angular generator versions. - // It only works for the 'simple' parameter style. - // Date-handling only works for the 'date-time' format. - // All other styles and Date-formats are probably handled incorrectly. - // - // But: if that's all you need (i.e.: the most common use-case): no need for customization! + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! - const value = - param.dataFormat === 'date-time' && param.value instanceof Date - ? (param.value as Date).toISOString() - : param.value; + const value = param.dataFormat === 'date-time' && param.value instanceof Date + ? (param.value as Date).toISOString() + : param.value; - return encodeURIComponent(String(value)); - } + return encodeURIComponent(String(value)); + } } diff --git a/webapp/src/app/api/model/accessResponse.ts b/webapp/src/app/api/model/accessResponse.ts index f1610895..6a36e872 100644 --- a/webapp/src/app/api/model/accessResponse.ts +++ b/webapp/src/app/api/model/accessResponse.ts @@ -7,7 +7,6 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { RefreshToken } from './refreshToken'; import { AccessToken } from './accessToken'; @@ -16,9 +15,5 @@ export interface AccessResponse { * The access token issued upon successful authentication. */ access_token: AccessToken; - /** - * The refresh token issued alongside the access token for obtaining new access tokens. - */ - refresh_token: RefreshToken; } diff --git a/webapp/src/app/api/model/accessToken.ts b/webapp/src/app/api/model/accessToken.ts index ce3ea930..2c470009 100644 --- a/webapp/src/app/api/model/accessToken.ts +++ b/webapp/src/app/api/model/accessToken.ts @@ -12,10 +12,6 @@ import { UserRole } from './userRole'; export interface AccessToken { - /** - * The type of the token, which is always ACCESS_TOKEN for this class. - */ - token_type?: TokenType; /** * The unique identifier of the real account associated with this token. */ @@ -29,13 +25,13 @@ export interface AccessToken { */ epoch?: number; /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. + * The type of the token, which is always ACCESS_TOKEN for this class. + */ + token_type?: TokenType; + /** + * A unique fingerprint of the user, used for additional security checks. */ user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; /** * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. */ @@ -48,6 +44,10 @@ export interface AccessToken { * The unique identifier of the organization associated with this access token. */ effective_organization_id: string; + /** + * The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes. + */ + raw_token: string; } export namespace AccessToken { } diff --git a/webapp/src/app/api/model/accountProfile.ts b/webapp/src/app/api/model/accountProfile.ts index 52a9f7e6..58adefb8 100644 --- a/webapp/src/app/api/model/accountProfile.ts +++ b/webapp/src/app/api/model/accountProfile.ts @@ -26,3 +26,4 @@ export interface AccountProfile { export namespace AccountProfile { } + diff --git a/webapp/src/app/api/model/bodyRequestOtk.ts b/webapp/src/app/api/model/bodyRequestOtk.ts index 1600a002..ba1a396d 100644 --- a/webapp/src/app/api/model/bodyRequestOtk.ts +++ b/webapp/src/app/api/model/bodyRequestOtk.ts @@ -1,20 +1,22 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface BodyRequestOtk { - /** - * User\'s email address - */ - email: string; - /** - * User\'s password - */ - password: string; + +export interface BodyRequestOtk { + /** + * User\'s email address + */ + email: string; + /** + * User\'s password + */ + password: string; } + diff --git a/webapp/src/app/api/model/createOrganizationRequest.ts b/webapp/src/app/api/model/createOrganizationRequest.ts index 94aacb80..fffb5457 100644 --- a/webapp/src/app/api/model/createOrganizationRequest.ts +++ b/webapp/src/app/api/model/createOrganizationRequest.ts @@ -1,14 +1,16 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface CreateOrganizationRequest { - name: string; - other_inst_id?: string | null; + +export interface CreateOrganizationRequest { + name: string; + other_inst_id?: string | null; } + diff --git a/webapp/src/app/api/model/extractedKeywordsResponse.ts b/webapp/src/app/api/model/extractedKeywordsResponse.ts index 8fe10a5f..43731b7c 100644 --- a/webapp/src/app/api/model/extractedKeywordsResponse.ts +++ b/webapp/src/app/api/model/extractedKeywordsResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -10,17 +10,19 @@ import { ExtractedKeywordsLLM } from './extractedKeywordsLLM'; import { ExtractedKeywords } from './extractedKeywords'; -export interface ExtractedKeywordsResponse { - results_llm?: ExtractedKeywordsLLM | null; - results?: ExtractedKeywords | null; - /** - * The source of the input text, e.g., \'url\', \'text\', or \'keywords\'. - */ - source: string; - source_url?: string | null; - /** - * The actual content from which keywords were extracted. - */ - source_content: string; - duration?: number | null; + +export interface ExtractedKeywordsResponse { + results_llm?: ExtractedKeywordsLLM | null; + results?: ExtractedKeywords | null; + /** + * The source of the input text, e.g., \'url\', \'text\', or \'keywords\'. + */ + source: string; + source_url?: string | null; + /** + * The actual content from which keywords were extracted. + */ + source_content: string; + duration?: number | null; } + diff --git a/webapp/src/app/api/model/idToken.ts b/webapp/src/app/api/model/idTokenMetadata.ts similarity index 72% rename from webapp/src/app/api/model/idToken.ts rename to webapp/src/app/api/model/idTokenMetadata.ts index e6a88cd3..5398083d 100644 --- a/webapp/src/app/api/model/idToken.ts +++ b/webapp/src/app/api/model/idTokenMetadata.ts @@ -10,11 +10,7 @@ import { TokenType } from './tokenType'; -export interface IdToken { - /** - * The type of the token, which is always ID_TOKEN for this class. - */ - token_type?: TokenType; +export interface IdTokenMetadata { /** * The unique identifier of the real account associated with this token. */ @@ -28,15 +24,11 @@ export interface IdToken { */ epoch?: number; /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. + * The type of the token, which is always ID_TOKEN for this class. */ - user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; + token_type?: TokenType; } -export namespace IdToken { +export namespace IdTokenMetadata { } diff --git a/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts index 47235351..c67acc71 100644 --- a/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseAccountManagementModelOrganizationProfile.ts @@ -1,15 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface InseAccountManagementModelOrganizationProfile { - id: string; - name: string; - openalex_institution_id?: string | null; + +export interface InseAccountManagementModelOrganizationProfile { + id: string; + name: string; + openalex_institution_id?: string | null; } + diff --git a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts index 8f9f0e6b..404df0f9 100644 --- a/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts +++ b/webapp/src/app/api/model/inseOrganizationManagementModelOrganizationProfile.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface InseOrganizationManagementModelOrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; + +export interface InseOrganizationManagementModelOrganizationProfile { + id: string; + name: string; + other_inst_id?: string | null; + deleted: boolean; + member_count: number; } + diff --git a/webapp/src/app/api/model/keywordTopicMatch.ts b/webapp/src/app/api/model/keywordTopicMatch.ts index ee4c8326..f9c2ab49 100644 --- a/webapp/src/app/api/model/keywordTopicMatch.ts +++ b/webapp/src/app/api/model/keywordTopicMatch.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,7 +9,9 @@ */ import { Topic } from './topic'; -export interface KeywordTopicMatch { - keyword: string; - topic?: Topic | null; + +export interface KeywordTopicMatch { + keyword: string; + topic?: Topic | null; } + diff --git a/webapp/src/app/api/model/keywordsTopicsRequest.ts b/webapp/src/app/api/model/keywordsTopicsRequest.ts index 883ed079..8810bf5f 100644 --- a/webapp/src/app/api/model/keywordsTopicsRequest.ts +++ b/webapp/src/app/api/model/keywordsTopicsRequest.ts @@ -1,16 +1,18 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface KeywordsTopicsRequest { - /** - * List of keywords/sentences to query by similarity. - */ - keywords: Array; + +export interface KeywordsTopicsRequest { + /** + * List of keywords/sentences to query by similarity. + */ + keywords: Array; } + diff --git a/webapp/src/app/api/model/keywordsTopicsResponse.ts b/webapp/src/app/api/model/keywordsTopicsResponse.ts index 78a2f9d2..4aee622f 100644 --- a/webapp/src/app/api/model/keywordsTopicsResponse.ts +++ b/webapp/src/app/api/model/keywordsTopicsResponse.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,9 +9,11 @@ */ import { KeywordTopicMatch } from './keywordTopicMatch'; -export interface KeywordsTopicsResponse { - /** - * Top matching topics for each keyword in the requested list. - */ - results: Array; + +export interface KeywordsTopicsResponse { + /** + * Top matching topics for each keyword in the requested list. + */ + results: Array; } + diff --git a/webapp/src/app/api/model/loginResponse.ts b/webapp/src/app/api/model/loginResponse.ts index 216d0fb0..c91eb493 100644 --- a/webapp/src/app/api/model/loginResponse.ts +++ b/webapp/src/app/api/model/loginResponse.ts @@ -1,17 +1,19 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -import { IdToken } from './idToken'; +import { IdTokenMetadata } from './idTokenMetadata'; -export interface LoginResponse { - /** - * The ID token issued upon successful login. - */ - id_token: IdToken; + +export interface LoginResponse { + /** + * The ID token issued upon successful login. + */ + id_token: IdTokenMetadata; } + diff --git a/webapp/src/app/api/model/matchedAuthor.ts b/webapp/src/app/api/model/matchedAuthor.ts index 311e2184..6194df94 100644 --- a/webapp/src/app/api/model/matchedAuthor.ts +++ b/webapp/src/app/api/model/matchedAuthor.ts @@ -1,14 +1,16 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface MatchedAuthor { - openalex_author_id: string; - author_name: string; + +export interface MatchedAuthor { + openalex_author_id: string; + author_name: string; } + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 7868aabe..3bf537d5 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -89,7 +89,7 @@ export * from './hEUReportSummary'; export * from './hEUTopic'; export * from './hEUWebLink'; export * from './hTTPValidationError'; -export * from './idToken'; +export * from './idTokenMetadata'; export * from './inseAccountManagementModelOrganizationProfile'; export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './institution'; @@ -136,7 +136,6 @@ export * from './publicationDetailByFunder'; export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './rankingResponse'; -export * from './refreshToken'; export * from './score'; export * from './sortDirection'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/refreshToken.ts b/webapp/src/app/api/model/refreshToken.ts deleted file mode 100644 index 89506b70..00000000 --- a/webapp/src/app/api/model/refreshToken.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { TokenType } from './tokenType'; -import { UserRole } from './userRole'; - - -export interface RefreshToken { - /** - * The type of the token, which is always REFRESH_TOKEN for this class. - */ - token_type?: TokenType; - /** - * The unique identifier of the real account associated with this token. - */ - real_account_id: string; - /** - * The timestamp indicating when the token will expire. - */ - expires_at: string; - /** - * The epoch value for the token. Used for versioning of tokens. - */ - epoch?: number; - /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. - */ - user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; - /** - * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. - */ - effective_account_id: string; - /** - * The specific role this access token grants within its organization. - */ - effective_role?: UserRole; - /** - * The unique identifier of the organization associated with this access token. - */ - effective_organization_id: string; -} -export namespace RefreshToken { -} - - diff --git a/webapp/src/app/api/model/tokenType.ts b/webapp/src/app/api/model/tokenType.ts index 06231c11..a0efdc46 100644 --- a/webapp/src/app/api/model/tokenType.ts +++ b/webapp/src/app/api/model/tokenType.ts @@ -10,9 +10,9 @@ export const TokenType = { - Id: 'ID', - Refresh: 'REFRESH', - Access: 'ACCESS' + IdToken: 'ID_TOKEN', + RefreshToken: 'REFRESH_TOKEN', + AccessToken: 'ACCESS_TOKEN' } as const; export type TokenType = typeof TokenType[keyof typeof TokenType]; diff --git a/webapp/src/app/api/model/updateAccountRequest.ts b/webapp/src/app/api/model/updateAccountRequest.ts index 1d4389f7..efc4cea6 100644 --- a/webapp/src/app/api/model/updateAccountRequest.ts +++ b/webapp/src/app/api/model/updateAccountRequest.ts @@ -23,3 +23,4 @@ export interface UpdateAccountRequest { export namespace UpdateAccountRequest { } + diff --git a/webapp/src/app/api/model/updateOrganizationRequest.ts b/webapp/src/app/api/model/updateOrganizationRequest.ts index a56b51e7..e12063b6 100644 --- a/webapp/src/app/api/model/updateOrganizationRequest.ts +++ b/webapp/src/app/api/model/updateOrganizationRequest.ts @@ -1,15 +1,17 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface UpdateOrganizationRequest { - name?: string | null; - other_inst_id?: string | null; - deleted?: boolean | null; + +export interface UpdateOrganizationRequest { + name?: string | null; + other_inst_id?: string | null; + deleted?: boolean | null; } + diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index db6739c5..a8bd7fea 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -91,7 +91,7 @@ export class AppLoginComponent implements OnDestroy { this.stopCountdown(); } - async requestOtk() { + requestOtk() { if (this.credentialsForm.invalid || this.isSubmitting) { this.credentialsForm.markAllAsTouched(); return; @@ -103,36 +103,35 @@ export class AppLoginComponent implements OnDestroy { const email = this.credentialsForm.controls.email.value ?? ''; const password = this.credentialsForm.controls.password.value ?? ''; - try { - const otkResponse = await this.credentialService.requestOtk( - email, - password, - ); - const accountId = otkResponse.account_id; - this.accountId = accountId; - this.currentStep = 'otk'; - this.otkForm.reset(); - this.startCountdown(); - this.snackBar.open( - 'OTK-Code wurde an die E-Mail-Adresse gesendet.', - 'OK', - { - duration: 4000, - }, - ); - } catch (error: unknown) { - this.credentialService.clearLocalAuthState(); - this.snackBar.open( - this.getLoginErrorMessage(error as HttpErrorResponse), - 'OK', - { - duration: 5000, - }, - ); - } finally { - this.isSubmitting = false; - this.credentialsForm.enable(); - } + this.credentialService.requestOtk(email, password).subscribe({ + next: (otkResponse) => { + const accountId = otkResponse.account_id; + this.accountId = accountId; + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open( + 'OTK-Code wurde an die E-Mail-Adresse gesendet.', + 'OK', + { + duration: 4000, + }, + ); + }, + error: (error: unknown) => { + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, + }, + ); + }, + complete: () => { + this.isSubmitting = false; + this.credentialsForm.enable(); + }, + }); } resendCode() { @@ -143,7 +142,7 @@ export class AppLoginComponent implements OnDestroy { this.requestOtk(); } - async login() { + login() { if (this.otkForm.invalid || this.isSubmitting) { this.otkForm.markAllAsTouched(); return; @@ -170,23 +169,30 @@ export class AppLoginComponent implements OnDestroy { const code = this.otkForm.controls.code.value ?? ''; - try { - await this.credentialService.loginWithOtk(this.accountId, code); - this.stopCountdown(); - this.router.navigate(['/dashboard']); - } catch (error: unknown) { - this.credentialService.clearLocalAuthState(); - this.snackBar.open( - this.getLoginErrorMessage(error as HttpErrorResponse), - 'OK', - { - duration: 5000, - }, - ); - } finally { - this.isSubmitting = false; - this.otkForm.enable(); - } + this.credentialService.loginWithOtk(this.accountId, code).subscribe({ + next: () => { + this.credentialService.reauthenticateViaIdToken().subscribe({ + next: () => { + this.checkEnter(); + this.stopCountdown(); + this.router.navigate(['/dashboard']); + }, + }); + }, + error: (error: unknown) => { + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { + duration: 5000, + }, + ); + }, + complete: () => { + this.isSubmitting = false; + this.otkForm.enable(); + }, + }); } editCredentials() { diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 194799a2..08113260 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -5,69 +5,100 @@ import { } from '@angular/common/http'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; -import { catchError, throwError } from 'rxjs'; -import { CredentialService } from '../services/credential.service'; +import { catchError, switchMap, throwError } from 'rxjs'; +import { + CredentialService, + clearStoredAuthState, + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE, +} from '../services/credential.service'; -const UNAUTHENTICATED_POST_ENDPOINTS = [ - '/api/auth/v2/request-otk', - '/api/auth/v2/login', - '/institutions/autocomplete', -]; - -const isUnauthenticatedPostRequest = (req: any) => { - const url = req.url.split('?')[0]; - return ( - req.method === 'POST' && - UNAUTHENTICATED_POST_ENDPOINTS.some((endpoint) => url.endsWith(endpoint)) - ); -}; - -export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { - const url = req.url.split('?')[0]; - - if (isUnauthenticatedPostRequest(req)) { - return next(req); - } - - const credentialService = inject(CredentialService); - const router = inject(Router); - - if (!credentialService.isActiveIdentityToken()) { - void router.navigate(['/login']); - return throwError(() => new Error('No valid identity token')); - } - const idToken = credentialService.identityToken(); - let bearerToken: string; - if (url.endsWith('/api/auth/v2/access')) { - bearerToken = idToken?.raw_token ?? ''; - } else { - if (!credentialService.isActiveAccessToken()) { - credentialService.refreshAccessToken(idToken!); - } - const accessToken = credentialService.accessToken(); - if (!accessToken) { - void router.navigate(['/login']); - return throwError(() => new Error('No valid access token')); - } - return next(attachToken(req, accessToken.raw_token)); - } - const authorizedRequest = req.clone({ - headers: req.headers.set('Authorization', 'Bearer ' + bearerToken), - }); - - return next(authorizedRequest).pipe( - catchError((error: HttpErrorResponse) => { - console.error('Authentication error:', error); - return throwError(() => error); - }), - ); -}; - -const attachToken = ( - req: HttpRequest, +const attachBearer = ( + req: HttpRequest, token: string, -): HttpRequest => { +): HttpRequest => { + if (!token) { + return req; + } return req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token), }); }; + +const handleAccessTokenError = ( + error: unknown, + req: HttpRequest, + next: Parameters[1], + credentialService: CredentialService, + router: Router, +) => { + if (!(error instanceof HttpErrorResponse) || error.status !== 401) { + return throwError(() => error); + } + + if (!credentialService.getRawAccessToken()) { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError(() => error); + } + + return credentialService.refreshAccessToken().pipe( + switchMap((accessToken) => next(attachBearer(req, accessToken.raw_token))), + catchError((refreshError) => { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError(() => refreshError); + }), + ); +}; + +export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { + const router = inject(Router); + + const requiredType = req.context.get(REQUIRED_TOKEN_TYPE); + + if (requiredType === TOKEN_TYPE.NONE) { + return next(req); + } + + if (requiredType === TOKEN_TYPE.ID_TOKEN_COOKIE) { + return next(req.clone({ withCredentials: true })).pipe( + catchError((err) => { + if (err instanceof HttpErrorResponse && err.status === 401) { + clearStoredAuthState(); + router.navigate(['/login'], { replaceUrl: true }); + } + return throwError(() => err); + }), + ); + } + + if (requiredType === TOKEN_TYPE.REFRESH_TOKEN_COOKIE) { + return next(req.clone({ withCredentials: true })); + } + + const credentialService = inject(CredentialService); + + const rawAccessToken = credentialService.getRawAccessToken(); + + if (rawAccessToken && credentialService.accessTokenIsExpired()) { + return credentialService.refreshAccessToken().pipe( + switchMap((accessToken) => + next(attachBearer(req, accessToken.raw_token)), + ), + catchError(() => { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError( + () => new Error('Sitzung abgelaufen. Bitte erneut anmelden.'), + ); + }), + ); + } + + return next(rawAccessToken ? attachBearer(req, rawAccessToken) : req).pipe( + catchError((err) => + handleAccessTokenError(err, req, next, credentialService, router), + ), + ); +}; diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index be87cb65..e70311a2 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,17 +1,55 @@ import { Injectable, computed, effect, inject, signal } from '@angular/core'; import { toObservable, toSignal } from '@angular/core/rxjs-interop'; -import { firstValueFrom, Observable, of, switchMap, throwError } from 'rxjs'; +import { + catchError, + finalize, + firstValueFrom, + map, + Observable, + of, + shareReplay, + switchMap, + tap, + throwError, +} from 'rxjs'; import { AccessResponse, - AccessToken, AuthService, - IdToken, AccountProfile, - RefreshToken, OtkResponse, + IdTokenMetadata, + AccessToken, + LoginResponse, } from '../../api'; import { Router } from '@angular/router'; +import { HttpContext, HttpContextToken } from '@angular/common/http'; + +export const TOKEN_TYPE = { + ACCESS_TOKEN: 'ACCESS_TOKEN', + ID_TOKEN_COOKIE: 'ID_TOKEN_COOKIE', + REFRESH_TOKEN_COOKIE: 'REFRESH_TOKEN_COOKIE', + NONE: 'NONE', +} as const; + +export type TokenContextType = (typeof TOKEN_TYPE)[keyof typeof TOKEN_TYPE]; + +export const REQUIRED_TOKEN_TYPE = new HttpContextToken( + () => TOKEN_TYPE.ACCESS_TOKEN, +); + +const STORAGE_KEY = 'auth_state'; + +export const clearStoredAuthState = (): void => { + localStorage.removeItem(STORAGE_KEY); +}; + +export interface StoredAuthState { + idTokenMetadata: IdTokenMetadata | null; + accessToken: AccessToken | null; +} + +const EXPIRY_SKEW_MS = 10 * 1000; // 10 seconds @Injectable({ providedIn: 'root', @@ -19,10 +57,6 @@ import { Router } from '@angular/router'; export class CredentialService { private readonly authService = inject(AuthService); - private static readonly KEY_IDENTITY_TOKEN = 'identity_token'; - private static readonly KEY_REFRESH_TOKEN = 'refresh_token'; - private static readonly KEY_ACCESS_TOKEN = 'access_token'; - public readonly isValidating = signal(false); public readonly isAuthenticated = computed( () => this.accessToken() !== undefined, @@ -59,18 +93,8 @@ export class CredentialService { () => this.realAccountId() !== this.effectiveAccountId(), ); - public readonly identityToken = signal(undefined); - public readonly refreshToken = signal(undefined); public readonly accessToken = signal(undefined); - public readonly isActiveIdentityToken = computed(() => { - const idToken = this.identityToken(); - return ( - idToken !== undefined && - new Date(idToken.expires_at).getTime() >= Date.now() - ); - }); - public readonly isActiveAccessToken = computed(() => { const accessToken = this.accessToken(); return ( @@ -80,9 +104,9 @@ export class CredentialService { }); public readonly accountProfile = toSignal( - toObservable(this.isAuthenticated).pipe( - switchMap((isAuthenticated) => - isAuthenticated + toObservable(this.accessToken).pipe( + switchMap((accessToken) => + accessToken ? this.authService.getCurrentAccount() : of(undefined), ), @@ -90,216 +114,262 @@ export class CredentialService { { initialValue: undefined }, ); + private refreshInFlight$: Observable | null = null; + private request = 0; - loadTokensFromStorage(): void { - const idTokenData = localStorage.getItem( - CredentialService.KEY_IDENTITY_TOKEN, - ); - const refreshTokenData = localStorage.getItem( - CredentialService.KEY_REFRESH_TOKEN, - ); - const accessTokenData = localStorage.getItem( - CredentialService.KEY_ACCESS_TOKEN, - ); - - if (idTokenData) { - this.identityToken.set(JSON.parse(idTokenData) as IdToken); - } - if (refreshTokenData) { - this.refreshToken.set(JSON.parse(refreshTokenData) as RefreshToken); - } - if (accessTokenData) { - this.accessToken.set(JSON.parse(accessTokenData) as AccessToken); - } - } - - storeIdentityToken(idToken: IdToken): void { - this.identityToken.set(idToken); - localStorage.setItem( - CredentialService.KEY_IDENTITY_TOKEN, - JSON.stringify(idToken), - ); - } - - storeRefreshToken(refreshToken: RefreshToken): void { - this.refreshToken.set(refreshToken); - localStorage.setItem( - CredentialService.KEY_REFRESH_TOKEN, - JSON.stringify(refreshToken), - ); - } - - storeAccessToken(accessToken: AccessToken): void { - this.accessToken.set(accessToken); - localStorage.setItem( - CredentialService.KEY_ACCESS_TOKEN, - JSON.stringify(accessToken), - ); - } - - clearTokensFromStorage(): void { - localStorage.removeItem(CredentialService.KEY_IDENTITY_TOKEN); - localStorage.removeItem(CredentialService.KEY_REFRESH_TOKEN); - localStorage.removeItem(CredentialService.KEY_ACCESS_TOKEN); - } - constructor(private readonly router: Router) { - this.loadTokensFromStorage(); + this.restoreAuthState(); + effect(() => { - console.log('IdToken', this.identityToken()); - console.log('RefreshToken', this.refreshToken()); - console.log('AccessToken', this.accessToken()); + console.log('Access token changed:', this.accessToken()); }); - const id = this.identityToken(); - if (id && new Date(id.expires_at).getTime() >= Date.now()) { - this.isValidating.set(true); - setTimeout(() => this.refreshAccessToken(id), 0); + + const storedAccessToken = this.getStoredAccessToken(); + if (storedAccessToken && this.isExpired(storedAccessToken)) { + this.refreshAccessToken().subscribe({ + error: (err) => { + console.error('Error refreshing access token on init:', err); + this.logout(); + this.router.navigate(['/login'], { replaceUrl: true }); + }, + }); } } - public async requestOtk( - email: string, - password: string, - ): Promise { - this.isValidating.set(true); - this.identityToken.set(undefined); - this.accessToken.set(undefined); - - const otkResponse: OtkResponse = await firstValueFrom( - this.authService.requestOtk({ - email: email.trim().toLowerCase(), - password, - }), - ); - - this.isValidating.set(false); - return otkResponse; + private restoreAuthState(): void { + this.accessToken.set(this.getStoredAccessToken() ?? undefined); } - public async loginWithOtk( + private readAuthState(): StoredAuthState { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) { + return { idTokenMetadata: null, accessToken: null }; + } + try { + return JSON.parse(raw) as StoredAuthState; + } catch { + return { idTokenMetadata: null, accessToken: null }; + } + } + + private writeAuthState(patch: Partial): void { + const next: StoredAuthState = { + ...this.readAuthState(), + ...patch, + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); + } + + private persistAccessToken(accessToken: AccessToken | null): void { + this.writeAuthState({ accessToken }); + this.accessToken.set(accessToken ?? undefined); + } + + private getStoredIdTokenMetadata(): IdTokenMetadata | null { + return this.readAuthState().idTokenMetadata; + } + + private getStoredAccessToken(): AccessToken | null { + return this.readAuthState().accessToken; + } + + private isExpired(token: { expires_at: string }): boolean { + return new Date(token.expires_at).getTime() < Date.now() + EXPIRY_SKEW_MS; + } + + public accessTokenIsExpired(): boolean { + const accessToken = this.getStoredAccessToken(); + return !accessToken || this.isExpired(accessToken); + } + + public logout() { + clearStoredAuthState(); + this.accessToken.set(undefined); + this.refreshInFlight$ = null; + } + + public requestOtk(email: string, password: string): Observable { + return this.authService.requestOtk( + { + email: email.trim(), + password: password.trim(), + }, + undefined, + undefined, + { context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) }, + ); + } + + public loginWithOtk( accountId: string, emailCode: string, - ): Promise { - const request = ++this.request; - this.isValidating.set(true); + ): Observable { + return this.authService + .login( + { + account_id: accountId, + email_code: emailCode.trim(), + }, + undefined, + undefined, + { + context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE), + }, + ) + .pipe( + tap(({ id_token }) => + this.writeAuthState({ idTokenMetadata: id_token }), + ), + ); + } - const loginResponse = await firstValueFrom( - this.authService.login({ - account_id: accountId, - email_code: emailCode.trim(), + public requestAccess( + realAccountId: string, + effectiveAccountId?: string, + ): Observable { + return this.authService + .getAccessToken( + { + real_account_id: realAccountId, + effective_account_id: effectiveAccountId ?? realAccountId, + }, + undefined, + 'body', + undefined, + { + context: new HttpContext().set( + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE.ID_TOKEN_COOKIE, + ), + }, + ) + .pipe( + tap(({ access_token }) => { + this.persistAccessToken(access_token); + }), + ); + } + + public changePassword( + currentPassword: string, + newPassword: string, + ): Observable { + this.isValidating.set(true); + return this.authService + .changePassword({ + current_password: currentPassword, + new_password: newPassword, + }) + .pipe( + tap(() => this.isValidating.set(false)), + catchError((err) => { + this.isValidating.set(false); + return throwError(() => err); + }), + ); + } + + public refreshAccessToken(): Observable { + if (this.refreshInFlight$) { + return this.refreshInFlight$; + } + + this.refreshInFlight$ = this.authService + .refreshAccessToken(undefined, 'body', undefined, { + context: new HttpContext().set( + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE.REFRESH_TOKEN_COOKIE, // 'REFRESH_TOKEN_COOKIE' and NOT 'REFRESH_COOKIE', + 30 Minutes debugging this shit, changed to types + ), + }) + .pipe( + tap((accessToken) => { + this.persistAccessToken(accessToken); + }), + catchError(() => this.reauthenticateViaIdToken()), + finalize(() => { + this.refreshInFlight$ = null; + }), + shareReplay(1), + ); + + return this.refreshInFlight$; + } + + reauthenticateViaIdToken(): Observable { + const idTokenMetadata = this.getStoredIdTokenMetadata(); + + if (!idTokenMetadata || this.isExpired(idTokenMetadata)) { + this.logout(); + return throwError( + () => new Error('No valid ID token metadata available.'), + ); + } + + return this.requestAccess( + idTokenMetadata.real_account_id, + idTokenMetadata.real_account_id, + ).pipe( + map(({ access_token }) => access_token), + catchError((err) => { + console.error('Error reauthenticating via ID token:', err); + this.logout(); + return throwError(() => err); }), ); - - const idToken = loginResponse.id_token; - this.identityToken.set(idToken); - this.storeIdentityToken(idToken); - - this.isValidating.set(false); - await this.getAccessToken(idToken, request); } - public async refreshAccessToken(identityToken: IdToken) { - const request = ++this.request; - this.isValidating.set(true); - this.accessToken.set(undefined); - - await this.getAccessToken(identityToken, request).catch((err) => { - if (this.request === request) { - this.clearLocalAuthState(); - } - throw err; - }); - - this.isValidating.set(false); + public getRawAccessToken(): string | undefined { + return this.getStoredAccessToken()?.raw_token; } - public async impersonateAccount(accountId: string): Promise { - const idToken = this.identityToken(); - - if (!idToken) { - throw new Error('No identity token available.'); + public async impersonateAccount(effectiveAccountId: string): Promise { + const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id; + if (!realAccountId) { + throw new Error('No real account ID available.'); } const request = ++this.request; this.isValidating.set(true); - this.accessToken.set(undefined); - await this.getAccessToken(idToken, request, accountId).catch((err) => { - if (this.request === request) { - this.clearLocalAuthState(); + + try { + await firstValueFrom( + this.requestAccess(realAccountId, effectiveAccountId), + ); + } finally { + if (request === this.request) { + this.isValidating.set(false); } - throw err; - }); - this.isValidating.set(false); + } } public async stopImpersonating(): Promise { - const idToken = this.identityToken(); + this.isValidating.set(true); - if (!idToken) { - throw new Error('No identity token available.'); + const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id; + if (!realAccountId) { + throw new Error('No real account ID available.'); } - const request = ++this.request; - this.isValidating.set(true); - this.accessToken.set(undefined); - await this.getAccessToken(idToken, request); - this.isValidating.set(false); + try { + await firstValueFrom(this.requestAccess(realAccountId, realAccountId)); + } finally { + this.isValidating.set(false); + } } - public async logoutAccount() { - await firstValueFrom(this.authService.logout()); - this.clearLocalAuthState(); - } - - public clearLocalAuthState(): void { - this.request += 1; - this.clearTokensFromStorage(); - this.identityToken.set(undefined); - this.accessToken.set(undefined); - this.isValidating.set(false); - this.router.navigate(['/login'], { replaceUrl: true }); - } - - public async changePassword( - currentPassword: string, - newPassword: string, - ): Promise { - this.isValidating.set(true); - await firstValueFrom( - this.authService.changePassword({ - current_password: currentPassword, - new_password: newPassword, - }), - ); - this.clearLocalAuthState(); - this.isValidating.set(false); + public async logoutAccount(): Promise { + try { + await firstValueFrom(this.authService.logout()); + } catch (err) { + console.error('Error logging out on the server:', err); + } finally { + this.logout(); + await this.router.navigate(['/login'], { replaceUrl: true }); + } } public registerAccount(_data: unknown): Observable { return throwError(() => new Error('Registration is temporarily disabled.')); } - - private async getAccessToken( - idToken: IdToken, - request: number, - effectiveAccountId?: string, - ): Promise { - if (this.request !== request) { - return; - } - - const realAccountId = idToken.real_account_id; - - const result: AccessResponse = await firstValueFrom( - this.authService.getAccessToken({ - real_account_id: realAccountId, - effective_account_id: effectiveAccountId ?? realAccountId, - }), - ); - - this.accessToken.set(result.access_token); - this.refreshToken.set(result.refresh_token); - this.isValidating.set(false); - } } diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index bee7ed7c..abd2f2ec 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -105,12 +105,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy { async logout() { const isImpersonating = this.credentialService.isImpersonating(); - await this.credentialService.stopImpersonating(); - if (isImpersonating) { + await this.credentialService.stopImpersonating(); this.router.navigate(['/accounts']); } else { - this.router.navigate(['/login']); + await this.credentialService.logoutAccount(); } } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 9ce28c8d..f39ff565 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -142,9 +142,7 @@ export class AppMenuComponent { label: 'Navigation', items: this.navItems.filter( (item) => - !item.adminOnly && - !item.superAdminOnly && - !item.managerOrAdminOnly, + !item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly, ), }, { @@ -181,9 +179,7 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAccount().then(() => { - this.router.navigate(['/login']); - }); + void this.credentialService.logoutAccount(); }); } } From b2d965d60457b8e4c54849b29c7ce05a40dbdd4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 5 Jul 2026 16:15:41 +0200 Subject: [PATCH 32/41] fix(frontend): added label to some query param selectors --- .../institutions/institutions.component.html | 6 ++++-- .../institutions/institutions.component.scss | 2 +- .../src/app/modules/patents/patents.component.html | 13 +++++-------- webapp/src/app/modules/patents/patents.component.ts | 11 +++++++++++ .../app/modules/projects/projects.component.html | 6 ++++-- 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index 0ec24397..5edb4c3c 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -12,11 +12,13 @@
+ [queryParamKey]="'sort_by'" + label="Sortieren nach" /> + [queryParamKey]="'sorting_order'" + label="Sortierreihenfolge" />
diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 7303fdd7..8edbecef 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -25,7 +25,7 @@ .cards { display: grid; gap: 1.5rem; - grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(550px, 1fr)); padding: 0 1rem; } diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 14a37666..60086f40 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -26,14 +26,11 @@ USPTO -
- -
+ diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index adfd23e2..0eb946dc 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -15,6 +15,10 @@ import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; import { PatentsService } from '../../api/api/patents.service'; import { PatentEntry } from '../../api/model/patentEntry'; import { IpcClassification } from '../../api'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; @@ -44,6 +48,7 @@ const DESCRIPTION_PREVIEW_LENGTH = 140; MatProgressSpinnerModule, MatChipsModule, MatDividerModule, + QueryParamSelectorComponent, ], templateUrl: './patents.component.html', styleUrl: './patents.component.scss', @@ -71,6 +76,12 @@ export class PatentsComponent implements OnInit { private searchSubject = new Subject(); + sortingDirectionOptions: SelectorOption[] = [ + { value: '', display_name: '' }, + { value: 'asc', display_name: 'Aufsteigend' }, + { value: 'desc', display_name: 'Absteigend' }, + ]; + constructor() { this.searchSubject .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed()) diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 706f34fb..b2bcbddf 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -28,11 +28,13 @@
+ queryParamKey="sort_by" + label="Sortieren nach" /> + queryParamKey="sorting_order" + label="Sortierreihenfolge" />
From 04eb0f0185f272f0d594ca4162cb2706e8b28727 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 18:01:10 +0200 Subject: [PATCH 33/41] fixed bug with no url content --- service/src/main/inse/keywords/logic.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py index 81ba9f57..e329fb56 100644 --- a/service/src/main/inse/keywords/logic.py +++ b/service/src/main/inse/keywords/logic.py @@ -140,7 +140,11 @@ async def extract_keywords_stream_enriched( if mode == "url": await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump()) text = await _get_text_content(query) - await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump()) + if text: + await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump()) + else: + await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump()) + raise RuntimeError(f"Failed to fetch content from {query}") system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT else: text = query From 0c3db967b04530108507d85527e5b5c7ad65309e Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 18:01:54 +0200 Subject: [PATCH 34/41] added handling autocomplete topics ( no extra backend call anymore) --- .../topic-autocomplete.component.html | 4 +- .../topic-autocomplete.component.ts | 59 +++++++++++++------ 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html index d23c2dc0..5be3be18 100644 --- a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html @@ -45,7 +45,9 @@ } @for (topic of topics(); track topic) { - {{ topic }} + {{ + topic.display_name + }} } @if ( diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts index 6b14edd7..9dbb3796 100644 --- a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts @@ -19,6 +19,7 @@ import { of, switchMap, } from 'rxjs'; +import { Topic } from '../../../api'; @Component({ selector: 'app-topic-autocomplete', @@ -42,10 +43,10 @@ export class TopicAutocompleteComponent { readonly minCharacters = input(2); readonly limit = input(12); - readonly topicSelected = output(); + readonly topicSelected = output(); readonly searchControl = new FormControl('', { nonNullable: true }); - readonly topics = signal([]); + readonly topics = signal([]); readonly loading = signal(false); constructor( @@ -60,12 +61,12 @@ export class TopicAutocompleteComponent { const normalizedQuery = query.trim(); if (normalizedQuery.length < this.minCharacters()) { this.loading.set(false); - return of([] as string[]); + return of([]); } this.loading.set(true); return this.topicsService - .autocompleteTopics( + .listTopics( normalizedQuery, undefined, undefined, @@ -73,21 +74,19 @@ export class TopicAutocompleteComponent { this.limit(), ) .pipe( - map((response) => - Array.from( - new Set( - (response.results ?? []) - .map((topic) => topic.display_name?.trim() ?? '') - .filter((topic) => !!topic), - ), - ), - ), + map(({ results }) => { + const seen = new Map(); + for (const topic of results ?? []) { + if (topic?.id != null) seen.set(String(topic.id), topic); + } + return Array.from(seen.values()); + }), catchError((error) => { console.error( 'Error fetching topic autocomplete options:', error, ); - return of([] as string[]); + return of([] as Topic[]); }), finalize(() => this.loading.set(false)), ); @@ -101,19 +100,45 @@ export class TopicAutocompleteComponent { selectTopic(topic: string): void { this.searchControl.setValue('', { emitEvent: false }); + const selectedTopic = this.getTopicByDisplayName(topic); this.topics.set([]); - this.topicSelected.emit(topic); + if (selectedTopic) { + this.topicSelected.emit(selectedTopic); + } else { + const newTopic: Topic = { + display_name: topic, + id: null, + }; + this.topicSelected.emit(newTopic); + } } onKeydownTab(event: KeyboardEvent): void { event.preventDefault(); - this.searchControl.setValue(this.topics()[0], { emitEvent: false }); + const first = this.topics()[0]; + if (!first) return; + this.searchControl.setValue(first.display_name ?? '', { emitEvent: false }); + } + getTopicByDisplayName(displayName: string): Topic | undefined { + const normalized = displayName.trim().toLowerCase(); + return this.topics().find( + (topic) => topic.display_name?.trim().toLowerCase() === normalized, + ); } submitCurrentValue(): void { const topic = this.searchControl.value.trim(); if (!topic) return; this.searchControl.setValue('', { emitEvent: false }); this.topics.set([]); - this.topicSelected.emit(topic); + const selectedTopic = this.getTopicByDisplayName(topic); + if (selectedTopic) { + this.topicSelected.emit(selectedTopic); + } else { + const newTopic: Topic = { + display_name: topic, + id: null, + }; + this.topicSelected.emit(newTopic); + } } clear(): void { From 1eaf8f8c8ffe4df6a7d14faf2ff6aea41cf1c1f8 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 18:09:59 +0200 Subject: [PATCH 35/41] responsivness adjusted --- .../keywords-search.component.html | 381 ++++++++------- .../keywords-search.component.scss | 434 ++++++++---------- .../keywords-search.component.ts | 119 +++-- 3 files changed, 479 insertions(+), 455 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 5f4f27b9..e1de98d3 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -71,27 +71,29 @@ (expandedChange)="onSubfieldLegendExpandedChange($event)"> } - @if (extractedKeywordsExist()) { -
+ + +
+ @if (keywordsExist()) {
-
- @if (areAllExtractedSelected()) { +
+ @if (areAllSelected()) { } @else { }
@@ -126,170 +128,216 @@
-
- -
+ } @else { + +
+ } + +
+
+
+
+ + + + @if (keywords.length > 0) { +
+ @for (keyword of keywords; track keyword.llm_keyword.keyword) { + + + } +
+ } @else { +

{{ emptyText }}

} - - -
- -
-
Breite Keywords
-
Coarse Keywords
-
- Fine Keywords -
-
Eigene Keywords
+ + + +
+ @if (manualKeywords().length > 0) { + @for ( + keyword of manualKeywords(); + track keyword.llm_keyword.keyword + ) { +
+ + + +
+ } + } @else if (loadingNewKeyword()) { +
+ + +
+ } @else { +

Nichts hinzugefügt

+ }
+
- -
-
- @if (broadKeywords().length > 0) { -
- - @for ( - keyword of broadKeywords(); - track keyword.llm_keyword.keyword - ) { - - - } -
- } @else { -

Nichts extrahiert

- } + + @if (!isMobile()) { +
+
+
Breite Keywords
+
Coarse Keywords
+
+ Fine Keywords +
+
Eigene Keywords
-
- @if (coarseKeywords().length > 0) { -
- @for ( - keyword of coarseKeywords(); - track keyword.llm_keyword.keyword - ) { - - - } -
- } @else { -

Nichts extrahiert

- } -
+
+
+ +
-
- @if (fineKeywords().length > 0) { -
- @for ( - keyword of fineKeywords(); - track keyword.llm_keyword.keyword - ) { - - - } -
- } @else { -

Nichts extrahiert

- } -
-
-
- @if (manualKeywords().length > 0) { - @for ( - keyword of manualKeywords(); - track keyword.llm_keyword.keyword - ) { -
- - - -
- } - } @else if (loadingNewKeyword()) { -
- - -
- } @else { -

Nichts hinzugefügt

- } +
+ +
+ +
+ +
+ +
+
-
+ } @else { + + + + + Breit + {{ broadKeywords().length }} + +
+ +
+
+ + + + Coarse + {{ coarseKeywords().length }} + +
+ +
+
+ + + + Fine + {{ fineKeywords().length }} + +
+ +
+
+ + + + Eigene + {{ manualKeywords().length }} + +
+ +
+
+
+ } @if (isExtracting()) {
@@ -300,14 +348,13 @@
{{ statusMessage() }}
- } @else if ( - !extractedKeywordsExist() && manualKeywords().length === 0 - ) { + } @else if (!keywordsExist()) {

- Keine Keywords vorhanden. Extrahiere Keywords oder füge eigene - hinzu. + Noch keine Keywords vorhanden. Extrahiere Keywords aus URL/Text + oder füge oben eigene Keywords hinzu.

} + @if (sourceContent().length > 0) { diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index d92e54be..cfa3f8b9 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -1,8 +1,21 @@ +/* ============================================================ + DESIGN TOKENS / LOCAL VARIABLES + ============================================================ */ +$phone: 599px; +$tablet: 900px; +$touch-target: 44px; + +/* ============================================================ + BASE LAYOUT — container becomes the responsive anchor + ============================================================ */ .content { + container-type: inline-size; + container-name: keyword-tool; + display: flex; flex-direction: column; - gap: 0.75rem; - padding: 1rem; + gap: clamp(0.5rem, 1.5vw, 0.75rem); + padding: clamp(0.5rem, 2vw, 1rem); } .tab-content { @@ -12,12 +25,14 @@ gap: 0.5rem; align-items: start; } + .full-width { width: 100%; } .extract-btn { white-space: nowrap; + min-height: $touch-target; } .actions { @@ -25,6 +40,9 @@ justify-content: center; } +/* ============================================================ + TOOLBAR + ============================================================ */ .keywords-toolbar { display: flex; flex-direction: column; @@ -39,9 +57,9 @@ .toolbar-controls { display: flex; align-items: center; - justify-content: space-between; + justify-content: center; gap: 0.75rem; - flex-wrap: wrap; + flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */ padding: 0.5rem 0.75rem; background: var(--sg-background-muted, #f4f5f7); } @@ -50,13 +68,35 @@ grid-template-columns: 3fr 1.3fr; border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); } + +.toolbar-controls--placeholder { + /* invisible spacer, preserves grid column width/position */ + visibility: hidden; + pointer-events: none; +} + +.manual-input-controls { + min-width: 0; +} + +@container keyword-tool (max-width: #{$tablet}) { + .toolbar-wrapper { + grid-template-columns: 1fr; + border-left: none; + } + + .toolbar-controls--placeholder { + display: none; /* no need for a spacer once stacked */ + } +} + .toolbar-group { display: flex; align-items: center; gap: 0.6rem; } -.toolbar-group--select button { +.toolbar-group button { display: flex; align-items: center; gap: 0.35rem; @@ -64,6 +104,7 @@ line-height: 30px; border-radius: 20px; padding: 0 14px; + min-height: $touch-target; mat-icon { font-size: 20px; @@ -76,22 +117,29 @@ width: 1px; align-self: stretch; background: var(--sg-divider, rgba(0, 0, 0, 0.12)); - display: none; -} - -@media (min-width: 640px) { - .toolbar-divider { - display: block; - } } mat-button-toggle-group { border-radius: 20px; overflow: hidden; + justify-content: space-around; + + ::ng-deep .mat-button-toggle-label-content { + line-height: $touch-target; + } + ::ng-deep mat-button-toggle { + width: 100%; + } } -/* Tablet / phone: stack the toolbar and go full-width */ -@media (max-width: 768px) { +/* Container-query driven toolbar collapse (tablet/phone) */ +@container keyword-tool (min-width: #{$phone + 1}) { + .toolbar-divider { + display: block; + } +} + +@container keyword-tool (max-width: #{$tablet}) { .toolbar-controls { flex-direction: column; align-items: stretch; @@ -101,35 +149,38 @@ mat-button-toggle-group { justify-content: center; } - .toolbar-group--select button { + .toolbar-group button { width: 100%; justify-content: center; } - .toolbar-group--view { - justify-content: center; + .toolbar-wrapper { + grid-template-columns: 1fr; + border-left: none; + } + + .toolbar-wrapper .spacer { + width: 100%; } } -/* Phone: icon-only buttons to save space */ -@media (max-width: 480px) { +/* Phone: icon-only toolbar buttons to save space */ +@container keyword-tool (max-width: #{$phone}) { .btn-label { display: none; } - .toolbar-group--select button { + .toolbar-group button { width: auto; - padding: 0 10px; + padding: 0; + min-width: $touch-target; + justify-content: center; } } -mat-button-toggle-group { - flex-wrap: wrap; -} - -.toggle-text { - margin-left: 0.35rem; -} +/* ============================================================ + EXTRACTION GRID / CARD + ============================================================ */ .extraction-grid { display: grid; grid-template-columns: 1fr; @@ -150,7 +201,9 @@ mat-button-toggle-group { } } -/* === Table-like keyword grid === */ +/* ============================================================ + DESKTOP TABLE-LIKE KEYWORD GRID + ============================================================ */ .keyword-table { display: flex; flex-direction: column; @@ -161,7 +214,6 @@ mat-button-toggle-group { padding-top: 0.5rem; display: grid; grid-template-columns: repeat(3, 1fr) 1.3fr; - grid-template-rows: auto; column-gap: 1rem; border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); padding-bottom: 0.5rem; @@ -173,91 +225,16 @@ mat-button-toggle-group { text-align: center; } -.extracted-header { - grid-column: 1 / span 3; - grid-row: 0; - font-size: 0.95rem; - font-weight: 600; - color: var(--sg-text-primary); - align-self: end; -} - .sub-cell { font-weight: 500; color: var(--sg-text-secondary); - font-size: 1rem; + font-size: clamp(0.8rem, 1.2vw, 1rem); text-transform: uppercase; letter-spacing: 0.05em; align-self: end; - grid-row: 2; text-align: center; } -.broad-sub { - grid-column: 1; -} -.coarse-sub { - grid-column: 2; -} -.fine-sub { - grid-column: 3; -} -.manual-sub { - grid-column: 4; -} - -.keyword-input-row { - margin-left: 0.5rem; - width: 100%; - display: grid; - grid-column: 1 / span 4; - display: flex; - align-items: center; - gap: 0.35rem; - - &.compact { - .small-field { - flex: 10; - ::ng-deep .mat-mdc-text-field-wrapper { - padding: 0 0.6rem; - } - ::ng-deep .mat-mdc-form-field-flex { - min-height: 8px; - align-items: center; - } - ::ng-deep .mat-mdc-form-field-infix { - min-height: 8px; - padding: 1rem 0; - } - ::ng-deep .mat-mdc-form-field-subscript-wrapper { - display: none; - } - ::ng-deep input.mat-mdc-input-element { - font-size: 0.8rem; - } - ::ng-deep .mat-mdc-form-field-label, - ::ng-deep mat-label { - font-size: 1rem; - } - } - - button.mat-mdc-icon-button { - width: 28px; - height: 28px; - padding: 0; - line-height: 28px; - flex: 1; - - .mat-icon { - font-size: 26px; - width: 26px; - height: 26px; - line-height: 26px; - } - } - } -} - .table-body { display: grid; grid-template-columns: repeat(3, 1fr) 1.3fr; @@ -265,7 +242,6 @@ mat-button-toggle-group { row-gap: 0.4rem; align-items: start; border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); - //background: var(--sg-background-muted, #f4f5f7); } .table-col { @@ -279,9 +255,6 @@ mat-button-toggle-group { &:last-child { border-right: none; } - &:nth-child(3) { - border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)); - } ::ng-deep app-topic-chip { width: 100%; @@ -292,9 +265,58 @@ mat-button-toggle-group { opacity: 0.4; } } + .thick-border { - border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)); + border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)) !important; } + +@container keyword-tool (max-width: #{$tablet}) { + .table-head, + .table-body { + column-gap: 0.5rem; + } + + .table-col { + padding: 0.4rem; + } +} + +/* ============================================================ + MOBILE KEYWORD TABS (structural replacement for stacked table) + ============================================================ */ +.mobile-keyword-tabs { + margin-top: 0.5rem; + + ::ng-deep .mat-mdc-tab-labels { + justify-content: stretch; + } + + ::ng-deep .mat-mdc-tab { + flex: 1; + min-height: $touch-target; + } +} + +.tab-count { + margin-left: 0.35rem; + font-size: 0.75rem; + font-weight: 600; + color: var(--sg-text-secondary); + background: var(--sg-background-muted, #eceff1); + border-radius: 10px; + padding: 0 6px; + min-width: 18px; + display: inline-block; + text-align: center; +} + +.mobile-tab-panel { + padding: 0.75rem 0.25rem; +} + +/* ============================================================ + CHIP STACKS + ============================================================ */ .keyword-chip-stack { display: flex; flex-direction: column; @@ -307,6 +329,7 @@ mat-button-toggle-group { display: flex; align-items: center; width: 100%; + gap: 0.25rem; app-topic-chip { flex: 1 1 auto; @@ -315,6 +338,8 @@ mat-button-toggle-group { button[mat-icon-button] { flex: 0 0 auto; + min-width: $touch-target; + min-height: $touch-target; } } @@ -370,12 +395,9 @@ mat-button-toggle-group { } } -::ng-deep .mat-mdc-chip-option.compact-chip { - .mat-mdc-chip-action-label { - padding: 0 4px; - } - .mat-mdc-chip-action { - padding: 0 4px; +@container keyword-tool (max-width: #{$tablet}) { + .compact-chip { + width: 100%; } } @@ -391,57 +413,44 @@ mat-button-toggle-group { } } -.select-all-container { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; - justify-content: space-between; - margin-top: 0.5rem; - - button { - display: flex; - justify-content: center; - font-size: 0.75rem; - padding: 0 12px; - line-height: 30px; - mat-icon { - font-size: 26px; - width: 26px; - height: 26px; - } - } -} - +/* ============================================================ + SEARCH BUTTON (sticky on mobile — improves conversion/UX) + ============================================================ */ .search-container { display: flex; justify-content: flex-end; margin-top: 0.5rem; } -/* ============================================================ - RESPONSIVE BREAKPOINTS - ============================================================ */ +.search-btn { + min-height: $touch-target; +} -/* Tablet: soften columns, keep 4 columns but tighter */ -@media (max-width: 1024px) { - .table-head, - .table-body { - column-gap: 0.5rem; +@media (max-width: $phone) { + .search-container { + position: sticky; + bottom: 0; + z-index: 5; + background: var(--sg-background); + padding: 0.75rem 0.5rem; + box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08); } - .table-col { - padding: 0.4rem; - } - - .compact-chip { + .search-btn { width: 100%; } } -/* Small tablet / large phone: stack columns */ -@media (max-width: 768px) { - .content { - padding: 0.75rem; +/* ============================================================ + TABS (URL / Text) — stretch on smaller containers + ============================================================ */ +@container keyword-tool (max-width: #{$tablet}) { + .content ::ng-deep .mat-mdc-tab-labels { + justify-content: stretch; + } + + .content ::ng-deep .mat-mdc-tab { + flex: 1; } .tab-content { @@ -452,87 +461,13 @@ mat-button-toggle-group { width: 100%; justify-content: center; } - - .table-head, - .table-body { - grid-template-columns: 1fr; - } - - .table-head { - display: none; /* labels are redundant once stacked; see column titles below */ - } - - .table-col { - border-right: none; - border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); - padding: 0.75rem 0.25rem; - - &:nth-child(3) { - border-right: none; - border-bottom: 3px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); - } - - &:last-child { - border-bottom: none; - } - - /* Re-introduce a column label since .table-head is hidden */ - &::before { - content: attr(data-col-label); - font-weight: 500; - font-size: 0.85rem; - text-transform: uppercase; - letter-spacing: 0.05em; - color: var(--sg-text-secondary); - margin-bottom: 0.35rem; - display: block; - } - } - - .extracted-header { - grid-column: 1; - grid-row: 1; - } - - .own-header { - grid-column: 1; - grid-row: 2; - } - - .actions { - align-self: center; - justify-content: flex-start; - } - - .search-container, - .select-all-container { - justify-content: stretch; - flex-direction: column; - } - - .search-btn, - .select-all-container button { - width: 100%; - } - - .view-toggle-row { - justify-content: center; - text-align: center; - } - - mat-button-toggle-group { - width: 100%; - - ::ng-deep .mat-button-toggle { - flex: 1; - } - } } -/* Phone: tighten further, reduce chip/font sizes */ -@media (max-width: 480px) { +/* ============================================================ + PHONE-SPECIFIC FINE-TUNING + ============================================================ */ +@container keyword-tool (max-width: #{$phone}) { .content { - padding: 0.5rem; gap: 0.5rem; } @@ -540,8 +475,7 @@ mat-button-toggle-group { padding: 0.35rem; } - .sub-cell, - .toggle-text { + .sub-cell { font-size: 0.8rem; } @@ -559,7 +493,9 @@ mat-button-toggle-group { } } -/* Source expansion panel */ +/* ============================================================ + SOURCE EXPANSION PANEL + ============================================================ */ .source-expansion { margin: 0.75rem 0; background: var(--sg-background-muted, #f5f5f5); @@ -610,6 +546,9 @@ mat-button-toggle-group { } } +/* ============================================================ + PROGRESS BAR + ============================================================ */ .progress-container { margin-top: 1rem; padding: 0.5rem 0; @@ -625,10 +564,7 @@ mat-button-toggle-group { &::after { content: ''; position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; + inset: 0; pointer-events: none; background: linear-gradient( 105deg, @@ -657,3 +593,21 @@ mat-button-toggle-group { transform: translateX(100%); } } + +/* ============================================================ + ACCESSIBILITY + ============================================================ */ +@media (prefers-reduced-motion: reduce) { + .compact-chip, + .progress-container mat-progress-bar::after { + animation: none !important; + transition: none !important; + } +} + +button:focus-visible, +.mat-button-toggle:focus-visible, +::ng-deep .mat-mdc-tab:focus-visible { + outline: 2px solid var(--sg-primary, #1976d2); + outline-offset: 2px; +} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index e2dcc526..1971ca12 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -1,10 +1,5 @@ -import { - Component, - computed, - signal, - Signal, - WritableSignal, -} from '@angular/core'; +import { Component, computed, signal, inject } from '@angular/core'; +import { BreakpointObserver } from '@angular/cdk/layout'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; @@ -30,6 +25,9 @@ import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/t import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component'; import { Topic } from '../../api/model/topic'; +import { NgTemplateOutlet } from '@angular/common'; +import { map } from 'rxjs/operators'; +import { toSignal } from '@angular/core/rxjs-interop'; import { MatButtonToggleModule, MatButtonToggleGroup, @@ -68,6 +66,7 @@ type KeywordView = 'llm' | 'topic'; MatButtonToggleGroup, MatTooltipModule, A11yModule, + NgTemplateOutlet, ], templateUrl: './keywords-search.component.html', styleUrl: './keywords-search.component.scss', @@ -80,7 +79,15 @@ export class KeywordsSearchComponent { }); private readonly SESSION_KEY = 'keywords-search-source'; + // in component class: + private breakpointObserver = inject(BreakpointObserver); + isMobile = toSignal( + this.breakpointObserver + .observe('(max-width: 768px)') + .pipe(map((r) => r.matches)), + { initialValue: false }, + ); // Category signals - the full backend entries are the source of truth; // the *Keywords() computed signals below just project the label out of them. private readonly broadKeywordEntries = signal([]); @@ -98,11 +105,12 @@ export class KeywordsSearchComponent { readonly loadingNewKeyword = signal(false); readonly extractionSource = signal(null); - readonly extractedKeywordsExist = computed( + readonly keywordsExist = computed( () => this.broadKeywords().length > 0 || this.coarseKeywords().length > 0 || - this.fineKeywords().length > 0, + this.fineKeywords().length > 0 || + this.manualKeywords().length > 0, ); readonly sourceContent = signal(''); @@ -309,12 +317,8 @@ export class KeywordsSearchComponent { ...this.getKeywordLabels(this.manualKeywords()), ].some((k) => this.normalizeKeyword(k) === normalized); } - - // Add manually from Keywords tab - addKeywordFromInput(keyword: string): void { - this.loadingNewKeyword.set(true); - - const normalizedKeyword = keyword.trim(); + addKeywordFromInput(keyword: Topic): void { + const normalizedKeyword = keyword.display_name?.trim() ?? ''; if (!normalizedKeyword) return; if (this.keywordExists(normalizedKeyword)) { @@ -322,35 +326,54 @@ export class KeywordsSearchComponent { return; } - this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({ - next: ({ results }) => { - const newEntry: KeywordEntryWithTopic = { - llm_keyword: { - keyword: normalizedKeyword, - relevance_score: 1, - }, - topic_mapping: { - keyword: normalizedKeyword, - topic: results?.[0], - }, - }; + this.loadingNewKeyword.set(true); - const updated = this.uniqueKeywordEntries([ - ...this.manualKeywordEntries(), - newEntry, - ]); + if (keyword.id === null) { + console.log('Adding new keyword without topic:', normalizedKeyword); + this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({ + next: ({ results }) => { + const newEntry: KeywordEntryWithTopic = { + llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 }, + topic_mapping: { keyword: normalizedKeyword, topic: results?.[0] }, + }; - this.manualKeywordEntries.set(updated); - this.selectedKeywords.set([ - ...this.selectedKeywords(), - normalizedKeyword, - ]); - this.loadingNewKeyword.set(false); - // Explicit enrichment trigger for new keywords - this.enrichManualKeywordsWithTopics([normalizedKeyword]); - this.updateQueryParams(); - }, - }); + this.manualKeywordEntries.set( + this.uniqueKeywordEntries([ + ...this.manualKeywordEntries(), + newEntry, + ]), + ); + this.selectedKeywords.set([ + ...this.selectedKeywords(), + normalizedKeyword, + ]); + this.loadingNewKeyword.set(false); + this.updateQueryParams(); // now fires after state is actually updated + }, + error: (err) => { + console.error('vectorSearchTopics failed', err); + this.loadingNewKeyword.set(false); + this.statusMessage.set( + `Fehler beim Hinzufügen von "${normalizedKeyword}".`, + ); + }, + }); + } else { + console.log('we dont search', keyword); + const newEntry: KeywordEntryWithTopic = { + llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 }, + topic_mapping: { keyword: normalizedKeyword, topic: keyword }, + }; + this.manualKeywordEntries.set( + this.uniqueKeywordEntries([...this.manualKeywordEntries(), newEntry]), + ); + this.selectedKeywords.set([ + ...this.selectedKeywords(), + normalizedKeyword, + ]); + this.loadingNewKeyword.set(false); + this.updateQueryParams(); + } } removeSelectedKeyword(keyword: string): void { @@ -388,7 +411,7 @@ export class KeywordsSearchComponent { this.updateQueryParams(); } - selectAllExtracted(): void { + selectAll(): void { const all = [ ...this.getKeywordLabels(this.manualKeywords()), ...this.getKeywordLabels(this.broadKeywords()), @@ -399,10 +422,8 @@ export class KeywordsSearchComponent { this.updateQueryParams(); } - deselectAllExtracted(): void { - this.selectedKeywords.set( - this.uniqueKeywords(this.getKeywordLabels(this.manualKeywords())), - ); + deselectAll(): void { + this.selectedKeywords.set([]); this.updateQueryParams(); } @@ -410,6 +431,7 @@ export class KeywordsSearchComponent { this.broadKeywordEntries.set([]); this.coarseKeywordEntries.set([]); this.fineKeywordEntries.set([]); + this.manualKeywordEntries.set([]); this.sourceContent.set(''); this.sourceUrl.set(null); @@ -428,11 +450,12 @@ export class KeywordsSearchComponent { this.updateQueryParams(); } - areAllExtractedSelected(): boolean { + areAllSelected(): boolean { const allExtracted = [ ...this.getKeywordLabels(this.broadKeywords()), ...this.getKeywordLabels(this.coarseKeywords()), ...this.getKeywordLabels(this.fineKeywords()), + ...this.getKeywordLabels(this.manualKeywords()), ]; return allExtracted.every((k) => this.selectedKeywords().includes(k)); } From 86bed62ac0141d0655b7428cdd80b4fc8b2963ba Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 18:10:24 +0200 Subject: [PATCH 36/41] delete button removed for autocompletion field --- .../ui/topic-autocomplete/topic-autocomplete.component.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html index 5be3be18..91a2bdcc 100644 --- a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html @@ -23,7 +23,7 @@ } - @if (searchControl.value) { + Date: Sun, 5 Jul 2026 18:35:39 +0200 Subject: [PATCH 37/41] cleaned log outputs --- .../app/modules/keywords-search/keywords-search.component.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 1971ca12..26a5f014 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -200,7 +200,6 @@ export class KeywordsSearchComponent { this.handleStatusEvent(event); break; case 'keywords': - console.log(event.keywords); if (event.keywords) this.addExtractedKeyword(event.keywords); break; case 'completed': @@ -359,7 +358,7 @@ export class KeywordsSearchComponent { }, }); } else { - console.log('we dont search', keyword); + console.log('topic was already there', keyword); const newEntry: KeywordEntryWithTopic = { llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 }, topic_mapping: { keyword: normalizedKeyword, topic: keyword }, From 3867540a4cdb1cc2c28a05269032ead9291648c9 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 5 Jul 2026 19:46:24 +0200 Subject: [PATCH 38/41] refactor(publications, people): unify active topic chip, add loading states --- .../person-card/person-card.component.html | 2 + .../person-card/person-card.component.scss | 8 + .../person-list/person-list.component.html | 23 +- .../person-list/person-list.component.scss | 43 +- .../person-publications.component.html | 23 +- .../person-publications.component.scss | 370 ++++++------------ webapp/src/styles.scss | 45 +++ 7 files changed, 230 insertions(+), 284 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 49edc9ae..946430ae 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -58,7 +58,9 @@ type="button" class="institution-tag" [class.active]="isInstitutionActive()" + [class.is-loading]="loading()" [matTooltip]="inst.display_name || ''" + [matTooltipDisabled]="loading()" matTooltipPosition="above" (click)=" institutionClick.emit(inst.display_name || ''); diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index c8b2db5a..75f0ed69 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -185,6 +185,14 @@ background: var(--sg-primary); color: #fff; } + + &.is-loading { + pointer-events: none; + background: var(--sg-surface-soft); + border-color: var(--sg-border); + color: var(--sg-text-soft); + box-shadow: none; + } } .flag-img { diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index fd360b6e..8f3b0f37 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -38,19 +38,14 @@ ) { @if (filter.category === 'topic') { - Thema: - - + + label + {{ + filter.value + }} +
+ + + + + {{ getDisplayName(institution) }} + {{ institution.geo?.city }}, + {{ institution.geo?.country }} + + + + + + + + + + + + info + Übersicht + + + article + Publikationen + + + work + Projekte + + + verified + Patente + + + + + diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 8edbecef..ce9afb83 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -5,23 +5,6 @@ padding: 1rem; } -.sorting { - display: flex; - justify-content: flex-end; - gap: 0.5rem; -} - -.sorting select { - padding: 0.75rem; - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - font-size: 1rem; -} - -.sorting select:hover { - cursor: pointer; -} - .cards { display: grid; gap: 1.5rem; @@ -71,13 +54,3 @@ mat-card-actions a { border: 1px solid var(--sg-border); border-radius: var(--sg-radius-sm); } - -.no-results { - text-align: center; - padding: 2rem; - color: var(--sg-text-secondary); -} - -.search-and-sorting { - padding: 0 1rem; -} diff --git a/webapp/src/app/modules/institutions/institutions.component.ts b/webapp/src/app/modules/institutions/institutions.component.ts index 18eea25f..48abc772 100644 --- a/webapp/src/app/modules/institutions/institutions.component.ts +++ b/webapp/src/app/modules/institutions/institutions.component.ts @@ -1,16 +1,16 @@ -import { Component, input } from '@angular/core'; +import { Component, computed, input } from '@angular/core'; import { Institution, InstitutionPage } from '../../api'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { RouterModule } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatDividerModule } from '@angular/material/divider'; -import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; + +import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; import { - QueryParamSelectorComponent, - SelectorOption, -} from '../../shared/ui/query-param-selector/query-param-selector.component'; -import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; + Page, + CardSearchComponent, +} from '../../shared/ui/card-search/card-search.component'; @Component({ selector: 'app-institutions', @@ -20,9 +20,7 @@ import { QueryParamInputComponent } from '../../shared/ui/query-param-input/quer MatIconModule, MatDividerModule, RouterModule, - QueryParamPaginatorComponent, - QueryParamSelectorComponent, - QueryParamInputComponent, + CardSearchComponent, ], templateUrl: './institutions.component.html', styleUrl: './institutions.component.scss', @@ -30,6 +28,13 @@ import { QueryParamInputComponent } from '../../shared/ui/query-param-input/quer export class InstitutionsComponent { institutionPage = input.required(); + page = computed(() => ({ + page: this.institutionPage().page || 0, + size: this.institutionPage().size || 10, + total: this.institutionPage().total || 0, + elements: this.institutionPage().elements || [], + })); + sortingOptions: SelectorOption[] = [ { value: 'relevance', display_name: 'Relevanz' }, { value: 'name', display_name: 'Name' }, diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index b2bcbddf..210363ec 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -2,98 +2,59 @@

Passende Projekte finden

- -
- - - -
- - EU - BUND - DFG - - -
- - - -
-
-
- - - - @let fundingProjectPageValue = fundingProjectPage(); - - @if ( - fundingProjectPageValue.elements && - fundingProjectPageValue.elements.length > 0 - ) { -
- @for (fundingProject of fundingProjectPageValue.elements; track $index) { - - - {{ fundingProject.title }} - {{ - fundingProject.type | uppercase - }} - - - - - - - - - - - - info - Übersicht - - - - - } -
- } @else { -
-

Keine passenden Projekte gefunden.

-
- } - - - - +
+ + + + + {{ element.title }} + {{ element.type | uppercase }} + + + + + + + + + + + + info + Übersicht + + + + + + + + + EU + BUND + DFG + + diff --git a/webapp/src/app/modules/projects/projects.component.scss b/webapp/src/app/modules/projects/projects.component.scss index 32a0f31e..55063bd0 100644 --- a/webapp/src/app/modules/projects/projects.component.scss +++ b/webapp/src/app/modules/projects/projects.component.scss @@ -5,23 +5,6 @@ padding: 1rem; } -.sorting { - display: flex; - justify-content: flex-end; - gap: 0.5rem; -} - -.sorting select { - padding: 0.75rem; - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - font-size: 1rem; -} - -.sorting select:hover { - cursor: pointer; -} - .cards { display: grid; gap: 1.5rem; @@ -29,10 +12,6 @@ padding: 0 1rem; } -mat-paginator { - background-color: var(--sg-background); -} - .card { padding: 0.5rem; background-color: var(--sg-background); @@ -76,12 +55,6 @@ mat-card-actions a { border-radius: var(--sg-radius-sm); } -.no-results { - text-align: center; - padding: 2rem; - color: var(--sg-text-secondary); -} - .mat-mdc-standard-chip { border-radius: var(--sg-radius-sm); } diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts index 4361c9bb..984ee116 100644 --- a/webapp/src/app/modules/projects/projects.component.ts +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -1,4 +1,4 @@ -import { Component, input, signal } from '@angular/core'; +import { Component, computed, input, signal } from '@angular/core'; import { FundingProject, FundingProjectPage, ProjectType } from '../../api'; import { MatDividerModule } from '@angular/material/divider'; import { MatIconModule } from '@angular/material/icon'; @@ -8,12 +8,12 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { DatePipe, UpperCasePipe } from '@angular/common'; import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; -import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; -import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; + +import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; import { - QueryParamSelectorComponent, - SelectorOption, -} from '../../shared/ui/query-param-selector/query-param-selector.component'; + CardSearchComponent, + Page, +} from '../../shared/ui/card-search/card-search.component'; @Component({ selector: 'app-projects', @@ -26,9 +26,7 @@ import { UpperCasePipe, DatePipe, MatChipsModule, - QueryParamInputComponent, - QueryParamPaginatorComponent, - QueryParamSelectorComponent, + CardSearchComponent, ], templateUrl: './projects.component.html', styleUrl: './projects.component.scss', @@ -36,6 +34,13 @@ import { export class ProjectsComponent { fundingProjectPage = input.required(); + page = computed(() => ({ + page: this.fundingProjectPage().page || 0, + size: this.fundingProjectPage().size || 10, + total: this.fundingProjectPage().total || 0, + elements: this.fundingProjectPage().elements || [], + })); + urlChips = signal(['eu', 'bund', 'dfg']); sortingOptions: SelectorOption[] = [{ value: 'title', display_name: 'Name' }]; @@ -72,13 +77,14 @@ export class ProjectsComponent { getDetaiLink(fundingProject: FundingProject): string | null { if (fundingProject.type === 'bund') { - const encodedId = encodeURIComponent(fundingProject.id) + const encodedId = encodeURIComponent(fundingProject.id); return '/projects/bund/' + encodedId; } else if (fundingProject.type === 'dfg') { return '/projects/dfg/' + fundingProject.id; } else if (fundingProject.type === 'eu') { return '/projects/eu/' + fundingProject.id; - } else + } else { return null; } + } } diff --git a/webapp/src/app/shared/ui/card-search/card-search.component.html b/webapp/src/app/shared/ui/card-search/card-search.component.html new file mode 100644 index 00000000..c06d03a6 --- /dev/null +++ b/webapp/src/app/shared/ui/card-search/card-search.component.html @@ -0,0 +1,54 @@ + diff --git a/webapp/src/app/shared/ui/card-search/card-search.component.scss b/webapp/src/app/shared/ui/card-search/card-search.component.scss new file mode 100644 index 00000000..521dda4c --- /dev/null +++ b/webapp/src/app/shared/ui/card-search/card-search.component.scss @@ -0,0 +1,31 @@ +.card-search { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.card-search-filter { + display: flex; + flex-direction: row; + gap: 1rem; + padding: 0rem 1rem; +} + +.cards { + display: grid; + gap: 1.5rem; + grid-template-columns: repeat(auto-fit, minmax(var(--card-min-width), 1fr)); + padding: 0 1rem; +} + +.pagination { + display: flex; + justify-content: end; + padding: 0rem 1rem; +} + +.no-results { + text-align: center; + padding: 2rem; + color: var(--sg-text-secondary); +} diff --git a/webapp/src/app/shared/ui/card-search/card-search.component.ts b/webapp/src/app/shared/ui/card-search/card-search.component.ts new file mode 100644 index 00000000..0b8bcc5b --- /dev/null +++ b/webapp/src/app/shared/ui/card-search/card-search.component.ts @@ -0,0 +1,50 @@ +import { Component, input, TemplateRef } from '@angular/core'; +import { QueryParamInputComponent } from '../query-param-input/query-param-input.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../query-param-selector/query-param-selector.component'; +import { MatDivider } from '@angular/material/divider'; +import { QueryParamPaginatorComponent } from '../query-param-paginator/query-param-paginator.component'; +import { NgTemplateOutlet } from '@angular/common'; + +export type Page = { + page: number; + size: number; + total: number; + elements: any[]; +}; + +@Component({ + selector: 'app-card-search', + imports: [ + QueryParamInputComponent, + QueryParamSelectorComponent, + MatDivider, + QueryParamPaginatorComponent, + NgTemplateOutlet, + ], + templateUrl: './card-search.component.html', + styleUrl: './card-search.component.scss', +}) +export class CardSearchComponent { + cardTmp = input.required>(); + additionalFiltersTmp = input>(); + noResultsTmp = input>(); + + + cardMinWidth = input(300); + + page = input.required(); + + withSearch = input(true); + searchLabel = input('Suchen'); + searchQueryParamKey = input('search'); + + sortingOptions = input(); + sortByQueryParamKey = input('sort_by'); + sortByLabel = input('Sortieren nach'); + sortingDirectionOptions = input(); + sortingDirectionQueryParamKey = input('sorting_order'); + sortingDirectionLabel = input('Sortierreihenfolge'); +} From c38355c817f68462a7eb1f75966d46a9b6008724 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 19:53:23 +0200 Subject: [PATCH 40/41] minor logic and layout adjustments --- .../keywords-search.component.html | 600 +++++++++--------- .../keywords-search.component.scss | 15 +- .../keywords-search.component.ts | 31 +- 3 files changed, 340 insertions(+), 306 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index e1de98d3..dbb9f941 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -43,10 +43,12 @@
@@ -54,134 +56,120 @@ + @if (isExtracting()) { +
+ + +
{{ statusMessage() }}
+
+ } -
- - - -
- @if (topicLegendGroups.length > 0) { - - - } - - -
- @if (keywordsExist()) { -
-
- @if (areAllSelected()) { - - } @else { - - } -
-
- - - - text_fields - Extrahierte Keywords - - - account_tree - Topic Mapping - - -
- -
- -
-
- } @else { - -
+ @if (keywordsExist()) { +
+ + + +
+ @if (topicLegendGroups.length > 0) { + + } -
- + +
+ @if (!isExtracting()) { +
+
+ @if (areAllSelected()) { + + } @else { + + } +
+
+ + + + text_fields + Extrahierte Keywords + + + account_tree + Topic Mapping + + +
+ +
+ +
+
+ } @else { + +
+ } + +
+ +
-
- - - @if (keywords.length > 0) { -
- @for (keyword of keywords; track keyword.llm_keyword.keyword) { - - - } -
- } @else { -

{{ emptyText }}

- } -
- - -
- @if (manualKeywords().length > 0) { - @for ( - keyword of manualKeywords(); - track keyword.llm_keyword.keyword - ) { -
+ + + @if (keywords.length > 0) { +
+ @for ( + keyword of keywords; + track keyword.llm_keyword.keyword + ) { - -
- } - } @else if (loadingNewKeyword()) { -
- - + }
} @else { -

Nichts hinzugefügt

+

{{ emptyText }}

} -
- + - - @if (!isMobile()) { -
-
-
Breite Keywords
-
Coarse Keywords
-
- Fine Keywords -
-
Eigene Keywords
+ +
+ @if (manualKeywords().length > 0) { + @for ( + keyword of manualKeywords(); + track keyword.llm_keyword.keyword + ) { +
+ + + +
+ } + } @else { +

Nichts hinzugefügt

+ } + @if (loadingNewKeyword()) { +
+ + + +
+ }
+
-
-
- + + @if (!isMobile()) { +
+
+
+ Breite Keywords +
+
+ Coarse Keywords +
+
+ Fine Keywords +
+
+ Eigene Keywords +
-
- -
+
+
+ +
-
- -
+
+ +
-
- +
+ +
+ +
+ +
-
- } @else { - - - - - Breit - {{ broadKeywords().length }} - -
- -
-
+ } @else { + + + + + Breit + {{ broadKeywords().length }} + +
+ +
+
- - - Coarse - {{ coarseKeywords().length }} - -
- -
-
+ + + Coarse + {{ coarseKeywords().length }} + +
+ +
+
- - - Fine - {{ fineKeywords().length }} - -
- -
-
+ + + Fine + {{ fineKeywords().length }} + +
+ +
+
- - - Eigene - {{ manualKeywords().length }} - -
- -
-
-
- } + + + Eigene + {{ manualKeywords().length }} + +
+ +
+
+
+ } - @if (isExtracting()) { -
- - -
{{ statusMessage() }}
-
- } @else if (!keywordsExist()) { -

- Noch keine Keywords vorhanden. Extrahiere Keywords aus URL/Text - oder füge oben eigene Keywords hinzu. -

- } + + @if (sourceContent().length > 0) { + + + + Quellentext: {{ sourceUrl() }} + +
{{ sourceContent() }}
+
+ } + + +
- - @if (sourceContent().length > 0) { - - - - Quellentext: {{ sourceUrl() }} - -
{{ sourceContent() }}
-
- } - - -
- - -
- -
+ +
+ +
+ }
diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index cfa3f8b9..15e6e6c5 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -19,11 +19,11 @@ $touch-target: 44px; } .tab-content { - display: grid; + display: flex; + flex-direction: column; margin-top: 0.5rem; - grid-template-columns: 5fr 1fr; gap: 0.5rem; - align-items: start; + align-items: center; } .full-width { @@ -32,6 +32,7 @@ $touch-target: 44px; .extract-btn { white-space: nowrap; + min-width: 240px; min-height: $touch-target; } @@ -418,11 +419,13 @@ mat-button-toggle-group { ============================================================ */ .search-container { display: flex; - justify-content: flex-end; + justify-content: center; margin-top: 0.5rem; } .search-btn { + min-width: 240px; + align-self: center; min-height: $touch-target; } @@ -454,6 +457,7 @@ mat-button-toggle-group { } .tab-content { + display: grid; grid-template-columns: 1fr; } @@ -461,6 +465,9 @@ mat-button-toggle-group { width: 100%; justify-content: center; } + .search-btn { + width: 100%; + } } /* ============================================================ diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 26a5f014..4870cd4b 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -409,15 +409,27 @@ export class KeywordsSearchComponent { ); this.updateQueryParams(); } + allKeywordEntries = computed(() => [ + ...this.manualKeywords(), + ...this.broadKeywords(), + ...this.coarseKeywords(), + ...this.fineKeywords(), + ]); selectAll(): void { - const all = [ - ...this.getKeywordLabels(this.manualKeywords()), - ...this.getKeywordLabels(this.broadKeywords()), - ...this.getKeywordLabels(this.coarseKeywords()), - ...this.getKeywordLabels(this.fineKeywords()), - ]; - this.selectedKeywords.set(this.uniqueKeywords(all)); + const seen = new Set(); + const result: string[] = []; + + for (const entry of this.allKeywordEntries()) { + const label = entry.llm_keyword.keyword; + const normalized = this.normalizeKeyword(label); + if (!seen.has(normalized)) { + seen.add(normalized); + result.push(label); + } + } + + this.selectedKeywords.set(result); this.updateQueryParams(); } @@ -426,7 +438,7 @@ export class KeywordsSearchComponent { this.updateQueryParams(); } - clearExtractedKeywords(): void { + clearKeywords(): void { this.broadKeywordEntries.set([]); this.coarseKeywordEntries.set([]); this.fineKeywordEntries.set([]); @@ -502,7 +514,7 @@ export class KeywordsSearchComponent { } async extractKeywords(): Promise { - this.clearExtractedKeywords(); + this.clearKeywords(); const query = this.getCurrentExtractionQuery(); if (!query) return; @@ -564,6 +576,7 @@ export class KeywordsSearchComponent { this.fineKeywordEntries.set( this.uniqueKeywordEntries(keywords.fine_grained, seenKeywords), ); + this.selectAll(); } private getSelectedExtractedKeywordEntries(): KeywordEntryWithTopic[] { From a07fadc30e8ace7746c168d25271da020cec3169 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 20:10:53 +0200 Subject: [PATCH 41/41] deleted unused TopicChipComponent from person-list --- webapp/src/app/modules/person-list/person-list.component.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts index d1ad59a8..e363e90f 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -23,7 +23,6 @@ import { import { TopicsService } from '../../api/api/topics.service'; import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component'; import { PersonCardComponent } from '../person-card/person-card.component'; -import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { SharedStateService } from '../../shared/services/shared-state.service'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -57,7 +56,6 @@ import { SkTextDirective } from '../../custom-directives/sk-text.directive'; MatRadioModule, TopicHierarchyComponent, PersonCardComponent, - TopicChipComponent, SkTextDirective, MatAutocompleteModule, ],