From 1bf595915d48aec2e9d80df12d7cb2a275b4e5ba Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sat, 20 Jun 2026 11:07:40 +0200 Subject: [PATCH 01/81] feat(patents): extend patent details with CPC, application info, claims and status --- .../inse/patents/elastic_search_client.py | 14 ++- service/src/main/inse/patents/logic.py | 12 +++ service/src/main/inse/patents/model.py | 10 ++- webapp/src/app/api/api/patents.service.ts | 9 +- .../person-patents.component.html | 88 +++++++++++++++---- .../person-patents.component.scss | 77 +++++++++++----- 6 files changed, 165 insertions(+), 45 deletions(-) diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 64d5865e..f10694e6 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -97,13 +97,15 @@ class PatentSearchClient: "kind", "date_publication", "date_publication_year", + "application_number", + "application_filing_date", "title_en", "title_de", "abstract", "inventors_name", "applicants_name", "ipc", - "ipc_text", + "cpc", ], "query": query, } @@ -150,13 +152,17 @@ class PatentSearchClient: "country", "publication_date", "publication_year", + "application_number", + "application_date", + "application_type", "title", "abstract", "inventors_names", - "inventors_names_text", "assignees_orgs", "ipcr", - "ipcr_text", + "cpc", + "number_of_claims", + "status", ], "query": query, } @@ -179,4 +185,4 @@ class PatentSearchClient: json=payload, ) response.raise_for_status() - return response.json() + return response.json() \ No newline at end of file diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 7e82cc31..d5227bcc 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -87,6 +87,7 @@ def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: inventors = src.get("inventors_name") or [] applicants = src.get("applicants_name") or [] ipc = src.get("ipc") or [] + cpc = src.get("cpc") or [] patents.append(model.PatentEntry( patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", source="EPO", @@ -94,9 +95,13 @@ def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: abstract=src.get("abstract"), publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, + application_number=src.get("application_number"), + application_date=src.get("application_filing_date"), + kind=src.get("kind"), inventors=inventors if isinstance(inventors, list) else [inventors], assignees=applicants if isinstance(applicants, list) else [applicants], ipc=ipc if isinstance(ipc, list) else [ipc], + cpc=cpc if isinstance(cpc, list) else [cpc], country=src.get("country", "EP"), )) return patents @@ -109,6 +114,7 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: inventors = src.get("inventors_names") or [] assignees = src.get("assignees_orgs") or [] ipc = src.get("ipcr") or [] + cpc = src.get("cpc") or [] patents.append(model.PatentEntry( patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}", source="USPTO", @@ -116,9 +122,15 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: abstract=src.get("abstract"), publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, + application_number=src.get("application_number"), + application_date=str(src.get("application_date")) if src.get("application_date") else None, + application_type=src.get("application_type"), + number_of_claims=src.get("number_of_claims"), + status=src.get("status"), inventors=inventors if isinstance(inventors, list) else [inventors], assignees=assignees if isinstance(assignees, list) else [assignees], ipc=ipc if isinstance(ipc, list) else [ipc], + cpc=cpc if isinstance(cpc, list) else [cpc], country=src.get("country", "US"), )) return patents diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index 31ebc18c..dd622b70 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -8,13 +8,21 @@ class PatentEntry(BaseModel): abstract: str | None = None publication_date: str | None = None publication_year: str | None = None + application_number: str | None = None + application_date: str | None = None + kind: str | None = None # EPO only + application_type: str | None = None # USPTO only + number_of_claims: int | None = None # USPTO only + status: str | None = None # USPTO only inventors: list[str] = Field(default_factory=list) assignees: list[str] = Field(default_factory=list) ipc: list[str] = Field(default_factory=list) + cpc: list[str] = Field(default_factory=list) country: str | None = None + class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int - patents: list[PatentEntry] + patents: list[PatentEntry] \ No newline at end of file diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 6a0e0b8a..33d7412b 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -28,12 +28,17 @@ export interface PatentEntry { abstract: string | null; publication_date: string | null; publication_year: string | null; + application_number: string | null; + application_date: string | null; + kind: string | null; + application_type: string | null; + number_of_claims: number | null; + status: string | null; inventors: string[]; assignees: string[]; ipc: string[]; + cpc: string[]; country: string | null; - confidence_score: number; - } export interface PatentsByAuthorResponse { diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 559aa284..db0c6bbb 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -6,20 +6,6 @@

Keine Patente gefunden.

} @else {
-
-

- {{ filteredPatents.length }} - Patente -

-

- {{ getEpoCount() }} - EPO -

-

- {{ getUsptoCount() }} - USPTO -

-
@if (showDetail && selectedPatent) {
} + + @if (selectedPatent.cpc.length > 0) { +
+

Klassifikation (CPC)

+ +
+ } + + @if (selectedPatent.application_number) { +
+

Anmeldungsnummer

+

{{ selectedPatent.application_number }}

+
+ } + + @if (selectedPatent.application_date) { +
+

Anmeldedatum

+

{{ formatDate(selectedPatent.application_date) }}

+
+ } + + @if (selectedPatent.kind) { +
+

Patentart

+

{{ selectedPatent.kind }}

+
+ } + + @if (selectedPatent.application_type) { +
+

Anmeldungstyp

+

{{ selectedPatent.application_type }}

+
+ } + + @if (selectedPatent.number_of_claims) { +
+

Anzahl Ansprüche

+

{{ selectedPatent.number_of_claims }}

+
+ } + + @if (selectedPatent.status) { +
+

Status

+

{{ selectedPatent.status }}

+
+ } + } @@ -148,8 +188,24 @@ } @else { -
-

Klicke auf ein Patent für Details.

+
+

Patentübersicht

+

Alle Patente dieser Person im Überblick.

+
+
+ {{ patents.length }} + Patente +
+
+ {{ getEpoCount() }} + EPO +
+
+ {{ getUsptoCount() }} + USPTO +
+
+

Wähle links ein Patent aus, um die Details zu sehen.

}
diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index df70826d..befd90ad 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -10,27 +10,6 @@ gap: 16px; } -.patents-summary { - margin-bottom: 8px; - display: flex; - gap: 24px; - - .summary-line { - margin: 0; - font-size: 14px; - color: #333; - } - - .summary-label { - color: #333; - } - - .summary-value { - font-weight: 600; - color: #333; - } -} - .sort-control { display: inline-flex; align-items: center; @@ -154,6 +133,60 @@ min-height: 200px; } + &.overview { + display: flex; + flex-direction: column; + gap: 12px; + + .overview-title { + font-size: 15px; + font-weight: 600; + color: #333; + margin: 0; + } + + .overview-subtitle { + font-size: 13px; + color: #888; + margin: 0; + } + + .overview-stats { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 10px; + margin-top: 4px; + } + + .overview-stat { + background: white; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 12px 8px; + text-align: center; + + .overview-value { + display: block; + font-size: 22px; + font-weight: 700; + color: #333; + } + + .overview-label { + display: block; + font-size: 12px; + color: #888; + margin-top: 4px; + } + } + + .overview-hint { + font-size: 12px; + color: #aaa; + margin: 0; + } + } + h3 { margin: 0 0 16px 0; font-size: 16px; @@ -239,7 +272,7 @@ font-size: 14px; font-weight: 400; padding: 0; - align-self: flex-start; // NEU + align-self: flex-start; &:hover { text-decoration: underline; From 50dbf0dc2f6a10ce861d2883a247bbbd76e819af Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 21 Jun 2026 15:04:59 +0200 Subject: [PATCH 02/81] refactor(news): extract news list into shared component --- .../news-detail/news-detail.component.scss | 3 + .../src/app/modules/news/news.component.html | 121 +++---------- .../src/app/modules/news/news.component.scss | 168 ----------------- webapp/src/app/modules/news/news.component.ts | 50 +----- .../person-news/person-news.component.html | 86 ++------- .../person-news/person-news.component.scss | 132 -------------- .../person-news/person-news.component.ts | 53 ++---- .../src/app/resolvers/person-news.resolver.ts | 1 + .../ui/news-list/news-list.component.html | 103 +++++++++++ .../ui/news-list/news-list.component.scss | 169 ++++++++++++++++++ .../ui/news-list/news-list.component.ts | 95 ++++++++++ 11 files changed, 423 insertions(+), 558 deletions(-) create mode 100644 webapp/src/app/shared/ui/news-list/news-list.component.html create mode 100644 webapp/src/app/shared/ui/news-list/news-list.component.scss create mode 100644 webapp/src/app/shared/ui/news-list/news-list.component.ts diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index 82f7b1ac..17d325bb 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -180,6 +180,9 @@ main { display: flex; flex-direction: column; gap: 8px; + max-height: 375px; + overflow-y: auto; + padding-right: 4px; } .person-item { diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index aff9aadc..7eadac9a 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -4,107 +4,26 @@

Aktuelle Nachrichten aus Campus-Aktuell.

-
- - search - - - - @if (!isSearching) { - - - Neueste zuerst - Älteste zuerst - - + + @if (article.snippet) { + + } @else { + — } -
+ -
- @if (loading) { -
- -
- } - - - - - - - - - - - - - - - - - - - - - - - - -
Titel - {{ - article.maintitle || 'Kein Titel' - }} - Fundstelle - @if (article.snippet) { - - } @else { - — - } - Relevanz - @if (article.relevant === true) { - - check_circle - Relevant - - } @else if (article.relevant === false) { - - cancel - Nicht relevant - - } @else { - - help - Nicht bestimmt - - } - Datum - {{ formatDate(article.date) }} -
- - @if (!loading && articles.length === 0) { -
- @if (isSearching) { - Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. - } @else { - Keine Nachrichten gefunden. - } -
- } -
- - + + diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index 100dead9..8cc7660b 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -17,103 +17,6 @@ h6 { font-size: 14px; } -.news-toolbar { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 12px; - padding-top: 10px; - padding-bottom: 25px; -} - -.search-field { - max-width: 480px; -} - -::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { - display: none; -} - -::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { - height: 42px; - background: #fff; - border-radius: var(--sg-radius-sm); -} - -::ng-deep .news-toolbar .mat-mdc-form-field-infix { - min-height: unset; - height: 42px; - padding: 0; - display: flex; - align-items: center; -} - -::ng-deep .news-toolbar .mdc-notched-outline__leading, -::ng-deep .news-toolbar .mdc-notched-outline__notch, -::ng-deep .news-toolbar .mdc-notched-outline__trailing { - border-color: #d9e2f0; -} - -::ng-deep .news-toolbar input.mat-mdc-input-element { - color: var(--sg-text); - font-size: 14px; -} - -::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { - color: var(--sg-text-muted); - opacity: 1; - font-size: 14px; -} - -.sort-field { - width: 180px; -} - -.table-wrap { - position: relative; - overflow-x: auto; -} - -table { - width: 100%; - min-width: 600px; - border-collapse: separate; - border-spacing: 0 10px; - background: transparent; - box-shadow: none; -} - -.article-title { - display: inline-block; - max-width: 520px; - line-height: 1.35; - color: var(--sg-text); - font-size: 14px; - font-weight: 700; - text-decoration: none; - - &:hover { - color: var(--sg-text); - text-decoration: underline; - } -} - -.loading { - position: absolute; - inset: 0; - z-index: 1; - display: grid; - place-items: center; - background: rgba(255, 255, 255, 0.65); -} - -.empty-state { - padding: 28px; - text-align: center; - color: rgba(0, 0, 0, 0.6); - background: transparent; -} - .snippet { color: var(--sg-text-muted); font-size: 13px; @@ -131,79 +34,8 @@ table { color: var(--sg-text-muted); } -.relevance-badge { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 5px 12px; - border-radius: 999px; - font-size: 13px; - font-weight: 600; - line-height: 1; - white-space: nowrap; - - mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - } - - &.is-relevant { - background: #effaf3; - border: 1px solid #bdebcf; - color: #24834f; - } - - &.not-relevant { - background: var(--sg-surface-muted); - border: 1px solid #e2e2e2; - color: var(--sg-text-muted); - } - - &.undetermined { - background: #fff7e8; - border: 1px solid #ffd796; - color: #c67500; - } -} - -::ng-deep .mat-mdc-header-cell { - color: var(--sg-text-muted); - font-size: 12px; - font-weight: 700; -} - -::ng-deep .mat-mdc-row { - height: 72px; -} - -::ng-deep .mat-mdc-cell { - color: var(--sg-text); - border-bottom-color: var(--sg-border); - font-size: 13px; -} - -mat-paginator { - background: transparent; -} - -.table-footer { - display: flex; - align-items: center; - justify-content: space-between; - min-height: 66px; - padding: 0 22px 0 28px; - color: var(--sg-text-muted); - font-size: 13px; -} - @media (max-width: 600px) { .page { padding: 16px; } - - .table-footer { - align-items: stretch; - flex-direction: column; - } } diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index 3c1ff74c..dc78da38 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -1,27 +1,21 @@ import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, Router, RouterLink } from '@angular/router'; -import { MatIconModule } from '@angular/material/icon'; -import { MatSelectModule } from '@angular/material/select'; -import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; -import { MatTableModule } from '@angular/material/table'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatInputModule } from '@angular/material/input'; +import { ActivatedRoute, Router } from '@angular/router'; +import { PageEvent } from '@angular/material/paginator'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; +import { + NewsArticleBase, + NewsListComponent, + SortOrder, +} from '../../shared/ui/news-list/news-list.component'; -interface NewsArticle { - id: string; - date?: string | null; - maintitle?: string | null; +interface NewsArticle extends NewsArticleBase { author?: string | null; - url?: string | null; - relevant?: boolean | null; snippet?: string | null; } @@ -32,22 +26,11 @@ interface NewsPage { results: NewsArticle[]; } -type SortOrder = 'desc' | 'asc'; const DEFAULT_SORT_ORDER: SortOrder = 'desc'; @Component({ selector: 'app-news', - imports: [ - MatIconModule, - MatSelectModule, - MatFormFieldModule, - MatInputModule, - MatPaginatorModule, - MatProgressSpinnerModule, - MatTableModule, - ReactiveFormsModule, - RouterLink, - ], + imports: [ReactiveFormsModule, NewsListComponent], templateUrl: './news.component.html', styleUrl: './news.component.scss', }) @@ -179,21 +162,6 @@ export class NewsComponent implements OnInit { }); } - formatDate(dateStr?: string | null): string { - if (!dateStr) return '-'; - const date = new Date(dateStr); - if (isNaN(date.getTime())) return dateStr; - return new Intl.DateTimeFormat('de-DE').format(date); - } - - articleRange(): string { - if (this.total === 0) return 'Keine Nachrichten gefunden'; - const pageSize = this.paginationService.selection; - const start = (this.currentPage - 1) * pageSize + 1; - const end = Math.min(start + this.articles.length - 1, this.total); - return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; - } - private parsePage(value: string | null): number { const page = Number.parseInt(value ?? '', 10); if (Number.isNaN(page) || page < 1) { diff --git a/webapp/src/app/modules/person-news/person-news.component.html b/webapp/src/app/modules/person-news/person-news.component.html index b4f717db..651e39d4 100644 --- a/webapp/src/app/modules/person-news/person-news.component.html +++ b/webapp/src/app/modules/person-news/person-news.component.html @@ -4,79 +4,15 @@

Aktuelle Nachrichten zu dieser Person.

-
- - search - - - - - - Neueste zuerst - Älteste zuerst - - -
- -
- @if (loading) { -
- -
- } - - - - - - - - - - - - - - - - - - - -
Titel - {{ - article.maintitle || 'Kein Titel' - }} - Autor - {{ article.author || '-' }} - Datum - {{ formatDate(article.date) }} -
- - @if (!loading && articles.length === 0) { -
- @if (isSearching) { - Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. - } @else { - Keine Nachrichten gefunden. - } -
- } -
- - + + diff --git a/webapp/src/app/modules/person-news/person-news.component.scss b/webapp/src/app/modules/person-news/person-news.component.scss index 68a1899f..6cad4cdb 100644 --- a/webapp/src/app/modules/person-news/person-news.component.scss +++ b/webapp/src/app/modules/person-news/person-news.component.scss @@ -17,140 +17,8 @@ h6 { font-size: 14px; } -.news-toolbar { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 12px; - padding-top: 10px; - padding-bottom: 25px; -} - -.search-field { - max-width: 480px; -} - -::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { - display: none; -} - -::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { - height: 42px; - background: #fff; - border-radius: var(--sg-radius-sm); -} - -::ng-deep .news-toolbar .mat-mdc-form-field-infix { - min-height: unset; - height: 42px; - padding: 0; - display: flex; - align-items: center; -} - -::ng-deep .news-toolbar .mdc-notched-outline__leading, -::ng-deep .news-toolbar .mdc-notched-outline__notch, -::ng-deep .news-toolbar .mdc-notched-outline__trailing { - border-color: #d9e2f0; -} - -::ng-deep .news-toolbar input.mat-mdc-input-element { - color: var(--sg-text); - font-size: 14px; -} - -::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { - color: var(--sg-text-muted); - opacity: 1; - font-size: 14px; -} - -.sort-field { - width: 180px; -} - -.table-wrap { - position: relative; - overflow-x: auto; -} - -table { - width: 100%; - min-width: 600px; - border-collapse: separate; - border-spacing: 0 10px; - background: transparent; - box-shadow: none; -} - -.article-title { - display: inline-block; - max-width: 520px; - line-height: 1.35; - color: var(--sg-text); - font-size: 14px; - font-weight: 700; - text-decoration: none; - - &:hover { - color: var(--sg-text); - text-decoration: underline; - } -} - -.loading { - position: absolute; - inset: 0; - z-index: 1; - display: grid; - place-items: center; - background: rgba(255, 255, 255, 0.65); -} - -.empty-state { - padding: 28px; - text-align: center; - color: rgba(0, 0, 0, 0.6); - background: transparent; -} - -::ng-deep .mat-mdc-header-cell { - color: var(--sg-text-muted); - font-size: 12px; - font-weight: 700; -} - -::ng-deep .mat-mdc-row { - height: 72px; -} - -::ng-deep .mat-mdc-cell { - color: var(--sg-text); - border-bottom-color: var(--sg-border); - font-size: 13px; -} - -mat-paginator { - background: transparent; -} - -.table-footer { - display: flex; - align-items: center; - justify-content: space-between; - min-height: 66px; - padding: 0 22px 0 28px; - color: var(--sg-text-muted); - font-size: 13px; -} - @media (max-width: 600px) { .page { padding: 16px; } - - .table-footer { - align-items: stretch; - flex-direction: column; - } } diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index b0e6356b..f05391e9 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -1,33 +1,21 @@ import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, Router, RouterLink } from '@angular/router'; -import { MatIconModule } from '@angular/material/icon'; -import { MatSelectModule } from '@angular/material/select'; -import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; -import { MatTableModule } from '@angular/material/table'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatInputModule } from '@angular/material/input'; +import { ActivatedRoute, Router } from '@angular/router'; +import { PageEvent } from '@angular/material/paginator'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, distinctUntilChanged } from 'rxjs'; import { PaginationService } from '../../shared/services/pagination.service'; import { ResolverStateService } from '../../shared/services/resolver-state.service'; import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver'; +import { + NewsListComponent, + SortOrder, +} from '../../shared/ui/news-list/news-list.component'; @Component({ selector: 'app-person-news', - imports: [ - MatIconModule, - MatSelectModule, - MatFormFieldModule, - MatInputModule, - MatPaginatorModule, - MatProgressSpinnerModule, - MatTableModule, - ReactiveFormsModule, - RouterLink, - ], + imports: [ReactiveFormsModule, NewsListComponent], templateUrl: './person-news.component.html', styleUrl: './person-news.component.scss', }) @@ -40,11 +28,11 @@ export class PersonNewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); - displayedColumns = ['maintitle', 'author', 'date']; + displayedColumns = ['maintitle', 'relevance', 'date']; articles: NewsArticle[] = []; total = 0; - currentPageIndex = 0; - sortOrder: 'desc' | 'asc' = 'desc'; + currentPage = 1; + sortOrder: SortOrder = 'desc'; get loading(): boolean { return this.resolverStateService.isResolving(); @@ -75,7 +63,7 @@ export class PersonNewsComponent implements OnInit { const sortOrder = params.get('sortOrder'); const query = params.get('query') ?? ''; - this.currentPageIndex = page - 1; + this.currentPage = page; this.paginationService.selection = pageSize; this.sortOrder = sortOrder === 'asc' ? 'asc' : 'desc'; this.searchControl.setValue(query, { emitEvent: false }); @@ -103,30 +91,13 @@ export class PersonNewsComponent implements OnInit { }); } - onSortChange(order: 'desc' | 'asc'): void { + onSortChange(order: SortOrder): void { this.updateQueryParams({ sortOrder: order, page: 1, }); } - formatDate(dateStr?: string | null): string { - if (!dateStr) return '-'; - const date = new Date(dateStr); - if (isNaN(date.getTime())) return dateStr; - return new Intl.DateTimeFormat('de-DE').format(date); - } - - articleRange(): string { - if (this.total === 0) return 'Keine Nachrichten gefunden'; - const start = this.currentPageIndex * this.paginationService.selection + 1; - const end = Math.min( - start + this.paginationService.selection - 1, - this.total, - ); - return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; - } - private updateQueryParams( overrides: Record, ): void { diff --git a/webapp/src/app/resolvers/person-news.resolver.ts b/webapp/src/app/resolvers/person-news.resolver.ts index 9d361534..6c4bde29 100644 --- a/webapp/src/app/resolvers/person-news.resolver.ts +++ b/webapp/src/app/resolvers/person-news.resolver.ts @@ -11,6 +11,7 @@ export interface NewsArticle { maintitle?: string | null; author?: string | null; url?: string | null; + relevant?: boolean | null; } export interface NewsPage { diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.html b/webapp/src/app/shared/ui/news-list/news-list.component.html new file mode 100644 index 00000000..91f290ea --- /dev/null +++ b/webapp/src/app/shared/ui/news-list/news-list.component.html @@ -0,0 +1,103 @@ +
+ + search + + + + + + Neueste zuerst + Älteste zuerst + + +
+ +
+ @if (loading) { +
+ +
+ } + + + + + + + + + + + + + + + + + + @if (extraColumnId && extraColumnTemplate) { + + + + + } + + + +
Titel + {{ + article.maintitle || 'Kein Titel' + }} + Relevanz + @if (article.relevant === true) { + + check_circle + Relevant + + } @else if (article.relevant === false) { + + cancel + Nicht relevant + + } @else { + + help + Nicht bestimmt + + } + Datum + {{ formatDate(article.date) }} + {{ extraColumnHeader }} + +
+ + @if (!loading && articles.length === 0) { +
+ @if (isSearching) { + Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. + } @else { + Keine Nachrichten gefunden. + } +
+ } +
+ + diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.scss b/webapp/src/app/shared/ui/news-list/news-list.component.scss new file mode 100644 index 00000000..a8eafe84 --- /dev/null +++ b/webapp/src/app/shared/ui/news-list/news-list.component.scss @@ -0,0 +1,169 @@ +.news-toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + padding-top: 10px; + padding-bottom: 25px; +} + +.search-field { + max-width: 480px; +} + +::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { + display: none; +} + +::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .news-toolbar .mat-mdc-form-field-infix { + min-height: unset; + height: 42px; + padding: 0; + display: flex; + align-items: center; +} + +::ng-deep .news-toolbar .mdc-notched-outline__leading, +::ng-deep .news-toolbar .mdc-notched-outline__notch, +::ng-deep .news-toolbar .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +.sort-field { + width: 180px; +} + +.table-wrap { + position: relative; + overflow-x: auto; +} + +table { + width: 100%; + min-width: 600px; + border-collapse: separate; + border-spacing: 0 10px; + background: transparent; + box-shadow: none; +} + +.article-title { + display: inline-block; + max-width: 520px; + line-height: 1.35; + color: var(--sg-text); + font-size: 14px; + font-weight: 700; + text-decoration: none; + + &:hover { + color: var(--sg-text); + text-decoration: underline; + } +} + +.loading { + position: absolute; + inset: 0; + z-index: 1; + display: grid; + place-items: center; + background: rgba(255, 255, 255, 0.65); +} + +.empty-state { + padding: 28px; + text-align: center; + color: rgba(0, 0, 0, 0.6); + background: transparent; +} + +.relevance-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + font-weight: 600; + line-height: 1; + white-space: nowrap; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &.is-relevant { + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + } + + &.not-relevant { + background: var(--sg-surface-muted); + border: 1px solid #e2e2e2; + color: var(--sg-text-muted); + } + + &.undetermined { + background: #fff7e8; + border: 1px solid #ffd796; + color: #c67500; + } +} + +::ng-deep .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; +} + +::ng-deep .mat-mdc-row { + height: 72px; +} + +::ng-deep .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; +} + +mat-paginator { + background: transparent; +} + +.table-footer { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 66px; + padding: 0 22px 0 28px; + color: var(--sg-text-muted); + font-size: 13px; +} + +@media (max-width: 600px) { + .table-footer { + align-items: stretch; + flex-direction: column; + } +} diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.ts b/webapp/src/app/shared/ui/news-list/news-list.component.ts new file mode 100644 index 00000000..ceddb449 --- /dev/null +++ b/webapp/src/app/shared/ui/news-list/news-list.component.ts @@ -0,0 +1,95 @@ +import { + Component, + EventEmitter, + Input, + Output, + TemplateRef, + inject, +} from '@angular/core'; +import { NgTemplateOutlet } from '@angular/common'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { RouterLink } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTableModule } from '@angular/material/table'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; + +import { PaginationService } from '../../services/pagination.service'; + +export interface NewsArticleBase { + id: string; + date?: string | null; + maintitle?: string | null; + url?: string | null; + relevant?: boolean | null; +} + +export type SortOrder = 'desc' | 'asc'; + +@Component({ + selector: 'app-news-list', + imports: [ + MatIconModule, + MatSelectModule, + MatFormFieldModule, + MatInputModule, + MatPaginatorModule, + MatProgressSpinnerModule, + MatTableModule, + NgTemplateOutlet, + ReactiveFormsModule, + RouterLink, + ], + templateUrl: './news-list.component.html', + styleUrl: './news-list.component.scss', +}) +export class NewsListComponent { + readonly paginationService = inject(PaginationService); + + @Input({ required: true }) articles: NewsArticleBase[] = []; + @Input({ required: true }) displayedColumns: string[] = []; + @Input() total = 0; + @Input() loading = false; + @Input() currentPage = 1; + @Input() sortOrder: SortOrder = 'desc'; + @Input({ required: true }) searchControl!: FormControl; + + @Input() extraColumnId: string | null = null; + @Input() extraColumnHeader = ''; + @Input() extraColumnTemplate: TemplateRef<{ + $implicit: NewsArticleBase; + }> | null = null; + + @Output() sortChange = new EventEmitter(); + @Output() pageChange = new EventEmitter(); + + get isSearching(): boolean { + return this.searchControl.value.trim().length > 0; + } + + onSortChange(order: SortOrder): void { + this.sortChange.emit(order); + } + + onPage(event: PageEvent): void { + this.pageChange.emit(event); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE').format(date); + } + + articleRange(): string { + if (this.total === 0) return 'Keine Nachrichten gefunden'; + const pageSize = this.paginationService.selection; + const start = (this.currentPage - 1) * pageSize + 1; + const end = Math.min(start + this.articles.length - 1, this.total); + return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; + } +} From f752dc81fc678a43436977c750ad0c2943a1852f Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sun, 21 Jun 2026 20:43:29 +0200 Subject: [PATCH 03/81] IPC/CPC enrichment (Backend + Tests) --- service/src/main/inse/patents/ipc_lookup.py | 221 ++++++++++++++++++ .../main/inse/patents/ipc_search_client.py | 150 ++++++++++++ service/src/main/inse/patents/logic.py | 61 ++++- service/src/main/inse/patents/model.py | 15 +- .../src/main/inse/patents/test_ipc_lookup.py | 129 ++++++++++ .../src/main/inse/patents/test_ipc_model.py | 50 ++++ .../inse/patents/test_ipc_search_client.py | 67 ++++++ 7 files changed, 688 insertions(+), 5 deletions(-) create mode 100644 service/src/main/inse/patents/ipc_lookup.py create mode 100644 service/src/main/inse/patents/ipc_search_client.py create mode 100644 service/src/main/inse/patents/test_ipc_lookup.py create mode 100644 service/src/main/inse/patents/test_ipc_model.py create mode 100644 service/src/main/inse/patents/test_ipc_search_client.py diff --git a/service/src/main/inse/patents/ipc_lookup.py b/service/src/main/inse/patents/ipc_lookup.py new file mode 100644 index 00000000..9581ffe6 --- /dev/null +++ b/service/src/main/inse/patents/ipc_lookup.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Parse IPC/CPC symbols and assemble enriched classification objects. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass + +from . import model + +IPC_SYMBOL_RE = re.compile( + r"^(?P
[A-HY])" + r"(?P\d{2})" + r"(?P[A-Z])" + r"\s*" + r"(?:(?P\d+))?" + r"(?:/(?P\d+))?" + r"\s*$", + re.IGNORECASE, +) + +# EPO strings append metadata after the symbol, e.g. +# "G01S 5/02 20100101AFI20140127BHEP" +IPC_CODE_EXTRACT_RE = re.compile( + r"^([A-HY]\d{2}[A-Z]\s*\d+(?:/\d+)?)", + re.IGNORECASE, +) +# Legacy EPO spacing and trailing classification value, e.g. +# "C 07C 405/00 A" or "C 07D 317/20 B" +EPO_LEGACY_IPC_RE = re.compile( + r"^(?P
[A-HY])\s+" + r"(?P\d{2})\s*" + r"(?P[A-Z])\s+" + r"(?P\d+)" + r"(?:/(?P\d+))?" + r"(?:\s+(?P[A-Z]))?" + r"(?:\s|$)", + re.IGNORECASE, +) +IPC_SUBCLASS_ONLY_RE = re.compile( + r"^([A-HY]\d{2}[A-Z])(?:\s|$)", + re.IGNORECASE, +) + + +@dataclass(frozen=True) +class IpcHierarchyKeys: + symbol: str + normalized: str + section: str | None + ipc_class: str | None + subclass: str | None + main_group: str | None + subgroup: str | None + + +def extract_ipc_symbol(raw: str) -> str: + """ + Extract the classification code from a raw patent IPC string. + + Supports: + - 'G01S 5/02 20100101AFI20140127BHEP' + - 'C 07C 405/00 A' (legacy EPO spacing) + """ + cleaned = raw.strip() + if not cleaned: + return cleaned + + legacy = EPO_LEGACY_IPC_RE.match(cleaned) + if legacy: + section = legacy.group("section").upper() + class_num = legacy.group("class_num") + subclass_letter = legacy.group("subclass_letter").upper() + prefix = f"{section}{class_num}{subclass_letter}" + main_group = legacy.group("main_group") + subgroup = legacy.group("subgroup") + if subgroup is not None: + normalized = f"{prefix}{main_group}/{subgroup}" + else: + normalized = f"{prefix}{main_group}" + return display_ipc_symbol(normalized) + + match = IPC_CODE_EXTRACT_RE.match(cleaned) + if match: + return display_ipc_symbol(normalize_ipc_symbol(match.group(1))) + + match = IPC_SUBCLASS_ONLY_RE.match(cleaned) + if match: + return match.group(1).upper() + + return cleaned + + +def normalize_ipc_symbol(symbol: str) -> str: + """Remove whitespace, e.g. 'H01L 21/02' -> 'H01L21/02'.""" + return re.sub(r"\s+", "", symbol.strip().upper()) + + +def display_ipc_symbol(normalized: str) -> str: + """Format for display, e.g. 'H01L21/02' -> 'H01L 21/02'.""" + match = re.match(r"^([A-HY]\d{2}[A-Z])(\d+)(/\d+)$", normalized, re.IGNORECASE) + if match: + return f"{match.group(1)} {match.group(2)}{match.group(3)}" + match = re.match(r"^([A-HY]\d{2}[A-Z])$", normalized, re.IGNORECASE) + if match: + return match.group(1) + return normalized + + +def parse_ipc_symbol(symbol: str) -> IpcHierarchyKeys: + """Derive lookup keys for each hierarchy level from a patent IPC symbol.""" + cleaned = extract_ipc_symbol(symbol.strip()) + normalized = normalize_ipc_symbol(cleaned) + match = IPC_SYMBOL_RE.match(cleaned) or IPC_SYMBOL_RE.match(normalized) + + if not match: + return IpcHierarchyKeys( + symbol=cleaned, + normalized=normalized, + section=None, + ipc_class=None, + subclass=None, + main_group=None, + subgroup=None, + ) + + section = match.group("section").upper() + class_num = match.group("class_num") + subclass_letter = match.group("subclass_letter").upper() + subclass = f"{section}{class_num}{subclass_letter}" + ipc_class = f"{section}{class_num}" + + main_group_digits = match.group("main_group") + subgroup_digits = match.group("subgroup") + + main_group = None + subgroup = None + if main_group_digits: + base = f"{subclass}{main_group_digits}" + if subgroup_digits: + full = f"{base}/{subgroup_digits}" + if len(subgroup_digits) > 2: + subgroup = full + main_group = f"{base}/{subgroup_digits[:2]}" + else: + main_group = full + else: + main_group = base + + return IpcHierarchyKeys( + symbol=cleaned, + normalized=normalized, + section=section, + ipc_class=ipc_class, + subclass=subclass, + main_group=main_group, + subgroup=subgroup, + ) + + +def _format_level(number: str | None, name: str | None) -> str | None: + if not number or not name: + return None + label = display_ipc_symbol(number) + return f"{label} - {name.strip()}" + + +def _lookup_name(level_names: dict[str, str | None], *keys: str | None) -> str | None: + for key in keys: + if not key: + continue + if key in level_names and level_names[key]: + return level_names[key] + normalized = normalize_ipc_symbol(key) + if normalized in level_names and level_names[normalized]: + return level_names[normalized] + return None + + +def build_ipc_classification( + keys: IpcHierarchyKeys, + names: dict[str, dict[str, str | None]], +) -> model.IpcClassification: + """Combine parsed keys with lookup results from the ipc index.""" + section_name = _lookup_name(names.get("section", {}), keys.section) + class_name = _lookup_name(names.get("class", {}), keys.ipc_class) + subclass_name = _lookup_name(names.get("class", {}), keys.subclass) + group_name = _lookup_name( + names.get("group", {}), + keys.main_group, + keys.normalized, + ) + subgroup_name = _lookup_name( + names.get("subgroup", {}), + keys.subgroup, + keys.normalized, + ) + + if not subgroup_name and group_name and keys.subgroup: + subgroup_name = group_name + + main_group = None + if group_name: + main_group = _format_level(keys.main_group or keys.normalized, group_name) + + subgroup = None + if subgroup_name: + subgroup = _format_level(keys.subgroup or keys.normalized, subgroup_name) + + return model.IpcClassification( + symbol=keys.symbol, + section=_format_level(keys.section, section_name), + ipc_class=_format_level(keys.ipc_class, class_name) + if class_name + else (display_ipc_symbol(keys.ipc_class) if keys.ipc_class else None), + subclass=_format_level(keys.subclass, subclass_name), + main_group=main_group, + subgroup=subgroup, + ) diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py new file mode 100644 index 00000000..6ab6afa4 --- /dev/null +++ b/service/src/main/inse/patents/ipc_search_client.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + HTTP client for IPC/CPC classification lookups in the ipc Elasticsearch index. +""" +from __future__ import annotations + +from typing import Any + +import httpx + +from .. import config +from . import model +from .elastic_search_client import MissingApiKeyError +from .ipc_lookup import IpcHierarchyKeys +from .ipc_lookup import build_ipc_classification +from .ipc_lookup import parse_ipc_symbol + +IPC_INDEX = "ipc" + +_LEVELS: tuple[tuple[str, str, str], ...] = ( + ("section", "cpc_section_number", "cpc_section_name"), + ("class", "cpc_class_number", "cpc_class_name"), + ("group", "cpc_group_number", "cpc_group_name"), + ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), +) + + +class IpcSearchClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float = 30.0, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key + self.timeout = timeout + self.transport = transport + + def _headers(self) -> dict[str, str]: + if not self.api_key: + raise MissingApiKeyError("Patent Elasticsearch API key is not configured.") + return { + "Authorization": f"ApiKey {self.api_key}", + "Content-Type": "application/json", + } + + async def resolve_symbols(self, symbols: list[str]) -> dict[str, model.IpcClassification]: + """Resolve patent IPC symbols to enriched classification objects.""" + unique_symbols = list(dict.fromkeys(s.strip() for s in symbols if s and s.strip())) + if not unique_symbols: + return {} + + parsed = {symbol: parse_ipc_symbol(symbol) for symbol in unique_symbols} + names = await self._lookup_all_levels(parsed.values()) + + return { + symbol: build_ipc_classification(keys, names) + for symbol, keys in parsed.items() + } + + async def _lookup_all_levels( + self, + keys_list: list[IpcHierarchyKeys], + ) -> dict[str, dict[str, str | None]]: + symbols_by_level: dict[str, set[str]] = { + "section": set(), + "class": set(), + "group": set(), + "subgroup": set(), + } + + for keys in keys_list: + if keys.section: + symbols_by_level["section"].add(keys.section) + if keys.ipc_class: + symbols_by_level["class"].add(keys.ipc_class) + if keys.subclass: + symbols_by_level["class"].add(keys.subclass) + if keys.main_group: + symbols_by_level["group"].add(keys.main_group) + if keys.subgroup: + symbols_by_level["subgroup"].add(keys.subgroup) + if "/" in keys.normalized: + symbols_by_level["group"].add(keys.normalized) + symbols_by_level["subgroup"].add(keys.normalized) + + results: dict[str, dict[str, str | None]] = { + level: {} for level in symbols_by_level + } + + for level, number_field, name_field in _LEVELS: + level_symbols = {s for s in symbols_by_level[level] if s} + if level_symbols: + results[level] = await self._lookup_level(number_field, name_field, level_symbols) + + return results + + async def _lookup_level( + self, + number_field: str, + name_field: str, + symbols: set[str], + ) -> dict[str, str | None]: + if not symbols: + return {} + + payload: dict[str, Any] = { + "size": min(len(symbols), 100), + "query": { + "bool": { + "should": [ + {"bool": {"filter": [{"match_phrase": {number_field: symbol}}]}} + for symbol in sorted(symbols) + ], + "minimum_should_match": 1, + } + }, + "_source": [number_field, name_field], + } + + data = await self._search(payload) + found: dict[str, str | None] = {} + + for hit in data.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + number = source.get(number_field) + if not number: + continue + normalized_number = number.strip().upper() + found[normalized_number] = source.get(name_field) + found[number.strip()] = source.get(name_field) + + return found + + async def _search(self, payload: dict[str, Any]) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{IPC_INDEX}/_search", + headers=self._headers(), + json=payload, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index d5227bcc..ed9b270e 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -15,6 +15,8 @@ from ..models.openalex.author import Author from . import model from .elastic_search_client import MissingApiKeyError from .elastic_search_client import PatentSearchClient +from .ipc_search_client import IpcSearchClient +from .ipc_lookup import extract_ipc_symbol from .name_matching import name_matches logger = logging.getLogger(__name__) @@ -23,8 +25,10 @@ logger = logging.getLogger(__name__) async def get_patents_by_author_id( author_id: str, client: PatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, ) -> model.PatentsByAuthorResponse: search_client = client or PatentSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() author = _get_author(author_id) if not author: @@ -63,6 +67,8 @@ async def get_patents_by_author_id( if first_name and last_name: all_patents = _filter_patents_by_name(all_patents, first_name, last_name) + await _enrich_patents_classifications(all_patents, ipc_search_client) + return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, @@ -100,8 +106,8 @@ def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: kind=src.get("kind"), inventors=inventors if isinstance(inventors, list) else [inventors], assignees=applicants if isinstance(applicants, list) else [applicants], - ipc=ipc if isinstance(ipc, list) else [ipc], - cpc=cpc if isinstance(cpc, list) else [cpc], + ipc=_to_classification_strings(ipc), + cpc=_to_classification_strings(cpc), country=src.get("country", "EP"), )) return patents @@ -129,13 +135,60 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: status=src.get("status"), inventors=inventors if isinstance(inventors, list) else [inventors], assignees=assignees if isinstance(assignees, list) else [assignees], - ipc=ipc if isinstance(ipc, list) else [ipc], - cpc=cpc if isinstance(cpc, list) else [cpc], + ipc=_to_classification_strings(ipc), + cpc=_to_classification_strings(cpc), country=src.get("country", "US"), )) return patents +def _to_classification_strings(value) -> list[str]: + if not value: + return [] + items = value if isinstance(value, list) else [value] + return [str(item).strip() for item in items if item and str(item).strip()] + + +def _descriptions_for_raw_codes( + raw_codes: list[str], + resolved: dict[str, model.IpcClassification], +) -> list[model.IpcClassification]: + return [ + resolved[extract_ipc_symbol(raw)] + for raw in raw_codes + if extract_ipc_symbol(raw) in resolved + ] + + +async def _enrich_patents_classifications( + patents: list[model.PatentEntry], + ipc_client: IpcSearchClient, +) -> None: + symbols = list(dict.fromkeys( + extract_ipc_symbol(raw) + for patent in patents + for raw in (*patent.ipc, *patent.cpc) + )) + if not symbols: + return + + try: + resolved = await ipc_client.resolve_symbols(symbols) + except MissingApiKeyError: + logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.") + return + except httpx.HTTPError as exc: + logger.warning("Classification enrichment failed: %s", exc) + return + except Exception as exc: + logger.exception("Classification enrichment failed unexpectedly: %s", exc) + return + + for patent in patents: + patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved) + patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved) + + def _filter_patents_by_name( patents: list[model.PatentEntry], first_name: str, diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index dd622b70..f00a17c3 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -1,4 +1,15 @@ -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field + + +class IpcClassification(BaseModel): + symbol: str + section: str | None = None + ipc_class: str | None = Field(default=None, serialization_alias="class") + subclass: str | None = None + main_group: str | None = None + subgroup: str | None = None + + model_config = ConfigDict(populate_by_name=True) class PatentEntry(BaseModel): @@ -17,7 +28,9 @@ class PatentEntry(BaseModel): inventors: list[str] = Field(default_factory=list) assignees: list[str] = Field(default_factory=list) ipc: list[str] = Field(default_factory=list) + ipc_descriptions: list[IpcClassification] = Field(default_factory=list) cpc: list[str] = Field(default_factory=list) + cpc_descriptions: list[IpcClassification] = Field(default_factory=list) country: str | None = None diff --git a/service/src/main/inse/patents/test_ipc_lookup.py b/service/src/main/inse/patents/test_ipc_lookup.py new file mode 100644 index 00000000..941ff03b --- /dev/null +++ b/service/src/main/inse/patents/test_ipc_lookup.py @@ -0,0 +1,129 @@ +import pytest + +from inse.patents.ipc_lookup import ( + build_ipc_classification, + display_ipc_symbol, + extract_ipc_symbol, + normalize_ipc_symbol, + parse_ipc_symbol, +) +from inse.patents.model import IpcClassification + + +@pytest.mark.parametrize( + ("raw", "normalized"), + [ + ("H01L 21/02", "H01L21/02"), + ("h01l21/02", "H01L21/02"), + ("H04L 29/08", "H04L29/08"), + ], +) +def test_normalize_ipc_symbol(raw: str, normalized: str) -> None: + assert normalize_ipc_symbol(raw) == normalized + + +def test_display_ipc_symbol() -> None: + assert display_ipc_symbol("H01L21/02") == "H01L 21/02" + + +def test_parse_ipc_symbol_main_group() -> None: + keys = parse_ipc_symbol("H01L 21/02") + assert keys.section == "H" + assert keys.ipc_class == "H01" + assert keys.subclass == "H01L" + assert keys.main_group == "H01L21/02" + assert keys.subgroup is None + + +def test_parse_ipc_symbol_subgroup() -> None: + keys = parse_ipc_symbol("H01L 21/0262") + assert keys.main_group == "H01L21/02" + assert keys.subgroup == "H01L21/0262" + + +def test_extract_ipc_symbol_from_epo_string() -> None: + raw = "G01S 5/02 20100101AFI20140127BHEP" + assert extract_ipc_symbol(raw) == "G01S 5/02" + + +def test_extract_ipc_symbol_from_cpc_string() -> None: + raw = "A61B 5/0713 20130101AFI20140127BHEP" + assert extract_ipc_symbol(raw) == "A61B 5/0713" + + +def test_parse_ipc_symbol_from_epo_string() -> None: + keys = parse_ipc_symbol("G01S 5/02 20100101AFI20140127BHEP") + assert keys.symbol == "G01S 5/02" + assert keys.section == "G" + assert keys.subclass == "G01S" + assert keys.main_group == "G01S5/02" + + +def test_extract_ipc_symbol_subclass_only() -> None: + assert extract_ipc_symbol("H01L extra") == "H01L" + + +def test_build_ipc_classification_uses_index_names() -> None: + keys = parse_ipc_symbol("H01L 21/02") + names = { + "section": {"H": "ELECTRICITY"}, + "class": {"H01L": "SEMICONDUCTOR DEVICES"}, + "group": {"H01L21/02": "Manufacture or treatment of semiconductor devices"}, + "subgroup": {}, + } + + result = build_ipc_classification(keys, names) + + assert result.symbol == "H01L 21/02" + assert result.section == "H - ELECTRICITY" + assert result.subclass == "H01L - SEMICONDUCTOR DEVICES" + assert result.main_group == "H01L 21/02 - Manufacture or treatment of semiconductor devices" + + +def test_extract_ipc_symbol_from_legacy_epo_string() -> None: + assert extract_ipc_symbol("C 07C 405/00 A") == "C07C 405/00" + assert extract_ipc_symbol("C 07D 317/20 B") == "C07D 317/20" + + +def test_parse_ipc_symbol_from_legacy_epo_string() -> None: + keys = parse_ipc_symbol("C 07D 319/06 B") + assert keys.symbol == "C07D 319/06" + assert keys.section == "C" + assert keys.subclass == "C07D" + assert keys.main_group == "C07D319/06" + + +def test_build_ipc_classification_uses_subgroup_when_only_subgroup_indexed() -> None: + keys = parse_ipc_symbol("G02B 6/42") + names = { + "section": {"G": "PHYSICS"}, + "class": {"G02B": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS"}, + "group": {}, + "subgroup": { + "G02B6/42": "Coupling light guides with opto-electronic elements", + }, + } + + result = build_ipc_classification(keys, names) + + assert result.main_group is None + assert result.subgroup == ( + "G02B 6/42 - Coupling light guides with opto-electronic elements" + ) + + +def test_build_ipc_classification_omits_levels_without_index_names() -> None: + keys = parse_ipc_symbol("G02B 6/44") + result = build_ipc_classification(keys, {}) + + assert result.symbol == "G02B 6/44" + assert result.section is None + assert result.main_group is None + assert result.subgroup is None + + +def test_build_ipc_classification_falls_back_to_symbol_only() -> None: + keys = parse_ipc_symbol("INVALID") + result = build_ipc_classification(keys, {}) + + assert result == IpcClassification(symbol="INVALID") diff --git a/service/src/main/inse/patents/test_ipc_model.py b/service/src/main/inse/patents/test_ipc_model.py new file mode 100644 index 00000000..5b942cba --- /dev/null +++ b/service/src/main/inse/patents/test_ipc_model.py @@ -0,0 +1,50 @@ +import pytest + +from inse.patents import model + + +def test_patent_entry_keeps_raw_ipc_and_separate_descriptions() -> None: + entry = model.PatentEntry( + patent_id="US123456", + source="USPTO", + ipc=["H01L 21/02 20100101AFI20140127BHEP"], + ipc_descriptions=[ + model.IpcClassification( + symbol="H01L 21/02", + section="H - ELECTRICITY", + subclass="H01L - SEMICONDUCTOR DEVICES", + ) + ], + ) + + assert entry.ipc == ["H01L 21/02 20100101AFI20140127BHEP"] + assert len(entry.ipc_descriptions) == 1 + assert entry.ipc_descriptions[0].symbol == "H01L 21/02" + + +def test_patent_entry_ipc_defaults_to_empty_lists() -> None: + entry = model.PatentEntry(patent_id="EP1", source="EPO") + + assert entry.ipc == [] + assert entry.ipc_descriptions == [] + assert entry.cpc == [] + assert entry.cpc_descriptions == [] + + +def test_patent_entry_keeps_raw_cpc_and_separate_descriptions() -> None: + entry = model.PatentEntry( + patent_id="US123456", + source="USPTO", + cpc=["A61B 5/0713 20130101AFI20140127BHEP"], + cpc_descriptions=[ + model.IpcClassification( + symbol="A61B 5/0713", + section="A - HUMAN NECESSITIES", + subclass="A61B - DIAGNOSIS", + ) + ], + ) + + assert entry.cpc == ["A61B 5/0713 20130101AFI20140127BHEP"] + assert len(entry.cpc_descriptions) == 1 + assert entry.cpc_descriptions[0].symbol == "A61B 5/0713" diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py new file mode 100644 index 00000000..4bf064bd --- /dev/null +++ b/service/src/main/inse/patents/test_ipc_search_client.py @@ -0,0 +1,67 @@ +import httpx +import pytest + +from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_resolve_symbols_posts_to_ipc_index(): + requests: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request.url.path) + return httpx.Response( + 200, + json={ + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + }, + { + "_source": { + "cpc_class_number": "H01L", + "cpc_class_name": "SEMICONDUCTOR DEVICES", + } + }, + { + "_source": { + "cpc_group_number": "H01L21/02", + "cpc_group_name": "Manufacture or treatment of semiconductor devices", + } + }, + ] + } + }, + ) + + transport = httpx.MockTransport(handler) + client = IpcSearchClient(api_key="test-key", transport=transport) + + result = await client.resolve_symbols(["H01L 21/02"]) + + assert len(requests) >= 1 + assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests) + assert "H01L 21/02" in result + assert result["H01L 21/02"].section == "H - ELECTRICITY" + assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" + + +@pytest.mark.anyio +async def test_resolve_symbols_does_not_crash_for_subclass_codes(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"hits": {"hits": []}}) + + client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler)) + result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) + + assert "A61J 1/14" in result + assert "C07D 319/06" in result From 7a47211c97681b71729adbb4ea11530c4ae69d93 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sun, 21 Jun 2026 20:44:33 +0200 Subject: [PATCH 04/81] Patent classification UI (Frontend) --- webapp/src/app/api/api/patents.service.ts | 11 ++ .../person-patents.component.html | 96 ++++++++++- .../person-patents.component.scss | 126 ++++++++++++++ .../person-patents.component.ts | 158 +++++++++++++++++- 4 files changed, 388 insertions(+), 3 deletions(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 33d7412b..4ec5192e 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -21,6 +21,15 @@ import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; +export interface IpcClassification { + symbol: string; + section: string | null; + class: string | null; + subclass: string | null; + main_group: string | null; + subgroup: string | null; +} + export interface PatentEntry { patent_id: string; source: string; @@ -37,7 +46,9 @@ export interface PatentEntry { inventors: string[]; assignees: string[]; ipc: string[]; + ipc_descriptions: IpcClassification[]; cpc: string[]; + cpc_descriptions: IpcClassification[]; country: string | null; } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index db0c6bbb..fe51cb23 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -45,7 +45,53 @@ } - @if (selectedPatent.ipc.length > 0) { + @if ((selectedPatent.ipc_descriptions?.length ?? 0) > 0) { +
+

Klassifikation (IPC)

+
+ @for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) { +
+
+
+ @for (symbol of card.symbols; track symbol) { + {{ symbol }} + } +
+
+ {{ card.system }} + {{ card.levelLabel }} +
+
+ + @if (card.primaryDescription) { +

+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }} +

+ @if (isLongDescription(card.primaryDescription)) { + + } + } + + @if (card.hierarchy.length > 0) { +
+ @for (row of card.hierarchy; track row.label) { +
+
{{ row.label }}
+
{{ row.value }}
+
+ } +
+ } +
+ } +
+
+ } @else if (selectedPatent.ipc.length > 0) {

Klassifikation (IPC)

    @@ -56,7 +102,53 @@
} - @if (selectedPatent.cpc.length > 0) { + @if ((selectedPatent.cpc_descriptions?.length ?? 0) > 0) { +
+

Klassifikation (CPC)

+
+ @for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) { +
+
+
+ @for (symbol of card.symbols; track symbol) { + {{ symbol }} + } +
+
+ {{ card.system }} + {{ card.levelLabel }} +
+
+ + @if (card.primaryDescription) { +

+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }} +

+ @if (isLongDescription(card.primaryDescription)) { + + } + } + + @if (card.hierarchy.length > 0) { +
+ @for (row of card.hierarchy; track row.label) { +
+
{{ row.label }}
+
{{ row.value }}
+
+ } +
+ } +
+ } +
+
+ } @else if (selectedPatent.cpc.length > 0) {

Klassifikation (CPC)

    diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index befd90ad..9bce06a7 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -309,6 +309,132 @@ line-height: 1.3; } +.classification-section { + &--ipc .classification-card { + background: #f0f6ff; + border-color: #bfdbfe; + } + + &--ipc .classification-badge--system { + background: #dbeafe; + color: #1d4ed8; + } + + &--cpc .classification-card { + background: #f0fdf4; + border-color: #bbf7d0; + } + + &--cpc .classification-badge--system { + background: #dcfce7; + color: #15803d; + } +} + +.classification-cards { + display: flex; + flex-direction: column; + gap: 10px; +} + +.classification-card { + padding: 12px 14px; + border-radius: 10px; + border: 1px solid #dbeafe; +} + +.classification-card__header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; +} + +.classification-card__codes { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.classification-card__badges { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.classification-code { + font-size: 0.9rem; + font-weight: 700; + color: #0f172a; +} + +.classification-badge { + display: inline-flex; + align-items: center; + padding: 2px 8px; + border-radius: 999px; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.02em; + text-transform: uppercase; +} + +.classification-badge--level { + background: #e2e8f0; + color: #475569; +} + +.classification-summary { + margin: 10px 0 0; + font-size: 0.84rem; + line-height: 1.5; + color: #334155; +} + +.classification-toggle { + margin-top: 6px; + padding: 0; + border: 0; + background: none; + color: #2563eb; + font-size: 0.78rem; + cursor: pointer; + + &:hover { + text-decoration: underline; + } +} + +.classification-hierarchy { + margin: 10px 0 0; + padding-top: 10px; + border-top: 1px solid rgba(15, 23, 42, 0.08); +} + +.classification-hierarchy__row { + display: grid; + grid-template-columns: 88px 1fr; + gap: 8px; + margin-bottom: 6px; + + dt { + margin: 0; + font-size: 0.72rem; + font-weight: 700; + color: #64748b; + text-transform: uppercase; + letter-spacing: 0.03em; + } + + dd { + margin: 0; + font-size: 0.8rem; + line-height: 1.45; + color: #334155; + } +} + .pagination { display: flex; align-items: center; diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index 4c71be01..fc3f86bb 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,10 +1,22 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { PatentsService, PatentEntry } from '../../api/api/patents.service'; +import { PatentsService, PatentEntry, IpcClassification } from '../../api/api/patents.service'; type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; +type ClassificationSystem = 'IPC' | 'CPC'; + +interface ClassificationCard { + key: string; + symbols: string[]; + system: ClassificationSystem; + levelLabel: string; + primaryDescription: string | null; + hierarchy: { label: string; value: string }[]; +} + +const DESCRIPTION_PREVIEW_LENGTH = 140; @Component({ selector: 'app-person-patents', @@ -31,6 +43,7 @@ export class PersonPatentsComponent implements OnInit { selectedPage = 1; readonly pageSize = 10; + private expandedClassificationKeys = new Set(); ngOnInit(): void { this.route.parent?.paramMap.subscribe((params) => { @@ -81,11 +94,13 @@ export class PersonPatentsComponent implements OnInit { selectPatent(patent: PatentEntry): void { this.selectedPatent = patent; this.showDetail = false; + this.expandedClassificationKeys.clear(); this.updateQueryParams(); } openDetail(): void { this.showDetail = true; + this.expandedClassificationKeys.clear(); } private applyFilter(): void { @@ -158,4 +173,145 @@ export class PersonPatentsComponent implements OnInit { getUsptoCount(): number { return this.patents.filter((p) => p.source === 'USPTO').length; } + + getClassificationCards( + entries: IpcClassification[] | undefined, + system: ClassificationSystem, + ): ClassificationCard[] { + if (!entries?.length) { + return []; + } + + const merged = new Map(); + + for (const entry of entries) { + const card = this.buildClassificationCard(entry, system); + const mergeKey = + card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key; + + const existing = merged.get(mergeKey); + if (existing) { + for (const symbol of card.symbols) { + if (!existing.symbols.includes(symbol)) { + existing.symbols.push(symbol); + } + } + continue; + } + + merged.set(mergeKey, card); + } + + return [...merged.values()]; + } + + toggleClassificationExpanded(key: string): void { + if (this.expandedClassificationKeys.has(key)) { + this.expandedClassificationKeys.delete(key); + return; + } + this.expandedClassificationKeys.add(key); + } + + isClassificationExpanded(key: string): boolean { + return this.expandedClassificationKeys.has(key); + } + + isLongDescription(text: string | null): boolean { + return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH; + } + + getDescriptionPreview(text: string | null): string { + if (!text) { + return ''; + } + if (text.length <= DESCRIPTION_PREVIEW_LENGTH) { + return text; + } + return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`; + } + + private buildClassificationCard( + entry: IpcClassification, + system: ClassificationSystem, + ): ClassificationCard { + const level = this.getClassificationLevel(entry); + const primaryDescription = this.extractDescriptionText(entry[level.field]); + + return { + key: `${system}-${entry.symbol}`, + symbols: [entry.symbol], + system, + levelLabel: level.label, + primaryDescription, + hierarchy: this.buildHierarchyRows(entry, primaryDescription), + }; + } + + private getClassificationLevel(entry: IpcClassification): { + label: string; + field: keyof IpcClassification; + } { + if (entry.subgroup) { + return { label: 'Untergruppe', field: 'subgroup' }; + } + if (entry.main_group) { + return { label: 'Hauptgruppe', field: 'main_group' }; + } + if (entry.subclass) { + return { label: 'Unterklasse', field: 'subclass' }; + } + if (entry.section) { + return { label: 'Sektion', field: 'section' }; + } + return { label: 'Code', field: 'symbol' }; + } + + private buildHierarchyRows( + entry: IpcClassification, + primaryDescription: string | null, + ): { label: string; value: string }[] { + const rows: { label: string; value: string }[] = []; + const seen = new Set(); + + const addRow = (label: string, raw: string | null) => { + const value = this.extractDescriptionText(raw); + if (!value) { + return; + } + const normalized = value.toLocaleLowerCase('en'); + if (seen.has(normalized) || normalized === primaryDescription?.toLocaleLowerCase('en')) { + return; + } + seen.add(normalized); + rows.push({ label, value }); + }; + + addRow('Sektion', entry.section); + addRow('Klasse', entry.class); + addRow('Unterklasse', entry.subclass); + + return rows; + } + + private extractDescriptionText(value: string | null | undefined): string | null { + if (!value?.trim()) { + return null; + } + + const text = value.includes(' - ') ? value.split(' - ').slice(1).join(' - ').trim() : value.trim(); + if (!text) { + return null; + } + + const firstSentence = text.split(/[;|]/)[0]?.trim() ?? text; + return this.normalizeDescriptionCase(firstSentence); + } + + private normalizeDescriptionCase(text: string): string { + if (text !== text.toUpperCase()) { + return text; + } + return text.charAt(0) + text.slice(1).toLowerCase(); + } } From 9f596e0e89901b7ea6ead092db94c4da905e01a9 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 21 Jun 2026 22:48:51 +0200 Subject: [PATCH 05/81] added URI encoding for single bund project requests --- service/src/main/inse/projects/projects_search_client.py | 8 +++++--- webapp/src/app/modules/projects/projects.component.ts | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index a53c2f1f..0a0653b2 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -3,7 +3,7 @@ import logging from typing import Any, Dict, List, Optional, Set, Tuple import httpx - +import urllib from inse.config import get_settings from inse.models.bund_project import BundProject from inse.projects.model import ( @@ -193,7 +193,7 @@ def _complete_response_to_bund_project_page( def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: - """Fetches the details of a single Bund project based on its project ID. + """Decodes project_id and fetches the details of a single Bund project based on its project ID. Args: project_id (str): The ID of the project to fetch. @@ -201,7 +201,9 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: Returns: Optional[BundProjectDetails]: The details of the project if found, otherwise None. """ - query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}} + + decoded_id = urllib.parse.unquote(project_id) + query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}} response = elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts index 4fc6f46d..78563c74 100644 --- a/webapp/src/app/modules/projects/projects.component.ts +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -118,7 +118,8 @@ export class ProjectsComponent { getDetaiLink(fundingProject: FundingProject): string | null { if (fundingProject.type === 'bund') { - return '/projects/bund/' + fundingProject.id; + const encodedId = encodeURIComponent(fundingProject.id) + return '/projects/bund/' + encodedId; } else if (fundingProject.type === 'dfg') { return '/projects/dfg/' + fundingProject.id; } else { From 42cf5d7897e5052d28b74fdb8cfbb0553158635a Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 00:04:02 +0200 Subject: [PATCH 06/81] moved project details pages from /person-projects to /projects --- .../bund-details/bund-details.component.html | 0 .../bund-details/bund-details.component.scss | 0 .../bund-details/bund-details.component.ts | 0 .../dfg-details/dfg-details.component.html | 0 .../dfg-details/dfg-details.component.scss | 0 .../dfg-details/dfg-details.component.ts | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename webapp/src/app/modules/{person-projects => projects}/bund-details/bund-details.component.html (100%) rename webapp/src/app/modules/{person-projects => projects}/bund-details/bund-details.component.scss (100%) rename webapp/src/app/modules/{person-projects => projects}/bund-details/bund-details.component.ts (100%) rename webapp/src/app/modules/{person-projects => projects}/dfg-details/dfg-details.component.html (100%) rename webapp/src/app/modules/{person-projects => projects}/dfg-details/dfg-details.component.scss (100%) rename webapp/src/app/modules/{person-projects => projects}/dfg-details/dfg-details.component.ts (100%) diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.html b/webapp/src/app/modules/projects/bund-details/bund-details.component.html similarity index 100% rename from webapp/src/app/modules/person-projects/bund-details/bund-details.component.html rename to webapp/src/app/modules/projects/bund-details/bund-details.component.html diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss b/webapp/src/app/modules/projects/bund-details/bund-details.component.scss similarity index 100% rename from webapp/src/app/modules/person-projects/bund-details/bund-details.component.scss rename to webapp/src/app/modules/projects/bund-details/bund-details.component.scss diff --git a/webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts similarity index 100% rename from webapp/src/app/modules/person-projects/bund-details/bund-details.component.ts rename to webapp/src/app/modules/projects/bund-details/bund-details.component.ts diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html similarity index 100% rename from webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.html rename to webapp/src/app/modules/projects/dfg-details/dfg-details.component.html diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss similarity index 100% rename from webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.scss rename to webapp/src/app/modules/projects/dfg-details/dfg-details.component.scss diff --git a/webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts similarity index 100% rename from webapp/src/app/modules/person-projects/dfg-details/dfg-details.component.ts rename to webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts From 299c7c3d9bf30fd3332d9bdd9d95eb327a306ca1 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 00:04:20 +0200 Subject: [PATCH 07/81] added EU single project resolver --- .../app/resolvers/eu-single-project-resolver.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 webapp/src/app/resolvers/eu-single-project-resolver.ts diff --git a/webapp/src/app/resolvers/eu-single-project-resolver.ts b/webapp/src/app/resolvers/eu-single-project-resolver.ts new file mode 100644 index 00000000..4bb3eb86 --- /dev/null +++ b/webapp/src/app/resolvers/eu-single-project-resolver.ts @@ -0,0 +1,16 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { ProjectsService } from '../api/api/projects.service'; +import { CordisEuProject } from '../api'; + +export const euSingleProjectResolver: ResolveFn = ( + route, + state, +) => { + const projectsService = inject(ProjectsService); + const projectId = route.paramMap.get('id'); + if (!projectId) { + throw new Error('EU Cordis Project ID is required'); + } + return projectsService.getSingleEuCordisProject(projectId); +}; From 15bfdf55bcb9550c1b2aab4b09213328e2b1da48 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 00:05:06 +0200 Subject: [PATCH 08/81] added signle EU project details page component to frontend --- webapp/src/app/api/api/projects.service.ts | 58 ++ webapp/src/app/app.routes.ts | 17 +- .../eu-details.component.html | 296 +++++++++ .../eu-details.component.scss | 619 ++++++++++++++++++ .../eu-cordis-details/eu-details.component.ts | 180 +++++ .../modules/projects/projects.component.ts | 5 +- 6 files changed, 1171 insertions(+), 4 deletions(-) create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 9edfb7fe..9514c05f 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -21,6 +21,8 @@ import { BundProjectDetails } from '../model/bundProjectDetails'; // @ts-ignore import { BundProjectPage } from '../model/bundProjectPage'; // @ts-ignore +import { CordisEuProject } from '../model/cordisEuProject'; +// @ts-ignore import { CordisEuProjectPage } from '../model/cordisEuProjectPage'; // @ts-ignore import { DfgProjectDetails } from '../model/dfgProjectDetails'; @@ -425,6 +427,62 @@ export class ProjectsService extends BaseService { ); } + /** + * Get a single EU Cordis project. + * Returns a single EU Cordis project based on its ID. + * @endpoint get /api/projects/eu/{id} + * @param id The ID of the EU Cordis project to retrieve. + * @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 getSingleEuCordisProject(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getSingleEuCordisProject(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getSingleEuCordisProject(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getSingleEuCordisProject(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 getSingleEuCordisProject.'); + } + + 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/projects/eu/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + 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 bund projects. * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 5bf5ab58..9d7bfba8 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -16,6 +16,7 @@ import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page. import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver'; import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; +import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'; export const routes: Routes = [ { @@ -111,7 +112,7 @@ export const routes: Routes = [ canActivate: [userGuard], pathMatch: 'full', loadComponent: () => - import('./modules/person-projects/dfg-details/dfg-details.component').then( + import('./modules/projects/dfg-details/dfg-details.component').then( (mod) => mod.DfgDetailsComponent, ), resolve: { @@ -123,12 +124,24 @@ export const routes: Routes = [ canActivate: [userGuard], pathMatch: 'full', loadComponent: () => - import('./modules/person-projects/bund-details/bund-details.component').then( + import('./modules/projects/bund-details/bund-details.component').then( (mod) => mod.BundDetailsComponent, ), resolve: { bundSingleProject: bundSingleProjectResolver, }, + }, + { + path: 'projects/eu/:id', + canActivate: [userGuard], + pathMatch: 'full', + loadComponent: () => + import('./modules/projects/eu-cordis-details/eu-details.component').then( + (mod) => mod.EuDetailsComponent, + ), + resolve: { + euSingleProject: euSingleProjectResolver, + }, }, { path: 'person/:id', diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html new file mode 100644 index 00000000..2f30b6a0 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -0,0 +1,296 @@ +
    + + + @if (euProject) { +
    +
    +
    + EU Projekt + ID: {{ euProject.id }} + @if (euProject.rcn) { + RCN: {{ euProject.rcn }} + } + @if (euProject.acronym) { + {{ euProject.acronym }} + } +
    +

    {{ euProject.title || 'Ohne Titel' }}

    + @if (euProject.frameworkProgramme) { +

    + Rahmenprogramm: + + {{ getFrameworkDisplay(euProject.frameworkProgramme) }} + +

    + } +
    + @if (euProject.status) { +
    + circle + {{ getStatusDisplay(euProject.status) }} +
    + } + @if (euProject.fundingScheme) { +
    + assignment + {{ getFundingSchemeDisplay(euProject.fundingScheme) }} +
    + } + @if (euProject.grantDoi) { + + link + DOI: {{ euProject.grantDoi }} + + } +
    +
    + +
    +
    + calendar_today +
    + {{ euProject.startDate || 'N/A' }} + Startdatum +
    +
    +
    + event_busy +
    + {{ euProject.endDate || 'N/A' }} + Enddatum +
    +
    +
    + access_time +
    + {{ getFundingStatus(euProject.endDate) }} + Status +
    +
    + @if (euProject.ecMaxContribution) { +
    + euro_symbol +
    + {{ formatCurrency(euProject.ecMaxContribution) }} + EU-Beitrag +
    +
    + } + @if (euProject.totalCost) { +
    + attach_money +
    + {{ formatCurrency(euProject.totalCost) }} + Gesamtkosten +
    +
    + } + @if (euProject.masterCall) { +
    + call_split +
    + {{ euProject.masterCall }} + Master Call +
    +
    + } +
    +
    + + @if (euProject.objective) { + +
    + description +

    Projektziel

    +
    +

    {{ euProject.objective }}

    +
    + } + +
    +
    + + @if (euProject.topics) { + +
    + topic +

    Themen

    + {{ getFormattedTopics(euProject.topics).length }} +
    +
    + @for (topic of getFormattedTopics(euProject.topics); track topic) { +
    + {{ topic }} + search +
    + } +
    +
    + } + + + @if (getKeywords(euProject.keywords).length > 0) { + +
    + tag +

    Schlüsselwörter

    + {{ getKeywords(euProject.keywords).length }} +
    +
    + @for (keyword of getKeywords(euProject.keywords); track keyword) { +
    + {{ keyword }} + search +
    + } +
    +
    + } +
    + + +
    + } @else { +
    +
    + error_outline +

    EU Projekt nicht gefunden.

    +
    +
    + } +
    \ No newline at end of file diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss new file mode 100644 index 00000000..4a26295b --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -0,0 +1,619 @@ +// Complete SCSS with all styles + +.detail-page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +.page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + margin-bottom: 24px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 8px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + cursor: pointer; + font-size: 14px; + transition: all 0.2s; +} + +.back-link:hover { + background: #f5f7fa; + border-color: #b8c5d6; +} + +.back-link mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} + +.breadcrumb { + display: flex; + align-items: center; + gap: 6px; + color: var(--sg-text-muted); + font-size: 13px; +} + +.breadcrumb mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.breadcrumb span:last-child { + color: var(--sg-text); + font-weight: 500; +} + +.project-hero { + background: #f8fafc; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-md); + padding: 28px 32px; + margin-bottom: 28px; +} + +.hero-content { + margin-bottom: 24px; +} + +.eyebrow { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 12px; + flex-wrap: wrap; +} + +.project-badge { + display: inline-block; + padding: 4px 12px; + background: #e8edf5; + color: var(--sg-text); + border-radius: var(--sg-radius-sm); + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.project-id { + color: var(--sg-text-muted); + font-size: 13px; +} + +.project-rcn { + display: inline-block; + padding: 4px 10px; + background: #e8f0fe; + color: #1a73e8; + border-radius: var(--sg-radius-sm); + font-size: 12px; + font-weight: 500; +} + +.project-acronym { + display: inline-block; + padding: 4px 10px; + background: #fff3e0; + color: #e65100; + border-radius: var(--sg-radius-sm); + font-size: 12px; + font-weight: 600; +} + +h1 { + margin: 0 0 8px; + font-size: 26px; + line-height: 1.3; + font-weight: 700; + color: var(--sg-text); +} + +.project-framework { + margin: 0 0 16px; + color: var(--sg-text-muted); + font-size: 14px; +} + +.framework-tag { + display: inline-block; + padding: 2px 10px; + background: #e8edf5; + border-radius: var(--sg-radius-sm); + color: var(--sg-text); + font-weight: 500; + cursor: pointer; + transition: all 0.2s; +} + +.framework-tag:hover { + background: #d5dde8; +} + +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.status-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 14px; + border-radius: var(--sg-radius-sm); + color: #fff; + font-size: 13px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; +} + +.status-badge:hover { + transform: translateY(-1px); + box-shadow: 0 2px 8px rgba(0,0,0,0.15); +} + +.status-badge mat-icon { + width: 16px; + height: 16px; + font-size: 16px; +} + +.scheme-info { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 6px 14px; + background: #fff; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + color: var(--sg-text); + font-size: 13px; + cursor: pointer; + transition: all 0.2s; +} + +.scheme-info:hover { + background: #f5f7fa; + border-color: #b8c5d6; +} + +.scheme-info mat-icon { + color: var(--sg-text-muted); + width: 18px; + height: 18px; + font-size: 18px; +} + +.doi-link { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 14px; + background: #e8f0fe; + border: 1px solid #c5d8f0; + border-radius: var(--sg-radius-sm); + color: #1a73e8; + text-decoration: none; + font-size: 13px; + transition: all 0.2s; +} + +.doi-link:hover { + background: #d5e3fa; +} + +.doi-link mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 16px; + padding-top: 20px; + border-top: 1px solid #d9e2f0; +} + +.metric-item { + display: flex; + align-items: center; + gap: 12px; +} + +.metric-item mat-icon { + color: var(--sg-text-muted); + width: 24px; + height: 24px; + font-size: 24px; +} + +.metric-content { + display: flex; + flex-direction: column; +} + +.metric-content strong { + font-size: 15px; + color: var(--sg-text); + line-height: 1.3; +} + +.metric-content span { + font-size: 12px; + color: var(--sg-text-muted); +} + +.card { + margin-bottom: 24px; + border-color: #d9e2f0 !important; + border-radius: var(--sg-radius-md) !important; +} + +.card ::ng-deep .mat-mdc-card-content { + padding: 0; +} + +.section-header { + display: flex; + align-items: center; + gap: 10px; + padding: 16px 20px 12px; + border-bottom: 1px solid #f0f2f5; +} + +.section-header mat-icon { + color: var(--sg-text-muted); + width: 22px; + height: 22px; + font-size: 22px; +} + +.section-header h2 { + margin: 0; + font-size: 16px; + font-weight: 600; + color: var(--sg-text); +} + +.count-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 24px; + height: 24px; + padding: 0 8px; + margin-left: auto; + background: #e8edf5; + border-radius: 12px; + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 500; +} + +.description-text { + padding: 16px 20px 20px; + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.6; +} + +.content-grid { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 24px; +} + +.main-content { + display: flex; + flex-direction: column; + gap: 24px; +} + +.sidebar { + display: flex; + flex-direction: column; + gap: 24px; +} + +.topics-grid { + display: grid; + grid-template-columns: 1fr; + gap: 10px; + padding: 16px 20px 20px; +} + +.topic-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + cursor: pointer; + transition: all 0.2s; +} + +.topic-item:hover { + background: #f8fafc; + border-color: #b8c5d6; + transform: translateY(-1px); +} + +.topic-value { + color: var(--sg-text); + font-size: 13px; + word-break: break-word; +} + +.topic-item .search-icon { + color: var(--sg-text-muted); + width: 18px; + height: 18px; + font-size: 18px; + opacity: 0; + transition: opacity 0.2s; +} + +.topic-item:hover .search-icon { + opacity: 1; +} + +.keywords-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; + padding: 16px 20px 20px; +} + +.keyword-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + cursor: pointer; + transition: all 0.2s; + position: relative; +} + +.keyword-item:hover { + background: #f8fafc; + border-color: #b8c5d6; + transform: translateY(-1px); +} + +.keyword-value { + color: var(--sg-text); + font-size: 13px; + word-break: break-word; +} + +.keyword-item .search-icon { + color: var(--sg-text-muted); + width: 16px; + height: 16px; + font-size: 16px; + opacity: 0; + transition: opacity 0.2s; +} + +.keyword-item:hover .search-icon { + opacity: 1; +} + +.details-list { + margin: 0; + padding: 16px 20px 20px; +} + +.detail-row { + display: grid; + grid-template-columns: 140px 1fr; + gap: 12px; + padding: 8px 0; + border-bottom: 1px solid #f0f2f5; +} + +.detail-row:last-child { + border-bottom: none; +} + +.detail-row dt { + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 500; +} + +.detail-row dd { + margin: 0; + color: var(--sg-text); + font-size: 13px; + word-break: break-word; + display: flex; + align-items: center; + gap: 6px; +} + +.detail-row dd.clickable { + cursor: pointer; + transition: color 0.2s; +} + +.detail-row dd.clickable:hover { + color: var(--sg-primary, #0066cc); +} + +.detail-row dd.clickable:hover .search-icon { + opacity: 1; +} + +.search-icon { + width: 16px; + height: 16px; + font-size: 16px; + opacity: 0; + transition: opacity 0.2s; + color: var(--sg-text-muted); +} + +.detail-row dd:hover .search-icon { + opacity: 1; +} + +.status-indicator { + display: inline-block; + padding: 2px 10px; + border-radius: var(--sg-radius-sm); + color: #fff; + font-size: 12px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; +} + +.status-indicator:hover { + transform: scale(1.05); +} + +.external-link { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--sg-primary, #0066cc); + text-decoration: none; + word-break: break-all; +} + +.external-link:hover { + text-decoration: underline; +} + +.external-link .external-icon { + width: 16px; + height: 16px; + font-size: 16px; +} + +.error-container { + display: flex; + align-items: center; + justify-content: center; + min-height: 400px; +} + +.error-state { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + color: var(--sg-text-muted); +} + +.error-state mat-icon { + width: 48px; + height: 48px; + font-size: 48px; + color: #e74c3c; +} + +.error-state p { + margin: 0; + font-size: 16px; +} + +// Utility function for date formatting +.format-date { + // Handled in component +} + +@media (max-width: 992px) { + .content-grid { + grid-template-columns: 1fr; + gap: 20px; + } + + .keywords-grid { + grid-template-columns: 1fr 1fr; + } +} + +@media (max-width: 768px) { + .detail-page { + padding: 16px; + } + + .page-header { + flex-direction: column; + align-items: flex-start; + gap: 12px; + } + + .project-hero { + padding: 20px; + } + + .metrics-grid { + grid-template-columns: 1fr 1fr; + gap: 12px; + } + + h1 { + font-size: 22px; + } + + .detail-row { + grid-template-columns: 1fr; + gap: 4px; + } + + .eyebrow { + gap: 8px; + } + + .topics-grid { + grid-template-columns: 1fr; + } + + .keywords-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 480px) { + .metrics-grid { + grid-template-columns: 1fr; + } + + .hero-actions { + flex-direction: column; + } + + .status-badge, + .scheme-info, + .doi-link { + width: 100%; + justify-content: center; + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts new file mode 100644 index 00000000..0c4020a9 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -0,0 +1,180 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { CommonModule } from '@angular/common'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { MatChipsModule } from '@angular/material/chips'; +import { Router } from '@angular/router'; + +@Component({ + selector: 'app-eu-details', + standalone: true, + imports: [CommonModule, MatCardModule, MatIconModule, MatChipsModule], + templateUrl: './eu-details.component.html', + styleUrl: './eu-details.component.scss', +}) +export class EuDetailsComponent implements OnInit { + private route = inject(ActivatedRoute); + euProject: any | undefined; + + constructor(private router: Router) {} + + ngOnInit(): void { + this.route.data.subscribe(({ euSingleProject }) => { + console.log('EU Project:', euSingleProject); + this.euProject = euSingleProject; + }); + } + + getInitials(name: string | null | undefined): string { + if (!name) return ''; + const parts = name.trim().split(/\s+/); + if (parts.length > 1) { + return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); + } + return parts[0][0].toUpperCase(); + } + + getFundingStatus(endDate: string | null | undefined): string { + if (!endDate) return 'N/A'; + const end = new Date(endDate); + const now = new Date(); + + if (isNaN(end.getTime())) return endDate; + + return end >= now ? 'Laufend' : 'Abgeschlossen'; + } + + formatCurrency(amount: number | null | undefined): string { + if (amount === null || amount === undefined) return 'N/A'; + + return new Intl.NumberFormat('de-DE', { + style: 'currency', + currency: 'EUR', + minimumFractionDigits: 0, + maximumFractionDigits: 0 + }).format(amount); + } + + getStatusColor(status: string | null | undefined): string { + if (!status) return '#95a5a6'; + + const statusUpper = status.toUpperCase(); + if (statusUpper.includes('CLOSED') || statusUpper.includes('COMPLETED')) { + return '#27ae60'; + } else if (statusUpper.includes('ONGOING') || statusUpper.includes('ACTIVE')) { + return '#f39c12'; + } else if (statusUpper.includes('SIGNED')) { + return '#3498db'; + } else if (statusUpper.includes('CANCELLED')) { + return '#e74c3c'; + } else { + return '#95a5a6'; + } + } + + getStatusDisplay(status: string | null | undefined): string { + if (!status) return 'N/A'; + + const statusMap: { [key: string]: string } = { + 'CLOSED': 'Abgeschlossen', + 'COMPLETED': 'Abgeschlossen', + 'ONGOING': 'Laufend', + 'ACTIVE': 'Aktiv', + 'SIGNED': 'Unterzeichnet', + 'CANCELLED': 'Abgebrochen', + 'SUSPENDED': 'Unterbrochen' + }; + + const statusUpper = status.toUpperCase(); + return statusMap[statusUpper] || status; + } + + getFrameworkDisplay(framework: string | null | undefined): string { + if (!framework) return 'N/A'; + + const frameworkMap: { [key: string]: string } = { + 'H2020': 'Horizon 2020', + 'FP7': '7. Rahmenprogramm', + 'FP6': '6. Rahmenprogramm', + 'HE': 'Horizon Europe' + }; + + return frameworkMap[framework] || framework; + } + + getFundingSchemeDisplay(scheme: string | null | undefined): string { + if (!scheme) return 'N/A'; + + const schemeMap: { [key: string]: string } = { + 'MSCA-IF-EF-SE': 'MSCA Individual Fellowship - European Fellowship - Standard', + 'MSCA-IF-EF': 'MSCA Individual Fellowship - European Fellowship', + 'MSCA-IF-GF': 'MSCA Individual Fellowship - Global Fellowship', + 'MSCA-IF': 'MSCA Individual Fellowship', + 'MSCA-ITN': 'MSCA Innovative Training Networks', + 'MSCA-RISE': 'MSCA Research and Innovation Staff Exchange', + 'MSCA-COFUND': 'MSCA Co-funding of Regional, National and International Programmes' + }; + + return schemeMap[scheme] || scheme; + } + + getFormattedTopics(topics: string | null | undefined): string[] { + if (!topics) return []; + return topics.split(',').map(t => t.trim()); + } + + getKeywords(keywords: string | null | undefined): string[] { + if (!keywords) return []; + if (keywords === 'false') return []; + // If keywords is a string with comma-separated values + if (typeof keywords === 'string') { + return keywords.split(',').map(k => k.trim()).filter(k => k && k !== 'false'); + } + return []; + } + + searchByTopic(topic: string): void { + this.router.navigate(['/eu-projects'], { + queryParams: { + topic: topic + } + }); + } + + searchByKeyword(keyword: string): void { + this.router.navigate(['/eu-projects'], { + queryParams: { + keyword: keyword + } + }); + } + + searchByFramework(framework: string): void { + this.router.navigate(['/eu-projects'], { + queryParams: { + framework: framework + } + }); + } + + searchByFundingScheme(scheme: string): void { + this.router.navigate(['/eu-projects'], { + queryParams: { + fundingScheme: scheme + } + }); + } + + searchByStatus(status: string): void { + this.router.navigate(['/eu-projects'], { + queryParams: { + status: status + } + }); + } + + goBack(): void { + window.history.back(); + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/projects/projects.component.ts b/webapp/src/app/modules/projects/projects.component.ts index 78563c74..5feada32 100644 --- a/webapp/src/app/modules/projects/projects.component.ts +++ b/webapp/src/app/modules/projects/projects.component.ts @@ -122,8 +122,9 @@ export class ProjectsComponent { return '/projects/bund/' + encodedId; } else if (fundingProject.type === 'dfg') { return '/projects/dfg/' + fundingProject.id; - } else { + } else if (fundingProject.type === 'eu') { + return '/projects/eu/' + fundingProject.id; + } else return null; } - } } From 0326fba2d460344b298873126c80d162c0d4d3a0 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 00:06:02 +0200 Subject: [PATCH 09/81] added eu project details endpoint to backend --- .../inse/projects/projects_search_client.py | 18 ++++++++++++++- service/src/main/inse/projects/router.py | 23 +++++++++++++++++++ service/src/main/inse/projects/service.py | 11 +++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 0a0653b2..777e51de 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -29,7 +29,6 @@ from inse.models.cordis_eu_project import CordisEuProject from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex - settings = get_settings() logger = logging.getLogger(__name__) @@ -559,6 +558,23 @@ def get_cordis_eu_projects_by_project_ids( ) +def get_eu_cordis_projects_by_id( + project_ids: List[str], +) -> CordisEuProject: + query = {"bool": {"filter": [{"term": {"id": project_ids}}]}} + + response = elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + ) + + hits = response.get("hits", {}).get("hits", []) + if hits: + hit = hits[0] + return CordisEuProject.model_validate(hit["_source"]) + return None + # DFG diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 509f5d8b..20d655ff 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -15,6 +15,7 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectsSortBy, SortDirection, + CordisEuProject ) from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails @@ -131,6 +132,28 @@ def get_single_bund_project( ) +@router.get( + "/eu/{id}", + summary="Get a single EU Cordis project.", + description="Returns a single EU Cordis project based on its ID.", + operation_id="getSingleEuCordisProject", + responses={ + status.HTTP_200_OK: { + "description": "Successful Response", + "model": CordisEuProject, + }, + status.HTTP_404_NOT_FOUND: {"description": "Project not found"}, + }, + response_model_by_alias=False, +) +def get_single_eu_cordis_project( + id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")], +) -> CordisEuProject: + logger.debug(f"Received request to get single EU Cordis project for id={id}") + return projects_service.get_single_eu_cordis_project( + project_id=id, + ) + @router.get( "/institution/bund/funding-over-time", summary="Get funding over time for bund projects.", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 75c72e0e..bf756cd0 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -17,6 +17,7 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectsSortBy, SortDirection, + CordisEuProject ) from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails @@ -322,6 +323,15 @@ def get_single_bund_project( raise NotFoundException(f"BUND project with id {project_id} not found") return project +def get_single_eu_cordis_project( + project_id: str, +) -> CordisEuProject: + logger.debug(f"Fetching single EU Cordis project for id={project_id}") + + project = projects_search_client.get_eu_cordis_projects_by_id(project_id) + if not project: + raise NotFoundException(f"EU project with id {project_id} not found") + return project def search_cordis_eu_projects_for_author_id( raw_oa_author_id: str, @@ -347,3 +357,4 @@ def search_cordis_eu_projects_for_author_id( ) return funding_project_page + From bd085764ddbe6687c091da4884596d56861da6b2 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 22 Jun 2026 17:30:22 +0200 Subject: [PATCH 10/81] Trigger Jenkins build From 68bc0cde7fbf69ea22c3e52b600006dc0bb16654 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 22 Jun 2026 23:46:55 +0200 Subject: [PATCH 11/81] feat(news): add relevant topics to news details page --- service/src/main/inse/news/logic.py | 49 +++++++++++++++++++ service/src/main/inse/news/model.py | 1 + .../news-detail/news-detail.component.html | 12 +++-- .../news-detail/news-detail.component.ts | 8 +-- 4 files changed, 59 insertions(+), 11 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 48e7f5ff..e62958e7 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -15,6 +15,11 @@ from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) +TOPIC_LIMIT = 4 +TOPIC_QUERY_CONTENT_CHARS = 300 +TOPIC_NUM_CANDIDATES = 100 +TOPIC_SIMILARITY = 0.5 + def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage: offset = (page - 1) * page_size @@ -130,6 +135,7 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) relevant, authors = _get_postproc_labels(news_id) + topics = _get_article_topics(source.get("maintitle"), source.get("full_content")) return NewsArticleDetail( id=response.get("_id"), @@ -140,9 +146,52 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: full_content=source.get("full_content"), relevant=relevant, authors=_build_mentioned_persons(authors), + topics=topics, ) +def _get_article_topics(maintitle: str | None, full_content: str | None) -> list: + query = " ".join( + part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part + ).strip() + if not query: + return [] + + try: + from ..util import get_model + + query_vector = get_model().encode(query).tolist() + except Exception: + logger.exception("Failed to encode news article text for topic search.") + return [] + + try: + response = elasticsearch.search( + index="topicvectors", + body={ + "knn": { + "field": "display_name_vector", + "query_vector": query_vector, + "k": TOPIC_LIMIT, + "num_candidates": TOPIC_NUM_CANDIDATES, + "similarity": TOPIC_SIMILARITY, + }, + "_source": ["display_name"], + "size": TOPIC_LIMIT, + }, + cluster="nes", + ) + except Exception: + logger.exception("Topic vector search for news article failed.") + return [] + + return [ + display_name + for hit in response.get("hits", {}).get("hits", []) + if (display_name := hit.get("_source", {}).get("display_name")) + ] + + def _build_mentioned_persons(author_names: list) -> list: ude_persons = [] diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 723e9b49..ec865fac 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -26,6 +26,7 @@ class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None relevant: Optional[bool] = None authors: List[MentionedPerson] = [] + topics: List[str] = [] class NewsPage(BaseModel): diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index dc1a3fc0..9df185c8 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -110,10 +110,14 @@ Relevante Themen
    - @for (topic of relevantTopics; track topic; let i = $index) { - {{ - topic - }} + @if (article.topics && article.topics.length) { + @for (topic of article.topics; track topic; let i = $index) { + {{ + topic + }} + } + } @else { +

    Keine Themen gefunden.

    }
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index bd75dc3c..f89e16fe 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -24,6 +24,7 @@ interface NewsArticleDetail { full_content?: string | null; relevant?: boolean; authors?: MentionedPerson[]; + topics?: string[]; } @Component({ @@ -49,13 +50,6 @@ export class NewsDetailComponent implements OnInit { loading = false; notFound = false; - readonly relevantTopics = [ - 'Künstliche Intelligenz', - 'Maschinelles Lernen', - 'Digitalisierung', - 'Datenwissenschaft', - ]; - private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink']; chipColor(index: number): string { From f894a48c31c36c0825eb6772cb880e420212fe7c Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 23:56:03 +0200 Subject: [PATCH 12/81] generated models for EU projects fp7 programm indexes --- .../projects_eu_cordis/fp7/fp7_eurosci_voc.py | 98 ++++++++ .../projects_eu_cordis/fp7/fp7_legal_basis.py | 96 ++++++++ .../fp7/fp7_organization.py | 139 ++++++++++++ .../projects_eu_cordis/fp7/fp7_project.py | 131 +++++++++++ .../fp7/fp7_project_details.py | 214 ++++++++++++++++++ .../projects_eu_cordis/fp7/fp7_project_ipr.py | 125 ++++++++++ .../projects_eu_cordis/fp7/fp7_publication.py | 123 ++++++++++ .../fp7/fp7_report_summary.py | 101 +++++++++ .../projects_eu_cordis/fp7/fp7_topic.py | 94 ++++++++ .../projects_eu_cordis/fp7/fp7_web_link.py | 107 +++++++++ 10 files changed, 1228 insertions(+) create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py new file mode 100644 index 00000000..27e2cec2 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_eurosci_voc.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7EurosciVoc(BaseModel): + """ + Fp7EurosciVoc + """ # noqa: E501 + code: Optional[StrictStr] = None + description: Optional[StrictStr] = None + id: Optional[StrictStr] = None + path: Optional[StrictStr] = None + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7EurosciVoc from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7EurosciVoc from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "code": obj.get("code"), + "description": obj.get("description"), + "id": obj.get("id"), + "path": obj.get("path"), + "projectID": obj.get("projectID"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py new file mode 100644 index 00000000..b4868f44 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_legal_basis.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7LegalBasis(BaseModel): + """ + Fp7LegalBasis + """ # noqa: E501 + id: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart") + __properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7LegalBasis from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7LegalBasis from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "legalBasis": obj.get("legalBasis"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "uniqueProgrammePart": obj.get("uniqueProgrammePart") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py new file mode 100644 index 00000000..9c6b1ffb --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_organization.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7Organization(BaseModel): + """ + Fp7Organization + """ # noqa: E501 + sme: Optional[StrictBool] = Field(default=None, alias="SME") + active: Optional[StrictBool] = None + activity_type: Optional[StrictStr] = Field(default=None, alias="activityType") + city: Optional[StrictStr] = None + contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm") + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + country: Optional[StrictStr] = None + ec_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecContribution") + end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation") + geolocation: Optional[StrictStr] = None + id: Optional[StrictStr] = None + name: Optional[StrictStr] = None + net_ec_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="netEcContribution") + nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode") + order: Optional[StrictInt] = None + organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID") + organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL") + post_code: Optional[StrictStr] = Field(default=None, alias="postCode") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + role: Optional[StrictStr] = None + short_name: Optional[StrictStr] = Field(default=None, alias="shortName") + street: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber") + __properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7Organization from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7Organization from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "SME": obj.get("SME"), + "active": obj.get("active"), + "activityType": obj.get("activityType"), + "city": obj.get("city"), + "contactForm": obj.get("contactForm"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "country": obj.get("country"), + "ecContribution": obj.get("ecContribution"), + "endOfParticipation": obj.get("endOfParticipation"), + "geolocation": obj.get("geolocation"), + "id": obj.get("id"), + "name": obj.get("name"), + "netEcContribution": obj.get("netEcContribution"), + "nutsCode": obj.get("nutsCode"), + "order": obj.get("order"), + "organisationID": obj.get("organisationID"), + "organizationURL": obj.get("organizationURL"), + "postCode": obj.get("postCode"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "role": obj.get("role"), + "shortName": obj.get("shortName"), + "street": obj.get("street"), + "totalCost": obj.get("totalCost"), + "vatNumber": obj.get("vatNumber") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py new file mode 100644 index 00000000..346bc4df --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project.py @@ -0,0 +1,131 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7Project(BaseModel): + """ + Fp7Project + """ # noqa: E501 + acronym: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + ec_max_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecMaxContribution") + ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate") + end_date: Optional[date] = Field(default=None, alias="endDate") + framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi") + human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated") + id: Optional[StrictStr] = None + keywords: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + master_call: Optional[StrictStr] = Field(default=None, alias="masterCall") + nature: Optional[StrictStr] = None + objective: Optional[StrictStr] = None + rcn: Optional[StrictStr] = None + start_date: Optional[date] = Field(default=None, alias="startDate") + status: Optional[StrictStr] = None + sub_call: Optional[StrictStr] = Field(default=None, alias="subCall") + title: Optional[StrictStr] = None + topics: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + __properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7Project from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7Project from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "acronym": obj.get("acronym"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "ecMaxContribution": obj.get("ecMaxContribution"), + "ecSignatureDate": obj.get("ecSignatureDate"), + "endDate": obj.get("endDate"), + "frameworkProgramme": obj.get("frameworkProgramme"), + "fundingScheme": obj.get("fundingScheme"), + "grantDoi": obj.get("grantDoi"), + "humanValidated": obj.get("humanValidated"), + "id": obj.get("id"), + "keywords": obj.get("keywords"), + "legalBasis": obj.get("legalBasis"), + "masterCall": obj.get("masterCall"), + "nature": obj.get("nature"), + "objective": obj.get("objective"), + "rcn": obj.get("rcn"), + "startDate": obj.get("startDate"), + "status": obj.get("status"), + "subCall": obj.get("subCall"), + "title": obj.get("title"), + "topics": obj.get("topics"), + "totalCost": obj.get("totalCost") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py new file mode 100644 index 00000000..be45d0db --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_details.py @@ -0,0 +1,214 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API - Extended Models +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +# Import all the base models +from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project +from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization +from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication +from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR +from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary +from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic +from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink +from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc +from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis + + +class Fp7ProjectDetails(BaseModel): + """ + Comprehensive FP7 Project model combining all related entities. + This model extends the base Fp7Project with all associated data. + """ + # Project core information (flattened from Fp7Project) + acronym: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + ec_max_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecMaxContribution") + ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate") + end_date: Optional[date] = Field(default=None, alias="endDate") + framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi") + human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated") + id: Optional[StrictStr] = None + keywords: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + master_call: Optional[StrictStr] = Field(default=None, alias="masterCall") + nature: Optional[StrictStr] = None + objective: Optional[StrictStr] = None + rcn: Optional[StrictStr] = None + start_date: Optional[date] = Field(default=None, alias="startDate") + status: Optional[StrictStr] = None + sub_call: Optional[StrictStr] = Field(default=None, alias="subCall") + title: Optional[StrictStr] = None + topics: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + + # Related entities (collections) + organizations: Optional[List[Fp7Organization]] = Field(default=None, description="Organizations participating in the project") + publications: Optional[List[Fp7Publication]] = Field(default=None, description="Publications related to the project") + iprs: Optional[List[Fp7ProjectIPR]] = Field(default=None, description="Intellectual Property Rights related to the project") + report_summaries: Optional[List[Fp7ReportSummary]] = Field(default=None, description="Report summaries for the project") + topics_list: Optional[List[Fp7Topic]] = Field(default=None, alias="topicsList", description="Topics associated with the project") + web_links: Optional[List[Fp7WebLink]] = Field(default=None, description="Web links related to the project") + eurosci_voc: Optional[List[Fp7EurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications") + legal_basis_list: Optional[List[Fp7LegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information") + + # Project statistics (aggregated) + organization_count: Optional[int] = Field(default=None, alias="organizationCount") + publication_count: Optional[int] = Field(default=None, alias="publicationCount") + ipr_count: Optional[int] = Field(default=None, alias="iprCount") + + __properties: ClassVar[List[str]] = [ + "acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", + "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", + "humanValidated", "id", "keywords", "legalBasis", "masterCall", + "nature", "objective", "rcn", "startDate", "status", "subCall", + "title", "topics", "totalCost", + "organizations", "publications", "iprs", "reportSummaries", + "topicsList", "webLinks", "eurosciVoc", "legalBasisList", + "organizationCount", "publicationCount", "iprCount" + ] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + populate_by_name=True, + ) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7ProjectDetailed from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias.""" + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7ProjectDetailed from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + # Project core fields + "acronym": obj.get("acronym"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "ecMaxContribution": obj.get("ecMaxContribution"), + "ecSignatureDate": obj.get("ecSignatureDate"), + "endDate": obj.get("endDate"), + "frameworkProgramme": obj.get("frameworkProgramme"), + "fundingScheme": obj.get("fundingScheme"), + "grantDoi": obj.get("grantDoi"), + "humanValidated": obj.get("humanValidated"), + "id": obj.get("id"), + "keywords": obj.get("keywords"), + "legalBasis": obj.get("legalBasis"), + "masterCall": obj.get("masterCall"), + "nature": obj.get("nature"), + "objective": obj.get("objective"), + "rcn": obj.get("rcn"), + "startDate": obj.get("startDate"), + "status": obj.get("status"), + "subCall": obj.get("subCall"), + "title": obj.get("title"), + "topics": obj.get("topics"), + "totalCost": obj.get("totalCost"), + + # Related entities + "organizations": [Fp7Organization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None, + "publications": [Fp7Publication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None, + "iprs": [Fp7ProjectIPR.from_dict(ipr) for ipr in obj.get("iprs", [])] if obj.get("iprs") else None, + "reportSummaries": [Fp7ReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None, + "topicsList": [Fp7Topic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None, + "webLinks": [Fp7WebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None, + "eurosciVoc": [Fp7EurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None, + "legalBasisList": [Fp7LegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None, + + # Statistics + "organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0, + "publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0, + "iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0, + }) + return _obj + + @classmethod + def from_project_with_relations( + cls, + project: Fp7Project, + organizations: Optional[List[Fp7Organization]] = None, + publications: Optional[List[Fp7Publication]] = None, + iprs: Optional[List[Fp7ProjectIPR]] = None, + report_summaries: Optional[List[Fp7ReportSummary]] = None, + topics_list: Optional[List[Fp7Topic]] = None, + web_links: Optional[List[Fp7WebLink]] = None, + eurosci_voc: Optional[List[Fp7EurosciVoc]] = None, + legal_basis_list: Optional[List[Fp7LegalBasis]] = None, + ) -> Self: + """ + Factory method to create a detailed project from a base project and its relations. + + Args: + project: The base Fp7Project object + organizations: List of organizations participating in the project + publications: List of publications related to the project + iprs: List of IPRs related to the project + report_summaries: List of report summaries + topics_list: List of topics associated with the project + web_links: List of web links + eurosci_voc: List of EuroSciVoc classifications + legal_basis_list: List of legal basis information + + Returns: + Fp7ProjectDetailed instance + """ + project_dict = project.to_dict() if project else {} + + return cls( + **project_dict, + organizations=organizations or [], + publications=publications or [], + iprs=iprs or [], + reportSummaries=report_summaries or [], + topicsList=topics_list or [], + webLinks=web_links or [], + eurosciVoc=eurosci_voc or [], + legalBasisList=legal_basis_list or [], + organizationCount=len(organizations) if organizations else 0, + publicationCount=len(publications) if publications else 0, + iprCount=len(iprs) if iprs else 0, + ) \ No newline at end of file diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py new file mode 100644 index 00000000..cfbdd89b --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_project_ipr.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7ProjectIPR(BaseModel): + """ + Fp7ProjectIPR + """ # noqa: E501 + applicant_name: Optional[StrictStr] = Field(default=None, alias="applicantName") + application_date: Optional[date] = Field(default=None, alias="applicationDate") + application_identifier: Optional[StrictStr] = Field(default=None, alias="applicationIdentifier") + application_kind: Optional[StrictStr] = Field(default=None, alias="applicationKind") + application_prefix: Optional[StrictStr] = Field(default=None, alias="applicationPrefix") + award_date: Optional[date] = Field(default=None, alias="awardDate") + award_identifier: Optional[StrictStr] = Field(default=None, alias="awardIdentifier") + award_kind: Optional[StrictStr] = Field(default=None, alias="awardKind") + award_prefix: Optional[StrictStr] = Field(default=None, alias="awardPrefix") + epo_app_url: Optional[StrictStr] = Field(default=None, alias="epoAppUrl") + epo_pub_url: Optional[StrictStr] = Field(default=None, alias="epoPubUrl") + id: Optional[StrictStr] = None + organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID") + patent_family_identifier: Optional[StrictStr] = Field(default=None, alias="patentFamilyIdentifier") + patent_type: Optional[StrictStr] = Field(default=None, alias="patentType") + priority_date: Optional[date] = Field(default=None, alias="priorityDate") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + type: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["applicantName", "applicationDate", "applicationIdentifier", "applicationKind", "applicationPrefix", "awardDate", "awardIdentifier", "awardKind", "awardPrefix", "epoAppUrl", "epoPubUrl", "id", "organisationID", "patentFamilyIdentifier", "patentType", "priorityDate", "projectID", "title", "type"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7ProjectIPR from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7ProjectIPR from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "applicantName": obj.get("applicantName"), + "applicationDate": obj.get("applicationDate"), + "applicationIdentifier": obj.get("applicationIdentifier"), + "applicationKind": obj.get("applicationKind"), + "applicationPrefix": obj.get("applicationPrefix"), + "awardDate": obj.get("awardDate"), + "awardIdentifier": obj.get("awardIdentifier"), + "awardKind": obj.get("awardKind"), + "awardPrefix": obj.get("awardPrefix"), + "epoAppUrl": obj.get("epoAppUrl"), + "epoPubUrl": obj.get("epoPubUrl"), + "id": obj.get("id"), + "organisationID": obj.get("organisationID"), + "patentFamilyIdentifier": obj.get("patentFamilyIdentifier"), + "patentType": obj.get("patentType"), + "priorityDate": obj.get("priorityDate"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "type": obj.get("type") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py new file mode 100644 index 00000000..2e9ab1ff --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_publication.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7Publication(BaseModel): + """ + Fp7Publication + """ # noqa: E501 + authors: Optional[StrictStr] = None + collection: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + doi: Optional[StrictStr] = None + id: Optional[StrictStr] = None + is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs") + journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber") + journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages") + published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear") + publisher: Optional[StrictStr] = None + qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi") + rcn: Optional[StrictStr] = None + repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl") + title: Optional[StrictStr] = None + volume: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7Publication from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7Publication from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "authors": obj.get("authors"), + "collection": obj.get("collection"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "doi": obj.get("doi"), + "id": obj.get("id"), + "isPublishedAs": obj.get("isPublishedAs"), + "journalNumber": obj.get("journalNumber"), + "journalTitle": obj.get("journalTitle"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "publishedPages": obj.get("publishedPages"), + "publishedYear": obj.get("publishedYear"), + "publisher": obj.get("publisher"), + "qaProcessedDoi": obj.get("qaProcessedDoi"), + "rcn": obj.get("rcn"), + "repositoryUrl": obj.get("repositoryUrl"), + "title": obj.get("title"), + "volume": obj.get("volume") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py new file mode 100644 index 00000000..43ce8910 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_report_summary.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7ReportSummary(BaseModel): + """ + Fp7ReportSummary + """ # noqa: E501 + attachments: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + id: Optional[StrictStr] = None + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7ReportSummary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7ReportSummary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "attachments": obj.get("attachments"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "id": obj.get("id"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py new file mode 100644 index 00000000..27a59a47 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_topic.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7Topic(BaseModel): + """ + Fp7Topic + """ # noqa: E501 + id: Optional[StrictStr] = None + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + topic: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7Topic from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7Topic from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "topic": obj.get("topic") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py new file mode 100644 index 00000000..6898b07f --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/fp7/fp7_web_link.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + CORDIS FP7 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Fp7WebLink(BaseModel): + """ + Fp7WebLink + """ # noqa: E501 + archived_date: Optional[datetime] = Field(default=None, alias="archivedDate") + available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages") + id: Optional[StrictStr] = None + link_id: Optional[StrictStr] = Field(default=None, alias="linkId") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + represents: Optional[StrictStr] = None + source: Optional[StrictStr] = None + status: Optional[StrictStr] = None + type: Optional[StrictStr] = None + url: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Fp7WebLink from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Fp7WebLink from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "archivedDate": obj.get("archivedDate"), + "availableLanguages": obj.get("availableLanguages"), + "id": obj.get("id"), + "linkId": obj.get("linkId"), + "projectID": obj.get("projectID"), + "represents": obj.get("represents"), + "source": obj.get("source"), + "status": obj.get("status"), + "type": obj.get("type"), + "url": obj.get("url") + }) + return _obj + + From ee7bd7ba05d0d6b664e0883618afbfc0d795e2a4 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 23:56:39 +0200 Subject: [PATCH 13/81] generated models for EU projects horizon 2020 programm indexes --- .../horizon2020/h2020_deliverable.py | 103 ++++++++ .../horizon2020/h2020_erc_pi.py | 102 ++++++++ .../horizon2020/h2020_eurosci_voc.py | 98 ++++++++ .../horizon2020/h2020_legal_basis.py | 96 ++++++++ .../horizon2020/h2020_organization.py | 139 +++++++++++ .../horizon2020/h2020_project.py | 131 ++++++++++ .../horizon2020/h2020_project_details.py | 224 ++++++++++++++++++ .../horizon2020/h2020_publication.py | 123 ++++++++++ .../horizon2020/h2020_report_summary.py | 101 ++++++++ .../horizon2020/h2020_topic.py | 94 ++++++++ .../horizon2020/h2020_web_link.py | 107 +++++++++ 11 files changed, 1318 insertions(+) create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py new file mode 100644 index 00000000..29166ca3 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_deliverable.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020Deliverable(BaseModel): + """ + H2020Deliverable + """ # noqa: E501 + collection: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + deliverable_type: Optional[StrictStr] = Field(default=None, alias="deliverableType") + description: Optional[StrictStr] = None + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + url: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["collection", "contentUpdateDate", "deliverableType", "description", "projectAcronym", "projectID", "rcn", "url"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020Deliverable from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020Deliverable from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "collection": obj.get("collection"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "deliverableType": obj.get("deliverableType"), + "description": obj.get("description"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "url": obj.get("url") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py new file mode 100644 index 00000000..b16ed4d0 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_erc_pi.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020ErcPI(BaseModel): + """ + H2020ErcPI + """ # noqa: E501 + first_name: Optional[StrictStr] = Field(default=None, alias="firstName") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + id: Optional[StrictStr] = None + last_name: Optional[StrictStr] = Field(default=None, alias="lastName") + organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["firstName", "fundingScheme", "id", "lastName", "organisationID", "projectAcronym", "projectID", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020ErcPI from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020ErcPI from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "firstName": obj.get("firstName"), + "fundingScheme": obj.get("fundingScheme"), + "id": obj.get("id"), + "lastName": obj.get("lastName"), + "organisationID": obj.get("organisationID"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py new file mode 100644 index 00000000..f6227b6c --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_eurosci_voc.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020EurosciVoc(BaseModel): + """ + H2020EurosciVoc + """ # noqa: E501 + code: Optional[StrictStr] = None + description: Optional[StrictStr] = None + id: Optional[StrictStr] = None + path: Optional[StrictStr] = None + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020EurosciVoc from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020EurosciVoc from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "code": obj.get("code"), + "description": obj.get("description"), + "id": obj.get("id"), + "path": obj.get("path"), + "projectID": obj.get("projectID"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py new file mode 100644 index 00000000..43327f68 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_legal_basis.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020LegalBasis(BaseModel): + """ + H2020LegalBasis + """ # noqa: E501 + id: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart") + __properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020LegalBasis from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020LegalBasis from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "legalBasis": obj.get("legalBasis"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "uniqueProgrammePart": obj.get("uniqueProgrammePart") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py new file mode 100644 index 00000000..057c1b71 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_organization.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020Organization(BaseModel): + """ + H2020Organization + """ # noqa: E501 + sme: Optional[StrictBool] = Field(default=None, alias="SME") + active: Optional[StrictBool] = None + activity_type: Optional[StrictStr] = Field(default=None, alias="activityType") + city: Optional[StrictStr] = None + contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm") + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + country: Optional[StrictStr] = None + ec_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecContribution") + end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation") + geolocation: Optional[StrictStr] = None + id: Optional[StrictStr] = None + name: Optional[StrictStr] = None + net_ec_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="netEcContribution") + nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode") + order: Optional[StrictInt] = None + organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID") + organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL") + post_code: Optional[StrictStr] = Field(default=None, alias="postCode") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + role: Optional[StrictStr] = None + short_name: Optional[StrictStr] = Field(default=None, alias="shortName") + street: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber") + __properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020Organization from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020Organization from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "SME": obj.get("SME"), + "active": obj.get("active"), + "activityType": obj.get("activityType"), + "city": obj.get("city"), + "contactForm": obj.get("contactForm"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "country": obj.get("country"), + "ecContribution": obj.get("ecContribution"), + "endOfParticipation": obj.get("endOfParticipation"), + "geolocation": obj.get("geolocation"), + "id": obj.get("id"), + "name": obj.get("name"), + "netEcContribution": obj.get("netEcContribution"), + "nutsCode": obj.get("nutsCode"), + "order": obj.get("order"), + "organisationID": obj.get("organisationID"), + "organizationURL": obj.get("organizationURL"), + "postCode": obj.get("postCode"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "role": obj.get("role"), + "shortName": obj.get("shortName"), + "street": obj.get("street"), + "totalCost": obj.get("totalCost"), + "vatNumber": obj.get("vatNumber") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py new file mode 100644 index 00000000..5aa572bd --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project.py @@ -0,0 +1,131 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020Project(BaseModel): + """ + H2020Project + """ # noqa: E501 + acronym: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + ec_max_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecMaxContribution") + ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate") + end_date: Optional[date] = Field(default=None, alias="endDate") + framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi") + human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated") + id: Optional[StrictStr] = None + keywords: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + master_call: Optional[StrictStr] = Field(default=None, alias="masterCall") + nature: Optional[StrictStr] = None + objective: Optional[StrictStr] = None + rcn: Optional[StrictStr] = None + start_date: Optional[date] = Field(default=None, alias="startDate") + status: Optional[StrictStr] = None + sub_call: Optional[StrictStr] = Field(default=None, alias="subCall") + title: Optional[StrictStr] = None + topics: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + __properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020Project from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020Project from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "acronym": obj.get("acronym"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "ecMaxContribution": obj.get("ecMaxContribution"), + "ecSignatureDate": obj.get("ecSignatureDate"), + "endDate": obj.get("endDate"), + "frameworkProgramme": obj.get("frameworkProgramme"), + "fundingScheme": obj.get("fundingScheme"), + "grantDoi": obj.get("grantDoi"), + "humanValidated": obj.get("humanValidated"), + "id": obj.get("id"), + "keywords": obj.get("keywords"), + "legalBasis": obj.get("legalBasis"), + "masterCall": obj.get("masterCall"), + "nature": obj.get("nature"), + "objective": obj.get("objective"), + "rcn": obj.get("rcn"), + "startDate": obj.get("startDate"), + "status": obj.get("status"), + "subCall": obj.get("subCall"), + "title": obj.get("title"), + "topics": obj.get("topics"), + "totalCost": obj.get("totalCost") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py new file mode 100644 index 00000000..fe0e3478 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_project_details.py @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API - Extended Models +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +# Import all the base models +from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project +from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization +from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication +from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable +from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary +from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic +from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink +from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc +from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis +from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI + + +class H2020ProjectDetails(BaseModel): + """ + Comprehensive Horizon 2020 Project model combining all related entities. + This model extends the base H2020Project with all associated data. + """ + # Project core information (flattened from H2020Project) + acronym: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + ec_max_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecMaxContribution") + ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate") + end_date: Optional[date] = Field(default=None, alias="endDate") + framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi") + human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated") + id: Optional[StrictStr] = None + keywords: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + master_call: Optional[StrictStr] = Field(default=None, alias="masterCall") + nature: Optional[StrictStr] = None + objective: Optional[StrictStr] = None + rcn: Optional[StrictStr] = None + start_date: Optional[date] = Field(default=None, alias="startDate") + status: Optional[StrictStr] = None + sub_call: Optional[StrictStr] = Field(default=None, alias="subCall") + title: Optional[StrictStr] = None + topics: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + + # Related entities (collections) + organizations: Optional[List[H2020Organization]] = Field(default=None, description="Organizations participating in the project") + publications: Optional[List[H2020Publication]] = Field(default=None, description="Publications related to the project") + deliverables: Optional[List[H2020Deliverable]] = Field(default=None, description="Deliverables of the project") + report_summaries: Optional[List[H2020ReportSummary]] = Field(default=None, alias="reportSummaries", description="Report summaries for the project") + topics_list: Optional[List[H2020Topic]] = Field(default=None, alias="topicsList", description="Topics associated with the project") + web_links: Optional[List[H2020WebLink]] = Field(default=None, alias="webLinks", description="Web links related to the project") + eurosci_voc: Optional[List[H2020EurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications") + legal_basis_list: Optional[List[H2020LegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information") + erc_principal_investigators: Optional[List[H2020ErcPI]] = Field(default=None, alias="ercPrincipalInvestigators", description="ERC Principal Investigators (specific to H2020)") + + # Project statistics (aggregated) + organization_count: Optional[int] = Field(default=None, alias="organizationCount") + publication_count: Optional[int] = Field(default=None, alias="publicationCount") + deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount") + erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount") + + __properties: ClassVar[List[str]] = [ + "acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", + "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", + "humanValidated", "id", "keywords", "legalBasis", "masterCall", + "nature", "objective", "rcn", "startDate", "status", "subCall", + "title", "topics", "totalCost", + "organizations", "publications", "deliverables", "reportSummaries", + "topicsList", "webLinks", "eurosciVoc", "legalBasisList", + "ercPrincipalInvestigators", + "organizationCount", "publicationCount", "deliverableCount", "ercPiCount" + ] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + populate_by_name=True, + ) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020ProjectDetailed from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias.""" + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020ProjectDetailed from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + # Project core fields + "acronym": obj.get("acronym"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "ecMaxContribution": obj.get("ecMaxContribution"), + "ecSignatureDate": obj.get("ecSignatureDate"), + "endDate": obj.get("endDate"), + "frameworkProgramme": obj.get("frameworkProgramme"), + "fundingScheme": obj.get("fundingScheme"), + "grantDoi": obj.get("grantDoi"), + "humanValidated": obj.get("humanValidated"), + "id": obj.get("id"), + "keywords": obj.get("keywords"), + "legalBasis": obj.get("legalBasis"), + "masterCall": obj.get("masterCall"), + "nature": obj.get("nature"), + "objective": obj.get("objective"), + "rcn": obj.get("rcn"), + "startDate": obj.get("startDate"), + "status": obj.get("status"), + "subCall": obj.get("subCall"), + "title": obj.get("title"), + "topics": obj.get("topics"), + "totalCost": obj.get("totalCost"), + + # Related entities + "organizations": [H2020Organization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None, + "publications": [H2020Publication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None, + "deliverables": [H2020Deliverable.from_dict(deliv) for deliv in obj.get("deliverables", [])] if obj.get("deliverables") else None, + "reportSummaries": [H2020ReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None, + "topicsList": [H2020Topic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None, + "webLinks": [H2020WebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None, + "eurosciVoc": [H2020EurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None, + "legalBasisList": [H2020LegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None, + "ercPrincipalInvestigators": [H2020ErcPI.from_dict(pi) for pi in obj.get("ercPrincipalInvestigators", [])] if obj.get("ercPrincipalInvestigators") else None, + + # Statistics + "organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0, + "publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0, + "deliverableCount": len(obj.get("deliverables", [])) if obj.get("deliverables") else 0, + "ercPiCount": len(obj.get("ercPrincipalInvestigators", [])) if obj.get("ercPrincipalInvestigators") else 0, + }) + return _obj + + @classmethod + def from_project_with_relations( + cls, + project: H2020Project, + organizations: Optional[List[H2020Organization]] = None, + publications: Optional[List[H2020Publication]] = None, + deliverables: Optional[List[H2020Deliverable]] = None, + report_summaries: Optional[List[H2020ReportSummary]] = None, + topics_list: Optional[List[H2020Topic]] = None, + web_links: Optional[List[H2020WebLink]] = None, + eurosci_voc: Optional[List[H2020EurosciVoc]] = None, + legal_basis_list: Optional[List[H2020LegalBasis]] = None, + erc_principal_investigators: Optional[List[H2020ErcPI]] = None, + ) -> Self: + """ + Factory method to create a detailed project from a base project and its relations. + + Args: + project: The base H2020Project object + organizations: List of organizations participating in the project + publications: List of publications related to the project + deliverables: List of deliverables of the project + report_summaries: List of report summaries + topics_list: List of topics associated with the project + web_links: List of web links + eurosci_voc: List of EuroSciVoc classifications + legal_basis_list: List of legal basis information + erc_principal_investigators: List of ERC Principal Investigators + + Returns: + H2020ProjectDetailed instance + """ + project_dict = project.to_dict() if project else {} + + return cls( + **project_dict, + organizations=organizations or [], + publications=publications or [], + deliverables=deliverables or [], + reportSummaries=report_summaries or [], + topicsList=topics_list or [], + webLinks=web_links or [], + eurosciVoc=eurosci_voc or [], + legalBasisList=legal_basis_list or [], + ercPrincipalInvestigators=erc_principal_investigators or [], + organizationCount=len(organizations) if organizations else 0, + publicationCount=len(publications) if publications else 0, + deliverableCount=len(deliverables) if deliverables else 0, + ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0, + ) \ No newline at end of file diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py new file mode 100644 index 00000000..ffe9a440 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_publication.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020Publication(BaseModel): + """ + H2020Publication + """ # noqa: E501 + authors: Optional[StrictStr] = None + collection: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + doi: Optional[StrictStr] = None + id: Optional[StrictStr] = None + is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs") + journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber") + journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages") + published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear") + publisher: Optional[StrictStr] = None + qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi") + rcn: Optional[StrictStr] = None + repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl") + title: Optional[StrictStr] = None + volume: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020Publication from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020Publication from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "authors": obj.get("authors"), + "collection": obj.get("collection"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "doi": obj.get("doi"), + "id": obj.get("id"), + "isPublishedAs": obj.get("isPublishedAs"), + "journalNumber": obj.get("journalNumber"), + "journalTitle": obj.get("journalTitle"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "publishedPages": obj.get("publishedPages"), + "publishedYear": obj.get("publishedYear"), + "publisher": obj.get("publisher"), + "qaProcessedDoi": obj.get("qaProcessedDoi"), + "rcn": obj.get("rcn"), + "repositoryUrl": obj.get("repositoryUrl"), + "title": obj.get("title"), + "volume": obj.get("volume") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py new file mode 100644 index 00000000..e1f7e49f --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_report_summary.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020ReportSummary(BaseModel): + """ + H2020ReportSummary + """ # noqa: E501 + attachments: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + id: Optional[StrictStr] = None + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020ReportSummary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020ReportSummary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "attachments": obj.get("attachments"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "id": obj.get("id"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py new file mode 100644 index 00000000..0c6bedbb --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_topic.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020Topic(BaseModel): + """ + H2020Topic + """ # noqa: E501 + id: Optional[StrictStr] = None + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + topic: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020Topic from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020Topic from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "topic": obj.get("topic") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py new file mode 100644 index 00000000..a8e45638 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon2020/h2020_web_link.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + CORDIS Horizon 2020 Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class H2020WebLink(BaseModel): + """ + H2020WebLink + """ # noqa: E501 + archived_date: Optional[datetime] = Field(default=None, alias="archivedDate") + available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages") + id: Optional[StrictStr] = None + link_id: Optional[StrictStr] = Field(default=None, alias="linkId") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + represents: Optional[StrictStr] = None + source: Optional[StrictStr] = None + status: Optional[StrictStr] = None + type: Optional[StrictStr] = None + url: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of H2020WebLink from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of H2020WebLink from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "archivedDate": obj.get("archivedDate"), + "availableLanguages": obj.get("availableLanguages"), + "id": obj.get("id"), + "linkId": obj.get("linkId"), + "projectID": obj.get("projectID"), + "represents": obj.get("represents"), + "source": obj.get("source"), + "status": obj.get("status"), + "type": obj.get("type"), + "url": obj.get("url") + }) + return _obj + + From 6ae5f3e620cd6b03090ad3e14a4051e3ebb90675 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 22 Jun 2026 23:57:04 +0200 Subject: [PATCH 14/81] generated models for EU projects horizon_europe programm indexes --- .../horizon_europe/heu_deliverable.py | 103 +++++++++ .../horizon_europe/heu_eurosci_voc.py | 98 ++++++++ .../horizon_europe/heu_legal_basis.py | 96 ++++++++ .../horizon_europe/heu_organization.py | 139 ++++++++++++ .../horizon_europe/heu_project.py | 131 +++++++++++ .../horizon_europe/heu_project_details.py | 214 ++++++++++++++++++ .../horizon_europe/heu_publication.py | 123 ++++++++++ .../horizon_europe/heu_report_summary.py | 101 +++++++++ .../horizon_europe/heu_topic.py | 94 ++++++++ .../horizon_europe/heu_web_link.py | 107 +++++++++ 10 files changed, 1206 insertions(+) create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py create mode 100644 service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py new file mode 100644 index 00000000..ba858158 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_deliverable.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUDeliverable(BaseModel): + """ + HEUDeliverable + """ # noqa: E501 + collection: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + deliverable_type: Optional[StrictStr] = Field(default=None, alias="deliverableType") + description: Optional[StrictStr] = None + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + url: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["collection", "contentUpdateDate", "deliverableType", "description", "projectAcronym", "projectID", "rcn", "url"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUDeliverable from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUDeliverable from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "collection": obj.get("collection"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "deliverableType": obj.get("deliverableType"), + "description": obj.get("description"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "url": obj.get("url") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py new file mode 100644 index 00000000..586f3777 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_eurosci_voc.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUEurosciVoc(BaseModel): + """ + HEUEurosciVoc + """ # noqa: E501 + code: Optional[StrictStr] = None + description: Optional[StrictStr] = None + id: Optional[StrictStr] = None + path: Optional[StrictStr] = None + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUEurosciVoc from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUEurosciVoc from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "code": obj.get("code"), + "description": obj.get("description"), + "id": obj.get("id"), + "path": obj.get("path"), + "projectID": obj.get("projectID"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py new file mode 100644 index 00000000..0c4e288e --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_legal_basis.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEULegalBasis(BaseModel): + """ + HEULegalBasis + """ # noqa: E501 + id: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart") + __properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEULegalBasis from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEULegalBasis from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "legalBasis": obj.get("legalBasis"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "uniqueProgrammePart": obj.get("uniqueProgrammePart") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py new file mode 100644 index 00000000..109a5a5a --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_organization.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUOrganization(BaseModel): + """ + HEUOrganization + """ # noqa: E501 + sme: Optional[StrictBool] = Field(default=None, alias="SME") + active: Optional[StrictBool] = None + activity_type: Optional[StrictStr] = Field(default=None, alias="activityType") + city: Optional[StrictStr] = None + contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm") + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + country: Optional[StrictStr] = None + ec_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecContribution") + end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation") + geolocation: Optional[StrictStr] = None + id: Optional[StrictStr] = None + name: Optional[StrictStr] = None + net_ec_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="netEcContribution") + nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode") + order: Optional[StrictInt] = None + organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID") + organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL") + post_code: Optional[StrictStr] = Field(default=None, alias="postCode") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + role: Optional[StrictStr] = None + short_name: Optional[StrictStr] = Field(default=None, alias="shortName") + street: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber") + __properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUOrganization from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUOrganization from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "SME": obj.get("SME"), + "active": obj.get("active"), + "activityType": obj.get("activityType"), + "city": obj.get("city"), + "contactForm": obj.get("contactForm"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "country": obj.get("country"), + "ecContribution": obj.get("ecContribution"), + "endOfParticipation": obj.get("endOfParticipation"), + "geolocation": obj.get("geolocation"), + "id": obj.get("id"), + "name": obj.get("name"), + "netEcContribution": obj.get("netEcContribution"), + "nutsCode": obj.get("nutsCode"), + "order": obj.get("order"), + "organisationID": obj.get("organisationID"), + "organizationURL": obj.get("organizationURL"), + "postCode": obj.get("postCode"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "role": obj.get("role"), + "shortName": obj.get("shortName"), + "street": obj.get("street"), + "totalCost": obj.get("totalCost"), + "vatNumber": obj.get("vatNumber") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py new file mode 100644 index 00000000..c843fc17 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project.py @@ -0,0 +1,131 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUProject(BaseModel): + """ + HEUProject + """ # noqa: E501 + acronym: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + ec_max_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecMaxContribution") + ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate") + end_date: Optional[date] = Field(default=None, alias="endDate") + framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi") + human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated") + id: Optional[StrictStr] = None + keywords: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + master_call: Optional[StrictStr] = Field(default=None, alias="masterCall") + nature: Optional[StrictStr] = None + objective: Optional[StrictStr] = None + rcn: Optional[StrictStr] = None + start_date: Optional[date] = Field(default=None, alias="startDate") + status: Optional[StrictStr] = None + sub_call: Optional[StrictStr] = Field(default=None, alias="subCall") + title: Optional[StrictStr] = None + topics: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + __properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUProject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUProject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "acronym": obj.get("acronym"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "ecMaxContribution": obj.get("ecMaxContribution"), + "ecSignatureDate": obj.get("ecSignatureDate"), + "endDate": obj.get("endDate"), + "frameworkProgramme": obj.get("frameworkProgramme"), + "fundingScheme": obj.get("fundingScheme"), + "grantDoi": obj.get("grantDoi"), + "humanValidated": obj.get("humanValidated"), + "id": obj.get("id"), + "keywords": obj.get("keywords"), + "legalBasis": obj.get("legalBasis"), + "masterCall": obj.get("masterCall"), + "nature": obj.get("nature"), + "objective": obj.get("objective"), + "rcn": obj.get("rcn"), + "startDate": obj.get("startDate"), + "status": obj.get("status"), + "subCall": obj.get("subCall"), + "title": obj.get("title"), + "topics": obj.get("topics"), + "totalCost": obj.get("totalCost") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py new file mode 100644 index 00000000..05bacd3a --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_project_details.py @@ -0,0 +1,214 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API - Extended Models +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +# Import all the base models +from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject +from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization +from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication +from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable +from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary +from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic +from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink +from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc +from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis + + +class HEUProjectDetails(BaseModel): + """ + Comprehensive Horizon Europe Project model combining all related entities. + This model extends the base HEUProject with all associated data. + """ + # Project core information (flattened from HEUProject) + acronym: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + ec_max_contribution: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="ecMaxContribution") + ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate") + end_date: Optional[date] = Field(default=None, alias="endDate") + framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme") + funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme") + grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi") + human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated") + id: Optional[StrictStr] = None + keywords: Optional[StrictStr] = None + legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis") + master_call: Optional[StrictStr] = Field(default=None, alias="masterCall") + nature: Optional[StrictStr] = None + objective: Optional[StrictStr] = None + rcn: Optional[StrictStr] = None + start_date: Optional[date] = Field(default=None, alias="startDate") + status: Optional[StrictStr] = None + sub_call: Optional[StrictStr] = Field(default=None, alias="subCall") + title: Optional[StrictStr] = None + topics: Optional[StrictStr] = None + total_cost: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalCost") + + # Related entities (collections) + organizations: Optional[List[HEUOrganization]] = Field(default=None, description="Organizations participating in the project") + publications: Optional[List[HEUPublication]] = Field(default=None, description="Publications related to the project") + deliverables: Optional[List[HEUDeliverable]] = Field(default=None, description="Deliverables of the project") + report_summaries: Optional[List[HEUReportSummary]] = Field(default=None, alias="reportSummaries", description="Report summaries for the project") + topics_list: Optional[List[HEUTopic]] = Field(default=None, alias="topicsList", description="Topics associated with the project") + web_links: Optional[List[HEUWebLink]] = Field(default=None, alias="webLinks", description="Web links related to the project") + eurosci_voc: Optional[List[HEUEurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications") + legal_basis_list: Optional[List[HEULegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information") + + # Project statistics (aggregated) + organization_count: Optional[int] = Field(default=None, alias="organizationCount") + publication_count: Optional[int] = Field(default=None, alias="publicationCount") + deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount") + + __properties: ClassVar[List[str]] = [ + "acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", + "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", + "humanValidated", "id", "keywords", "legalBasis", "masterCall", + "nature", "objective", "rcn", "startDate", "status", "subCall", + "title", "topics", "totalCost", + "organizations", "publications", "deliverables", "reportSummaries", + "topicsList", "webLinks", "eurosciVoc", "legalBasisList", + "organizationCount", "publicationCount", "deliverableCount" + ] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + populate_by_name=True, + ) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUProjectDetailed from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias.""" + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUProjectDetailed from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + # Project core fields + "acronym": obj.get("acronym"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "ecMaxContribution": obj.get("ecMaxContribution"), + "ecSignatureDate": obj.get("ecSignatureDate"), + "endDate": obj.get("endDate"), + "frameworkProgramme": obj.get("frameworkProgramme"), + "fundingScheme": obj.get("fundingScheme"), + "grantDoi": obj.get("grantDoi"), + "humanValidated": obj.get("humanValidated"), + "id": obj.get("id"), + "keywords": obj.get("keywords"), + "legalBasis": obj.get("legalBasis"), + "masterCall": obj.get("masterCall"), + "nature": obj.get("nature"), + "objective": obj.get("objective"), + "rcn": obj.get("rcn"), + "startDate": obj.get("startDate"), + "status": obj.get("status"), + "subCall": obj.get("subCall"), + "title": obj.get("title"), + "topics": obj.get("topics"), + "totalCost": obj.get("totalCost"), + + # Related entities + "organizations": [HEUOrganization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None, + "publications": [HEUPublication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None, + "deliverables": [HEUDeliverable.from_dict(deliv) for deliv in obj.get("deliverables", [])] if obj.get("deliverables") else None, + "reportSummaries": [HEUReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None, + "topicsList": [HEUTopic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None, + "webLinks": [HEUWebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None, + "eurosciVoc": [HEUEurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None, + "legalBasisList": [HEULegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None, + + # Statistics + "organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0, + "publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0, + "deliverableCount": len(obj.get("deliverables", [])) if obj.get("deliverables") else 0, + }) + return _obj + + @classmethod + def from_project_with_relations( + cls, + project: HEUProject, + organizations: Optional[List[HEUOrganization]] = None, + publications: Optional[List[HEUPublication]] = None, + deliverables: Optional[List[HEUDeliverable]] = None, + report_summaries: Optional[List[HEUReportSummary]] = None, + topics_list: Optional[List[HEUTopic]] = None, + web_links: Optional[List[HEUWebLink]] = None, + eurosci_voc: Optional[List[HEUEurosciVoc]] = None, + legal_basis_list: Optional[List[HEULegalBasis]] = None, + ) -> Self: + """ + Factory method to create a detailed project from a base project and its relations. + + Args: + project: The base HEUProject object + organizations: List of organizations participating in the project + publications: List of publications related to the project + deliverables: List of deliverables of the project + report_summaries: List of report summaries + topics_list: List of topics associated with the project + web_links: List of web links + eurosci_voc: List of EuroSciVoc classifications + legal_basis_list: List of legal basis information + + Returns: + HEUProjectDetailed instance + """ + project_dict = project.to_dict() if project else {} + + return cls( + **project_dict, + organizations=organizations or [], + publications=publications or [], + deliverables=deliverables or [], + reportSummaries=report_summaries or [], + topicsList=topics_list or [], + webLinks=web_links or [], + eurosciVoc=eurosci_voc or [], + legalBasisList=legal_basis_list or [], + organizationCount=len(organizations) if organizations else 0, + publicationCount=len(publications) if publications else 0, + deliverableCount=len(deliverables) if deliverables else 0, + ) \ No newline at end of file diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py new file mode 100644 index 00000000..9d3424df --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_publication.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUPublication(BaseModel): + """ + HEUPublication + """ # noqa: E501 + authors: Optional[StrictStr] = None + collection: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + doi: Optional[StrictStr] = None + id: Optional[StrictStr] = None + is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs") + journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber") + journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle") + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages") + published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear") + publisher: Optional[StrictStr] = None + qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi") + rcn: Optional[StrictStr] = None + repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl") + title: Optional[StrictStr] = None + volume: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUPublication from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUPublication from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "authors": obj.get("authors"), + "collection": obj.get("collection"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "doi": obj.get("doi"), + "id": obj.get("id"), + "isPublishedAs": obj.get("isPublishedAs"), + "journalNumber": obj.get("journalNumber"), + "journalTitle": obj.get("journalTitle"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "publishedPages": obj.get("publishedPages"), + "publishedYear": obj.get("publishedYear"), + "publisher": obj.get("publisher"), + "qaProcessedDoi": obj.get("qaProcessedDoi"), + "rcn": obj.get("rcn"), + "repositoryUrl": obj.get("repositoryUrl"), + "title": obj.get("title"), + "volume": obj.get("volume") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py new file mode 100644 index 00000000..bf5850fc --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_report_summary.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUReportSummary(BaseModel): + """ + HEUReportSummary + """ # noqa: E501 + attachments: Optional[StrictStr] = None + content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate") + id: Optional[StrictStr] = None + project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + rcn: Optional[StrictStr] = None + title: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUReportSummary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUReportSummary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "attachments": obj.get("attachments"), + "contentUpdateDate": obj.get("contentUpdateDate"), + "id": obj.get("id"), + "projectAcronym": obj.get("projectAcronym"), + "projectID": obj.get("projectID"), + "rcn": obj.get("rcn"), + "title": obj.get("title") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py new file mode 100644 index 00000000..4aa58787 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_topic.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUTopic(BaseModel): + """ + HEUTopic + """ # noqa: E501 + id: Optional[StrictStr] = None + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + title: Optional[StrictStr] = None + topic: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUTopic from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUTopic from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "projectID": obj.get("projectID"), + "title": obj.get("title"), + "topic": obj.get("topic") + }) + return _obj + + diff --git a/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py new file mode 100644 index 00000000..50797815 --- /dev/null +++ b/service/src/main/inse/models/projects_eu_cordis/horizon_europe/heu_web_link.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + CORDIS Horizon Europe Multi-Index API + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HEUWebLink(BaseModel): + """ + HEUWebLink + """ # noqa: E501 + archived_date: Optional[datetime] = Field(default=None, alias="archivedDate") + available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages") + id: Optional[StrictStr] = None + link_id: Optional[StrictStr] = Field(default=None, alias="linkId") + project_id: Optional[StrictStr] = Field(default=None, alias="projectID") + represents: Optional[StrictStr] = None + source: Optional[StrictStr] = None + status: Optional[StrictStr] = None + type: Optional[StrictStr] = None + url: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HEUWebLink from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HEUWebLink from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "archivedDate": obj.get("archivedDate"), + "availableLanguages": obj.get("availableLanguages"), + "id": obj.get("id"), + "linkId": obj.get("linkId"), + "projectID": obj.get("projectID"), + "represents": obj.get("represents"), + "source": obj.get("source"), + "status": obj.get("status"), + "type": obj.get("type"), + "url": obj.get("url") + }) + return _obj + + From ba384dffbb52deedc6263d94fcbc0763607fa3c5 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:03:08 +0200 Subject: [PATCH 15/81] created data enrichment logic for EU projects --- .../eu_cordis_projects_enrichment_client.py | 372 ++++++++++++++++++ 1 file changed, 372 insertions(+) create mode 100644 service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py new file mode 100644 index 00000000..88e314cb --- /dev/null +++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py @@ -0,0 +1,372 @@ +import json +import logging +from typing import Any, Dict, List, Optional, Union + +from inse.config import get_settings +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +# Import base models +from inse.models.cordis_eu_project import CordisEuProject + +# Import FP7 models +from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project +from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization +from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication +from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR +from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary +from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic +from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink +from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc +from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails + +# Import H2020 models +from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project +from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization +from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication +from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable +from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary +from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic +from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink +from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc +from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis +from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails + +# Import Horizon Europe models +from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject +from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization +from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication +from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable +from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary +from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic +from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink +from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc +from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails + +settings = get_settings() +logger = logging.getLogger(__name__) +logger.setLevel(settings.logging_level) + + +def get_enriched_cordis_project_by_id( + project_id: str, +) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: + """ + Fetches and enriches a single Cordis EU project by its ID across all program types. + + Args: + project_id: The project ID to fetch + + Returns: + The enriched detailed project model, or None if not found + """ + if not project_id: + return None + + # Step 1: Search for the project across all indices + query = {"bool": {"filter": [{"term": {"id": project_id}}]}} + + response = elasticsearch.search( + query=query, + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + cluster=ESCluster.INSE, + size=1, + ) + + hits = response.get("hits", {}).get("hits", []) + if not hits: + logger.info(f"No project found with ID: {project_id}") + return None + + hit = hits[0] + index = hit.get("_index", "") + source = hit.get("_source", {}) + + # Determine program type from index name + program_type = _determine_program_type_from_index(index) + + # Enrich and return the project based on program type + if program_type == "fp7": + return _enrich_fp7_project(project_id, source) + elif program_type == "h2020": + return _enrich_h2020_project(project_id, source) + elif program_type == "heu": + return _enrich_heu_project(project_id, source) + else: + # Unknown type, return base model + logger.warning(f"Unknown program type for index: {index}") + return CordisEuProject.model_validate(source) + + +def _determine_program_type_from_index(index: str) -> str: + """Determines the program type from the Elasticsearch index name.""" + index_lower = index.lower() + if "fp7" in index_lower: + return "fp7" + elif "horizon_2020" or () in index_lower: + return "h2020" + elif "heu" in index_lower or "horizon_europe" in index_lower: + return "heu" + return "unknown" + + +def _enrich_fp7_project( + project_id: str, + project_source: Dict[str, Any] +) -> Optional[Fp7ProjectDetails]: + """Enriches a single FP7 project with all related data.""" + try: + project = Fp7Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate FP7 project {project_id}: {e}") + return None + + # Fetch all related data + organizations = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_organizations", + model_class=Fp7Organization + ) + publications = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_publications", + model_class=Fp7Publication + ) + iprs = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_iprs", + model_class=Fp7ProjectIPR + ) + report_summaries = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_report_summaries", + model_class=Fp7ReportSummary + ) + topics_list = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_topics", + model_class=Fp7Topic + ) + web_links = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_web_links", + model_class=Fp7WebLink + ) + eurosci_voc = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_eurosci_voc", + model_class=Fp7EurosciVoc + ) + legal_basis_list = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_fp7_legal_basis", + model_class=Fp7LegalBasis + ) + + # Build and return enriched project + return Fp7ProjectDetails.from_project_with_relations( + project=project, + organizations=organizations.get(project_id, []), + publications=publications.get(project_id, []), + iprs=iprs.get(project_id, []), + report_summaries=report_summaries.get(project_id, []), + topics_list=topics_list.get(project_id, []), + web_links=web_links.get(project_id, []), + eurosci_voc=eurosci_voc.get(project_id, []), + legal_basis_list=legal_basis_list.get(project_id, []), + ) + + +def _enrich_h2020_project( + project_id: str, + project_source: Dict[str, Any] +) -> Optional[H2020ProjectDetails]: + """Enriches a single H2020 project with all related data.""" + try: + project = H2020Project.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate H2020 project {project_id}: {e}") + return None + + # Fetch all related data + organizations = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_organizations", + model_class=H2020Organization + ) + publications = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_publications", + model_class=H2020Publication + ) + deliverables = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_deliverables", + model_class=H2020Deliverable + ) + report_summaries = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_report_summaries", + model_class=H2020ReportSummary + ) + topics_list = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_topics", + model_class=H2020Topic + ) + web_links = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_web_links", + model_class=H2020WebLink + ) + eurosci_voc = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_eurosci_voc", + model_class=H2020EurosciVoc + ) + legal_basis_list = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_legal_basis", + model_class=H2020LegalBasis + ) + erc_pis = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_h2020_erc_pis", + model_class=H2020ErcPI + ) + + # Build and return enriched project + return H2020ProjectDetails.from_project_with_relations( + project=project, + organizations=organizations.get(project_id, []), + publications=publications.get(project_id, []), + deliverables=deliverables.get(project_id, []), + report_summaries=report_summaries.get(project_id, []), + topics_list=topics_list.get(project_id, []), + web_links=web_links.get(project_id, []), + eurosci_voc=eurosci_voc.get(project_id, []), + legal_basis_list=legal_basis_list.get(project_id, []), + erc_principal_investigators=erc_pis.get(project_id, []), + ) + + +def _enrich_heu_project( + project_id: str, + project_source: Dict[str, Any] +) -> Optional[HEUProjectDetails]: + """Enriches a single Horizon Europe project with all related data.""" + try: + project = HEUProject.model_validate(project_source) + except Exception as e: + logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") + return None + + # Fetch all related data + organizations = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_organizations", + model_class=HEUOrganization + ) + publications = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_publications", + model_class=HEUPublication + ) + deliverables = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_deliverables", + model_class=HEUDeliverable + ) + report_summaries = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_report_summaries", + model_class=HEUReportSummary + ) + topics_list = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_topics", + model_class=HEUTopic + ) + web_links = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_web_links", + model_class=HEUWebLink + ) + eurosci_voc = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_eurosci_voc", + model_class=HEUEurosciVoc + ) + legal_basis_list = _fetch_related_entities( + project_ids=[project_id], + index_pattern="cordis_eu_heu_legal_basis", + model_class=HEULegalBasis + ) + + # Build and return enriched project + return HEUProjectDetails.from_project_with_relations( + project=project, + organizations=organizations.get(project_id, []), + publications=publications.get(project_id, []), + deliverables=deliverables.get(project_id, []), + report_summaries=report_summaries.get(project_id, []), + topics_list=topics_list.get(project_id, []), + web_links=web_links.get(project_id, []), + eurosci_voc=eurosci_voc.get(project_id, []), + legal_basis_list=legal_basis_list.get(project_id, []), + ) + + +def _fetch_related_entities( + project_ids: List[str], + index_pattern: str, + model_class: Any +) -> Dict[str, List[Any]]: + """ + Fetches and groups related entities from Elasticsearch by project ID. + + Args: + project_ids: List of project IDs to fetch entities for + index_pattern: The index pattern to search (supports wildcards) + model_class: The Pydantic model class to validate against + + Returns: + Dictionary mapping project IDs to lists of entities + """ + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + + try: + response = elasticsearch.search( + query=query, + index=index_pattern, + cluster=ESCluster.INSE, + size=1 + ) + except Exception as e: + logger.warning(f"Failed to fetch from {index_pattern}: {e}") + return {} + + grouped = {} + hits = response.get("hits", {}).get("hits", []) + + for hit in hits: + source = hit.get("_source", {}) + project_id = source.get("projectID") + + if not project_id: + continue + + if project_id not in grouped: + grouped[project_id] = [] + + try: + entity = model_class.model_validate(source) + grouped[project_id].append(entity) + except Exception as e: + logger.warning(f"Failed to validate entity for project {project_id}: {e}") + continue + + return grouped \ No newline at end of file From 9908f8c0447210212a51e7e07771e90137ce8275 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:03:32 +0200 Subject: [PATCH 16/81] added backend logic for EU Cordis projects --- service/src/main/inse/projects/model.py | 24 +++++- .../inse/projects/projects_search_client.py | 36 +++++---- service/src/main/inse/projects/router.py | 78 +++++++++++++++++-- service/src/main/inse/projects/service.py | 7 +- 4 files changed, 117 insertions(+), 28 deletions(-) diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index d0957d4d..526e55af 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -9,7 +9,10 @@ from inse.models.bund_project import BundProject from inse.models.eu_project import EuProject from inse.models.cordis_eu_project import CordisEuProject from inse.model import ESIndex - +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails +from typing import Union class ProjectType(StrEnum): BUND = "bund" @@ -165,6 +168,25 @@ class CordisEuProjectPage(Page): ) +class EuCordisProjectResponse(BaseModel): + """ + Response model for EU Cordis project endpoints. + """ + success: bool = Field(description="Indicates if the request was successful") + project_type: Optional[str] = Field( + default=None, + description="The type of project: 'fp7', 'h2020', or 'heu'" + ) + data: Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]] = Field( + default=None, + description="The project data" + ) + error: Optional[str] = Field( + default=None, + description="Error message if the request failed" + ) + + class FundingProject(BaseModel): type: ProjectType = Field( description="The type of the project.", diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 777e51de..4cd2812a 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -22,13 +22,16 @@ from inse.projects.model import ( ProjectsSortBy, SortDirection, ) - +from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails from inse.models.cordis_eu_project import CordisEuProject from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex - +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails +from typing import Union settings = get_settings() logger = logging.getLogger(__name__) @@ -559,22 +562,21 @@ def get_cordis_eu_projects_by_project_ids( def get_eu_cordis_projects_by_id( - project_ids: List[str], -) -> CordisEuProject: - query = {"bool": {"filter": [{"term": {"id": project_ids}}]}} - - response = elasticsearch.search( - query=query, - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - cluster=ESCluster.INSE, + project_id: str, +) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: + """ + Fetches and enriches a single Cordis EU project by its ID. + + Args: + project_id: The project ID to fetch + + Returns: + The enriched project details, or None if not found + """ + enriched_project = get_enriched_cordis_project_by_id( + project_id=project_id ) - - hits = response.get("hits", {}).get("hits", []) - if hits: - hit = hits[0] - return CordisEuProject.model_validate(hit["_source"]) - return None - + return enriched_project # DFG diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 20d655ff..7aa1cddb 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -15,7 +15,7 @@ from inse.projects.model import ( ProjectsFilteringProperties, ProjectsSortBy, SortDirection, - CordisEuProject + EuCordisProjectResponse ) from inse.models.dfg_project_details import DfgProjectDetails from inse.models.bund_project_details import BundProjectDetails @@ -27,6 +27,11 @@ from inse.institutions.institutions_search_client import ( ) from inse.institutions.router import get_institutions_search_client +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails +from typing import Union + logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS]) @@ -140,19 +145,76 @@ def get_single_bund_project( responses={ status.HTTP_200_OK: { "description": "Successful Response", - "model": CordisEuProject, + "model": EuCordisProjectResponse, }, - status.HTTP_404_NOT_FOUND: {"description": "Project not found"}, + status.HTTP_404_NOT_FOUND: { + "description": "Project not found", + "model": EuCordisProjectResponse + }, + status.HTTP_500_INTERNAL_SERVER_ERROR: { + "description": "Internal server error", + "model": EuCordisProjectResponse + } }, - response_model_by_alias=False, ) + + def get_single_eu_cordis_project( id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")], -) -> CordisEuProject: +) -> EuCordisProjectResponse: + """ + Get a single EU Cordis project by ID. + Returns a wrapper response containing the project data or error information. + """ logger.debug(f"Received request to get single EU Cordis project for id={id}") - return projects_service.get_single_eu_cordis_project( - project_id=id, - ) + + try: + # Get the project from the service + project = projects_service.get_single_eu_cordis_project(project_id=id) + + # Check if project exists + if project is None: + logger.warning(f"Project with ID {id} not found") + return EuCordisProjectResponse( + success=False, + project_type=None, + data=None, + error=f"Project with ID {id} not found" + ) + + # Determine the project type + if isinstance(project, Fp7ProjectDetails): + project_type = "fp7" + elif isinstance(project, H2020ProjectDetails): + project_type = "h2020" + elif isinstance(project, HEUProjectDetails): + project_type = "heu" + else: + # Unknown project type - maybe it's the base CordisEuProject + logger.warning(f"Unknown project type for ID {id}: {type(project)}") + return EuCordisProjectResponse( + success=False, + project_type=None, + data=None, + error=f"Unknown project type for ID {id}" + ) + + # Return success with the project data + return EuCordisProjectResponse( + success=True, + project_type=project_type, + data=project, + error=None + ) + + except Exception as e: + logger.error(f"Error retrieving project with ID {id}: {str(e)}", exc_info=True) + return EuCordisProjectResponse( + success=False, + project_type=None, + data=None, + error=f"Internal server error: {str(e)}" + ) @router.get( "/institution/bund/funding-over-time", diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index bf756cd0..955d8289 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -27,7 +27,10 @@ from inse.institutions.institutions_search_client import ( from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id from inse.works.logic import get_publication_dois_of_author - +from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails +from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails +from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails +from typing import Union logger = logging.getLogger(__name__) @@ -325,7 +328,7 @@ def get_single_bund_project( def get_single_eu_cordis_project( project_id: str, -) -> CordisEuProject: +) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: logger.debug(f"Fetching single EU Cordis project for id={project_id}") project = projects_search_client.get_eu_cordis_projects_by_id(project_id) From 70fe8ce14fca2f07d61d29998e7031a0f05822dc Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:08:00 +0200 Subject: [PATCH 17/81] generated frontend models and interfaces --- webapp/src/app/api/api/projects.service.ts | 107 +++++++++++++++++- webapp/src/app/api/model/data.ts | 73 ++++++++++++ webapp/src/app/api/model/eccontribution.ts | 14 +++ webapp/src/app/api/model/ecmaxcontribution.ts | 14 +++ .../src/app/api/model/ecmaxcontribution1.ts | 14 +++ .../app/api/model/euCordisProjectResponse.ts | 25 ++++ webapp/src/app/api/model/fp7EurosciVoc.ts | 23 ++++ webapp/src/app/api/model/fp7LegalBasis.ts | 22 ++++ webapp/src/app/api/model/fp7Organization.ts | 46 ++++++++ webapp/src/app/api/model/fp7ProjectDetails.ts | 60 ++++++++++ webapp/src/app/api/model/fp7ProjectIPR.ts | 36 ++++++ webapp/src/app/api/model/fp7Publication.ts | 35 ++++++ webapp/src/app/api/model/fp7ReportSummary.ts | 24 ++++ webapp/src/app/api/model/fp7Topic.ts | 21 ++++ webapp/src/app/api/model/fp7WebLink.ts | 27 +++++ webapp/src/app/api/model/h2020Deliverable.ts | 25 ++++ webapp/src/app/api/model/h2020ErcPI.ts | 25 ++++ webapp/src/app/api/model/h2020EurosciVoc.ts | 23 ++++ webapp/src/app/api/model/h2020LegalBasis.ts | 22 ++++ webapp/src/app/api/model/h2020Organization.ts | 46 ++++++++ .../src/app/api/model/h2020ProjectDetails.ts | 63 +++++++++++ webapp/src/app/api/model/h2020Publication.ts | 35 ++++++ .../src/app/api/model/h2020ReportSummary.ts | 24 ++++ webapp/src/app/api/model/h2020Topic.ts | 21 ++++ webapp/src/app/api/model/h2020WebLink.ts | 27 +++++ webapp/src/app/api/model/hEUDeliverable.ts | 25 ++++ webapp/src/app/api/model/hEUEurosciVoc.ts | 23 ++++ webapp/src/app/api/model/hEULegalBasis.ts | 22 ++++ webapp/src/app/api/model/hEUOrganization.ts | 46 ++++++++ webapp/src/app/api/model/hEUProjectDetails.ts | 60 ++++++++++ webapp/src/app/api/model/hEUPublication.ts | 35 ++++++ webapp/src/app/api/model/hEUReportSummary.ts | 24 ++++ webapp/src/app/api/model/hEUTopic.ts | 21 ++++ webapp/src/app/api/model/hEUWebLink.ts | 27 +++++ webapp/src/app/api/model/models.ts | 34 ++++++ webapp/src/app/api/model/neteccontribution.ts | 14 +++ webapp/src/app/api/model/totalcost.ts | 14 +++ 37 files changed, 1195 insertions(+), 2 deletions(-) create mode 100644 webapp/src/app/api/model/data.ts create mode 100644 webapp/src/app/api/model/eccontribution.ts create mode 100644 webapp/src/app/api/model/ecmaxcontribution.ts create mode 100644 webapp/src/app/api/model/ecmaxcontribution1.ts create mode 100644 webapp/src/app/api/model/euCordisProjectResponse.ts create mode 100644 webapp/src/app/api/model/fp7EurosciVoc.ts create mode 100644 webapp/src/app/api/model/fp7LegalBasis.ts create mode 100644 webapp/src/app/api/model/fp7Organization.ts create mode 100644 webapp/src/app/api/model/fp7ProjectDetails.ts create mode 100644 webapp/src/app/api/model/fp7ProjectIPR.ts create mode 100644 webapp/src/app/api/model/fp7Publication.ts create mode 100644 webapp/src/app/api/model/fp7ReportSummary.ts create mode 100644 webapp/src/app/api/model/fp7Topic.ts create mode 100644 webapp/src/app/api/model/fp7WebLink.ts create mode 100644 webapp/src/app/api/model/h2020Deliverable.ts create mode 100644 webapp/src/app/api/model/h2020ErcPI.ts create mode 100644 webapp/src/app/api/model/h2020EurosciVoc.ts create mode 100644 webapp/src/app/api/model/h2020LegalBasis.ts create mode 100644 webapp/src/app/api/model/h2020Organization.ts create mode 100644 webapp/src/app/api/model/h2020ProjectDetails.ts create mode 100644 webapp/src/app/api/model/h2020Publication.ts create mode 100644 webapp/src/app/api/model/h2020ReportSummary.ts create mode 100644 webapp/src/app/api/model/h2020Topic.ts create mode 100644 webapp/src/app/api/model/h2020WebLink.ts create mode 100644 webapp/src/app/api/model/hEUDeliverable.ts create mode 100644 webapp/src/app/api/model/hEUEurosciVoc.ts create mode 100644 webapp/src/app/api/model/hEULegalBasis.ts create mode 100644 webapp/src/app/api/model/hEUOrganization.ts create mode 100644 webapp/src/app/api/model/hEUProjectDetails.ts create mode 100644 webapp/src/app/api/model/hEUPublication.ts create mode 100644 webapp/src/app/api/model/hEUReportSummary.ts create mode 100644 webapp/src/app/api/model/hEUTopic.ts create mode 100644 webapp/src/app/api/model/hEUWebLink.ts create mode 100644 webapp/src/app/api/model/neteccontribution.ts create mode 100644 webapp/src/app/api/model/totalcost.ts diff --git a/webapp/src/app/api/api/projects.service.ts b/webapp/src/app/api/api/projects.service.ts index 45e35a5a..c69e39c9 100644 --- a/webapp/src/app/api/api/projects.service.ts +++ b/webapp/src/app/api/api/projects.service.ts @@ -27,14 +27,14 @@ import { BundProjectDetails } from '../model/bundProjectDetails'; // @ts-ignore import { BundProjectPage } from '../model/bundProjectPage'; // @ts-ignore -import { CordisEuProject } from '../model/cordisEuProject'; -// @ts-ignore import { CordisEuProjectPage } from '../model/cordisEuProjectPage'; // @ts-ignore import { DfgProjectDetails } from '../model/dfgProjectDetails'; // @ts-ignore import { DfgProjectPage } from '../model/dfgProjectPage'; // @ts-ignore +import { EuCordisProjectResponse } from '../model/euCordisProjectResponse'; +// @ts-ignore import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage'; // @ts-ignore import { FundingProjectPage } from '../model/fundingProjectPage'; @@ -760,6 +760,109 @@ export class ProjectsService extends BaseService { ); } + /** + * Get a single EU Cordis project. + * Returns a single EU Cordis project based on its ID. + * @endpoint get /api/projects/eu/{id} + * @param id The ID of the EU Cordis project to retrieve. + * @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 getSingleEuCordisProject( + id: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getSingleEuCordisProject( + id: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSingleEuCordisProject( + id: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getSingleEuCordisProject( + 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 getSingleEuCordisProject.', + ); + } + + 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/projects/eu/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + 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 bund projects. * Returns a page of bund projects based on the provided pagination parameters and optional institution filter. diff --git a/webapp/src/app/api/model/data.ts b/webapp/src/app/api/model/data.ts new file mode 100644 index 00000000..cfd77d9c --- /dev/null +++ b/webapp/src/app/api/model/data.ts @@ -0,0 +1,73 @@ +/** + * 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 { Totalcost } from './totalcost'; +import { H2020ProjectDetails } from './h2020ProjectDetails'; +import { Ecmaxcontribution } from './ecmaxcontribution'; +import { Fp7ProjectDetails } from './fp7ProjectDetails'; +import { HEUOrganization } from './hEUOrganization'; +import { HEUPublication } from './hEUPublication'; +import { Fp7WebLink } from './fp7WebLink'; +import { HEUWebLink } from './hEUWebLink'; +import { HEUDeliverable } from './hEUDeliverable'; +import { Fp7ProjectIPR } from './fp7ProjectIPR'; +import { HEUEurosciVoc } from './hEUEurosciVoc'; +import { H2020ErcPI } from './h2020ErcPI'; +import { HEULegalBasis } from './hEULegalBasis'; +import { HEUTopic } from './hEUTopic'; +import { Fp7ReportSummary } from './fp7ReportSummary'; +import { HEUReportSummary } from './hEUReportSummary'; +import { HEUProjectDetails } from './hEUProjectDetails'; + + +/** + * The project data + */ +export interface Data { + acronym?: string; + contentUpdateDate?: string; + ecMaxContribution?: Ecmaxcontribution | null; + ecSignatureDate?: string; + endDate?: string; + frameworkProgramme?: string; + fundingScheme?: string; + grantDoi?: string; + humanValidated?: boolean; + id?: string; + keywords?: string; + legalBasis?: string; + masterCall?: string; + nature?: string; + objective?: string; + rcn?: string; + startDate?: string; + status?: string; + subCall?: string; + title?: string; + topics?: string; + totalCost?: Totalcost | null; + organizations?: Array; + publications?: Array; + iprs?: Array; + report_summaries?: Array; + topicsList?: Array; + web_links?: Array; + eurosciVoc?: Array; + legalBasisList?: Array; + organizationCount?: number; + publicationCount?: number; + iprCount?: number; + deliverables?: Array; + reportSummaries?: Array; + webLinks?: Array; + ercPrincipalInvestigators?: Array; + deliverableCount?: number; + ercPiCount?: number; +} + diff --git a/webapp/src/app/api/model/eccontribution.ts b/webapp/src/app/api/model/eccontribution.ts new file mode 100644 index 00000000..a93cc6ea --- /dev/null +++ b/webapp/src/app/api/model/eccontribution.ts @@ -0,0 +1,14 @@ +/** + * 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 Eccontribution { +} + diff --git a/webapp/src/app/api/model/ecmaxcontribution.ts b/webapp/src/app/api/model/ecmaxcontribution.ts new file mode 100644 index 00000000..5ed2a74c --- /dev/null +++ b/webapp/src/app/api/model/ecmaxcontribution.ts @@ -0,0 +1,14 @@ +/** + * 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 Ecmaxcontribution { +} + diff --git a/webapp/src/app/api/model/ecmaxcontribution1.ts b/webapp/src/app/api/model/ecmaxcontribution1.ts new file mode 100644 index 00000000..cc59333d --- /dev/null +++ b/webapp/src/app/api/model/ecmaxcontribution1.ts @@ -0,0 +1,14 @@ +/** + * 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 Ecmaxcontribution1 { +} + diff --git a/webapp/src/app/api/model/euCordisProjectResponse.ts b/webapp/src/app/api/model/euCordisProjectResponse.ts new file mode 100644 index 00000000..47bc1b53 --- /dev/null +++ b/webapp/src/app/api/model/euCordisProjectResponse.ts @@ -0,0 +1,25 @@ +/** + * 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 { Data } from './data'; + + +/** + * Response model for EU Cordis project endpoints. + */ +export interface EuCordisProjectResponse { + /** + * Indicates if the request was successful + */ + success: boolean; + project_type?: string | null; + data?: Data | null; + error?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7EurosciVoc.ts b/webapp/src/app/api/model/fp7EurosciVoc.ts new file mode 100644 index 00000000..fb7e8deb --- /dev/null +++ b/webapp/src/app/api/model/fp7EurosciVoc.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Fp7EurosciVoc + */ +export interface Fp7EurosciVoc { + code?: string | null; + description?: string | null; + id?: string | null; + path?: string | null; + projectID?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7LegalBasis.ts b/webapp/src/app/api/model/fp7LegalBasis.ts new file mode 100644 index 00000000..89a05742 --- /dev/null +++ b/webapp/src/app/api/model/fp7LegalBasis.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. + */ + + +/** + * Fp7LegalBasis + */ +export interface Fp7LegalBasis { + id?: string | null; + legalBasis?: string | null; + projectID?: string | null; + title?: string | null; + uniqueProgrammePart?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7Organization.ts b/webapp/src/app/api/model/fp7Organization.ts new file mode 100644 index 00000000..32053ea5 --- /dev/null +++ b/webapp/src/app/api/model/fp7Organization.ts @@ -0,0 +1,46 @@ +/** + * 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 { Neteccontribution } from './neteccontribution'; +import { Totalcost } from './totalcost'; +import { Eccontribution } from './eccontribution'; + + +/** + * Fp7Organization + */ +export interface Fp7Organization { + SME?: boolean | null; + active?: boolean | null; + activityType?: string | null; + city?: string | null; + contactForm?: string | null; + contentUpdateDate?: string | null; + country?: string | null; + ecContribution?: Eccontribution | null; + endOfParticipation?: boolean | null; + geolocation?: string | null; + id?: string | null; + name?: string | null; + netEcContribution?: Neteccontribution | null; + nutsCode?: string | null; + order?: number | null; + organisationID?: string | null; + organizationURL?: string | null; + postCode?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + role?: string | null; + shortName?: string | null; + street?: string | null; + totalCost?: Totalcost | null; + vatNumber?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7ProjectDetails.ts b/webapp/src/app/api/model/fp7ProjectDetails.ts new file mode 100644 index 00000000..3c79edb4 --- /dev/null +++ b/webapp/src/app/api/model/fp7ProjectDetails.ts @@ -0,0 +1,60 @@ +/** + * 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 { Fp7EurosciVoc } from './fp7EurosciVoc'; +import { Totalcost } from './totalcost'; +import { Ecmaxcontribution } from './ecmaxcontribution'; +import { Fp7WebLink } from './fp7WebLink'; +import { Fp7Publication } from './fp7Publication'; +import { Fp7ReportSummary } from './fp7ReportSummary'; +import { Fp7Topic } from './fp7Topic'; +import { Fp7ProjectIPR } from './fp7ProjectIPR'; +import { Fp7Organization } from './fp7Organization'; +import { Fp7LegalBasis } from './fp7LegalBasis'; + + +/** + * Comprehensive FP7 Project model combining all related entities. This model extends the base Fp7Project with all associated data. + */ +export interface Fp7ProjectDetails { + acronym?: string | null; + contentUpdateDate?: string | null; + ecMaxContribution?: Ecmaxcontribution | null; + ecSignatureDate?: string | null; + endDate?: string | null; + frameworkProgramme?: string | null; + fundingScheme?: string | null; + grantDoi?: string | null; + humanValidated?: boolean | null; + id?: string | null; + keywords?: string | null; + legalBasis?: string | null; + masterCall?: string | null; + nature?: string | null; + objective?: string | null; + rcn?: string | null; + startDate?: string | null; + status?: string | null; + subCall?: string | null; + title?: string | null; + topics?: string | null; + totalCost?: Totalcost | null; + organizations?: Array | null; + publications?: Array | null; + iprs?: Array | null; + report_summaries?: Array | null; + topicsList?: Array | null; + web_links?: Array | null; + eurosciVoc?: Array | null; + legalBasisList?: Array | null; + organizationCount?: number | null; + publicationCount?: number | null; + iprCount?: number | null; +} + diff --git a/webapp/src/app/api/model/fp7ProjectIPR.ts b/webapp/src/app/api/model/fp7ProjectIPR.ts new file mode 100644 index 00000000..f35487c4 --- /dev/null +++ b/webapp/src/app/api/model/fp7ProjectIPR.ts @@ -0,0 +1,36 @@ +/** + * 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. + */ + + +/** + * Fp7ProjectIPR + */ +export interface Fp7ProjectIPR { + applicantName?: string | null; + applicationDate?: string | null; + applicationIdentifier?: string | null; + applicationKind?: string | null; + applicationPrefix?: string | null; + awardDate?: string | null; + awardIdentifier?: string | null; + awardKind?: string | null; + awardPrefix?: string | null; + epoAppUrl?: string | null; + epoPubUrl?: string | null; + id?: string | null; + organisationID?: string | null; + patentFamilyIdentifier?: string | null; + patentType?: string | null; + priorityDate?: string | null; + projectID?: string | null; + title?: string | null; + type?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7Publication.ts b/webapp/src/app/api/model/fp7Publication.ts new file mode 100644 index 00000000..fd0e2491 --- /dev/null +++ b/webapp/src/app/api/model/fp7Publication.ts @@ -0,0 +1,35 @@ +/** + * 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. + */ + + +/** + * Fp7Publication + */ +export interface Fp7Publication { + authors?: string | null; + collection?: string | null; + contentUpdateDate?: string | null; + doi?: string | null; + id?: string | null; + isPublishedAs?: string | null; + journalNumber?: string | null; + journalTitle?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + publishedPages?: string | null; + publishedYear?: number | null; + publisher?: string | null; + qaProcessedDoi?: string | null; + rcn?: string | null; + repositoryUrl?: string | null; + title?: string | null; + volume?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7ReportSummary.ts b/webapp/src/app/api/model/fp7ReportSummary.ts new file mode 100644 index 00000000..f0413439 --- /dev/null +++ b/webapp/src/app/api/model/fp7ReportSummary.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Fp7ReportSummary + */ +export interface Fp7ReportSummary { + attachments?: string | null; + contentUpdateDate?: string | null; + id?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7Topic.ts b/webapp/src/app/api/model/fp7Topic.ts new file mode 100644 index 00000000..f39a021e --- /dev/null +++ b/webapp/src/app/api/model/fp7Topic.ts @@ -0,0 +1,21 @@ +/** + * 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. + */ + + +/** + * Fp7Topic + */ +export interface Fp7Topic { + id?: string | null; + projectID?: string | null; + title?: string | null; + topic?: string | null; +} + diff --git a/webapp/src/app/api/model/fp7WebLink.ts b/webapp/src/app/api/model/fp7WebLink.ts new file mode 100644 index 00000000..eeaff7ab --- /dev/null +++ b/webapp/src/app/api/model/fp7WebLink.ts @@ -0,0 +1,27 @@ +/** + * 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. + */ + + +/** + * Fp7WebLink + */ +export interface Fp7WebLink { + archivedDate?: string | null; + availableLanguages?: string | null; + id?: string | null; + linkId?: string | null; + projectID?: string | null; + represents?: string | null; + source?: string | null; + status?: string | null; + type?: string | null; + url?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020Deliverable.ts b/webapp/src/app/api/model/h2020Deliverable.ts new file mode 100644 index 00000000..390d2c7a --- /dev/null +++ b/webapp/src/app/api/model/h2020Deliverable.ts @@ -0,0 +1,25 @@ +/** + * 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. + */ + + +/** + * H2020Deliverable + */ +export interface H2020Deliverable { + collection?: string | null; + contentUpdateDate?: string | null; + deliverableType?: string | null; + description?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + url?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020ErcPI.ts b/webapp/src/app/api/model/h2020ErcPI.ts new file mode 100644 index 00000000..48ae3ff0 --- /dev/null +++ b/webapp/src/app/api/model/h2020ErcPI.ts @@ -0,0 +1,25 @@ +/** + * 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. + */ + + +/** + * H2020ErcPI + */ +export interface H2020ErcPI { + firstName?: string | null; + fundingScheme?: string | null; + id?: string | null; + lastName?: string | null; + organisationID?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020EurosciVoc.ts b/webapp/src/app/api/model/h2020EurosciVoc.ts new file mode 100644 index 00000000..7d1ea931 --- /dev/null +++ b/webapp/src/app/api/model/h2020EurosciVoc.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * H2020EurosciVoc + */ +export interface H2020EurosciVoc { + code?: string | null; + description?: string | null; + id?: string | null; + path?: string | null; + projectID?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020LegalBasis.ts b/webapp/src/app/api/model/h2020LegalBasis.ts new file mode 100644 index 00000000..d247488d --- /dev/null +++ b/webapp/src/app/api/model/h2020LegalBasis.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. + */ + + +/** + * H2020LegalBasis + */ +export interface H2020LegalBasis { + id?: string | null; + legalBasis?: string | null; + projectID?: string | null; + title?: string | null; + uniqueProgrammePart?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020Organization.ts b/webapp/src/app/api/model/h2020Organization.ts new file mode 100644 index 00000000..bb832216 --- /dev/null +++ b/webapp/src/app/api/model/h2020Organization.ts @@ -0,0 +1,46 @@ +/** + * 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 { Neteccontribution } from './neteccontribution'; +import { Totalcost } from './totalcost'; +import { Eccontribution } from './eccontribution'; + + +/** + * H2020Organization + */ +export interface H2020Organization { + SME?: boolean | null; + active?: boolean | null; + activityType?: string | null; + city?: string | null; + contactForm?: string | null; + contentUpdateDate?: string | null; + country?: string | null; + ecContribution?: Eccontribution | null; + endOfParticipation?: boolean | null; + geolocation?: string | null; + id?: string | null; + name?: string | null; + netEcContribution?: Neteccontribution | null; + nutsCode?: string | null; + order?: number | null; + organisationID?: string | null; + organizationURL?: string | null; + postCode?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + role?: string | null; + shortName?: string | null; + street?: string | null; + totalCost?: Totalcost | null; + vatNumber?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020ProjectDetails.ts b/webapp/src/app/api/model/h2020ProjectDetails.ts new file mode 100644 index 00000000..39172950 --- /dev/null +++ b/webapp/src/app/api/model/h2020ProjectDetails.ts @@ -0,0 +1,63 @@ +/** + * 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 { Totalcost } from './totalcost'; +import { Ecmaxcontribution } from './ecmaxcontribution'; +import { H2020LegalBasis } from './h2020LegalBasis'; +import { H2020ErcPI } from './h2020ErcPI'; +import { H2020Deliverable } from './h2020Deliverable'; +import { H2020WebLink } from './h2020WebLink'; +import { H2020Publication } from './h2020Publication'; +import { H2020ReportSummary } from './h2020ReportSummary'; +import { H2020Topic } from './h2020Topic'; +import { H2020EurosciVoc } from './h2020EurosciVoc'; +import { H2020Organization } from './h2020Organization'; + + +/** + * Comprehensive Horizon 2020 Project model combining all related entities. This model extends the base H2020Project with all associated data. + */ +export interface H2020ProjectDetails { + acronym?: string | null; + contentUpdateDate?: string | null; + ecMaxContribution?: Ecmaxcontribution | null; + ecSignatureDate?: string | null; + endDate?: string | null; + frameworkProgramme?: string | null; + fundingScheme?: string | null; + grantDoi?: string | null; + humanValidated?: boolean | null; + id?: string | null; + keywords?: string | null; + legalBasis?: string | null; + masterCall?: string | null; + nature?: string | null; + objective?: string | null; + rcn?: string | null; + startDate?: string | null; + status?: string | null; + subCall?: string | null; + title?: string | null; + topics?: string | null; + totalCost?: Totalcost | null; + organizations?: Array | null; + publications?: Array | null; + deliverables?: Array | null; + reportSummaries?: Array | null; + topicsList?: Array | null; + webLinks?: Array | null; + eurosciVoc?: Array | null; + legalBasisList?: Array | null; + ercPrincipalInvestigators?: Array | null; + organizationCount?: number | null; + publicationCount?: number | null; + deliverableCount?: number | null; + ercPiCount?: number | null; +} + diff --git a/webapp/src/app/api/model/h2020Publication.ts b/webapp/src/app/api/model/h2020Publication.ts new file mode 100644 index 00000000..945e22d2 --- /dev/null +++ b/webapp/src/app/api/model/h2020Publication.ts @@ -0,0 +1,35 @@ +/** + * 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. + */ + + +/** + * H2020Publication + */ +export interface H2020Publication { + authors?: string | null; + collection?: string | null; + contentUpdateDate?: string | null; + doi?: string | null; + id?: string | null; + isPublishedAs?: string | null; + journalNumber?: string | null; + journalTitle?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + publishedPages?: string | null; + publishedYear?: number | null; + publisher?: string | null; + qaProcessedDoi?: string | null; + rcn?: string | null; + repositoryUrl?: string | null; + title?: string | null; + volume?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020ReportSummary.ts b/webapp/src/app/api/model/h2020ReportSummary.ts new file mode 100644 index 00000000..a5975ffb --- /dev/null +++ b/webapp/src/app/api/model/h2020ReportSummary.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * H2020ReportSummary + */ +export interface H2020ReportSummary { + attachments?: string | null; + contentUpdateDate?: string | null; + id?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020Topic.ts b/webapp/src/app/api/model/h2020Topic.ts new file mode 100644 index 00000000..8ddb1991 --- /dev/null +++ b/webapp/src/app/api/model/h2020Topic.ts @@ -0,0 +1,21 @@ +/** + * 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. + */ + + +/** + * H2020Topic + */ +export interface H2020Topic { + id?: string | null; + projectID?: string | null; + title?: string | null; + topic?: string | null; +} + diff --git a/webapp/src/app/api/model/h2020WebLink.ts b/webapp/src/app/api/model/h2020WebLink.ts new file mode 100644 index 00000000..26d54599 --- /dev/null +++ b/webapp/src/app/api/model/h2020WebLink.ts @@ -0,0 +1,27 @@ +/** + * 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. + */ + + +/** + * H2020WebLink + */ +export interface H2020WebLink { + archivedDate?: string | null; + availableLanguages?: string | null; + id?: string | null; + linkId?: string | null; + projectID?: string | null; + represents?: string | null; + source?: string | null; + status?: string | null; + type?: string | null; + url?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUDeliverable.ts b/webapp/src/app/api/model/hEUDeliverable.ts new file mode 100644 index 00000000..05d8c5ba --- /dev/null +++ b/webapp/src/app/api/model/hEUDeliverable.ts @@ -0,0 +1,25 @@ +/** + * 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. + */ + + +/** + * HEUDeliverable + */ +export interface HEUDeliverable { + collection?: string | null; + contentUpdateDate?: string | null; + deliverableType?: string | null; + description?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + url?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUEurosciVoc.ts b/webapp/src/app/api/model/hEUEurosciVoc.ts new file mode 100644 index 00000000..93921ab7 --- /dev/null +++ b/webapp/src/app/api/model/hEUEurosciVoc.ts @@ -0,0 +1,23 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * HEUEurosciVoc + */ +export interface HEUEurosciVoc { + code?: string | null; + description?: string | null; + id?: string | null; + path?: string | null; + projectID?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/hEULegalBasis.ts b/webapp/src/app/api/model/hEULegalBasis.ts new file mode 100644 index 00000000..e3cb66ca --- /dev/null +++ b/webapp/src/app/api/model/hEULegalBasis.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. + */ + + +/** + * HEULegalBasis + */ +export interface HEULegalBasis { + id?: string | null; + legalBasis?: string | null; + projectID?: string | null; + title?: string | null; + uniqueProgrammePart?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUOrganization.ts b/webapp/src/app/api/model/hEUOrganization.ts new file mode 100644 index 00000000..65b365aa --- /dev/null +++ b/webapp/src/app/api/model/hEUOrganization.ts @@ -0,0 +1,46 @@ +/** + * 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 { Neteccontribution } from './neteccontribution'; +import { Totalcost } from './totalcost'; +import { Eccontribution } from './eccontribution'; + + +/** + * HEUOrganization + */ +export interface HEUOrganization { + SME?: boolean | null; + active?: boolean | null; + activityType?: string | null; + city?: string | null; + contactForm?: string | null; + contentUpdateDate?: string | null; + country?: string | null; + ecContribution?: Eccontribution | null; + endOfParticipation?: boolean | null; + geolocation?: string | null; + id?: string | null; + name?: string | null; + netEcContribution?: Neteccontribution | null; + nutsCode?: string | null; + order?: number | null; + organisationID?: string | null; + organizationURL?: string | null; + postCode?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + role?: string | null; + shortName?: string | null; + street?: string | null; + totalCost?: Totalcost | null; + vatNumber?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUProjectDetails.ts b/webapp/src/app/api/model/hEUProjectDetails.ts new file mode 100644 index 00000000..2d36478e --- /dev/null +++ b/webapp/src/app/api/model/hEUProjectDetails.ts @@ -0,0 +1,60 @@ +/** + * 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 { Totalcost } from './totalcost'; +import { Ecmaxcontribution } from './ecmaxcontribution'; +import { HEULegalBasis } from './hEULegalBasis'; +import { HEUOrganization } from './hEUOrganization'; +import { HEUTopic } from './hEUTopic'; +import { HEUPublication } from './hEUPublication'; +import { HEUWebLink } from './hEUWebLink'; +import { HEUReportSummary } from './hEUReportSummary'; +import { HEUDeliverable } from './hEUDeliverable'; +import { HEUEurosciVoc } from './hEUEurosciVoc'; + + +/** + * Comprehensive Horizon Europe Project model combining all related entities. This model extends the base HEUProject with all associated data. + */ +export interface HEUProjectDetails { + acronym?: string | null; + contentUpdateDate?: string | null; + ecMaxContribution?: Ecmaxcontribution | null; + ecSignatureDate?: string | null; + endDate?: string | null; + frameworkProgramme?: string | null; + fundingScheme?: string | null; + grantDoi?: string | null; + humanValidated?: boolean | null; + id?: string | null; + keywords?: string | null; + legalBasis?: string | null; + masterCall?: string | null; + nature?: string | null; + objective?: string | null; + rcn?: string | null; + startDate?: string | null; + status?: string | null; + subCall?: string | null; + title?: string | null; + topics?: string | null; + totalCost?: Totalcost | null; + organizations?: Array | null; + publications?: Array | null; + deliverables?: Array | null; + reportSummaries?: Array | null; + topicsList?: Array | null; + webLinks?: Array | null; + eurosciVoc?: Array | null; + legalBasisList?: Array | null; + organizationCount?: number | null; + publicationCount?: number | null; + deliverableCount?: number | null; +} + diff --git a/webapp/src/app/api/model/hEUPublication.ts b/webapp/src/app/api/model/hEUPublication.ts new file mode 100644 index 00000000..4d067177 --- /dev/null +++ b/webapp/src/app/api/model/hEUPublication.ts @@ -0,0 +1,35 @@ +/** + * 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. + */ + + +/** + * HEUPublication + */ +export interface HEUPublication { + authors?: string | null; + collection?: string | null; + contentUpdateDate?: string | null; + doi?: string | null; + id?: string | null; + isPublishedAs?: string | null; + journalNumber?: string | null; + journalTitle?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + publishedPages?: string | null; + publishedYear?: number | null; + publisher?: string | null; + qaProcessedDoi?: string | null; + rcn?: string | null; + repositoryUrl?: string | null; + title?: string | null; + volume?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUReportSummary.ts b/webapp/src/app/api/model/hEUReportSummary.ts new file mode 100644 index 00000000..b9e1a299 --- /dev/null +++ b/webapp/src/app/api/model/hEUReportSummary.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * HEUReportSummary + */ +export interface HEUReportSummary { + attachments?: string | null; + contentUpdateDate?: string | null; + id?: string | null; + projectAcronym?: string | null; + projectID?: string | null; + rcn?: string | null; + title?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUTopic.ts b/webapp/src/app/api/model/hEUTopic.ts new file mode 100644 index 00000000..a0a5e764 --- /dev/null +++ b/webapp/src/app/api/model/hEUTopic.ts @@ -0,0 +1,21 @@ +/** + * 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. + */ + + +/** + * HEUTopic + */ +export interface HEUTopic { + id?: string | null; + projectID?: string | null; + title?: string | null; + topic?: string | null; +} + diff --git a/webapp/src/app/api/model/hEUWebLink.ts b/webapp/src/app/api/model/hEUWebLink.ts new file mode 100644 index 00000000..81c5d60f --- /dev/null +++ b/webapp/src/app/api/model/hEUWebLink.ts @@ -0,0 +1,27 @@ +/** + * 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. + */ + + +/** + * HEUWebLink + */ +export interface HEUWebLink { + archivedDate?: string | null; + availableLanguages?: string | null; + id?: string | null; + linkId?: string | null; + projectID?: string | null; + represents?: string | null; + source?: string | null; + status?: string | null; + type?: string | null; + url?: string | null; +} + diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 89f601cc..6f643388 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -31,6 +31,7 @@ export * from './cordisEuProjectPage'; export * from './costUsd'; export * from './customAuthor'; export * from './customAuthorsListResponse'; +export * from './data'; export * from './dehydratedAuthor'; export * from './dehydratedFunder'; export * from './dehydratedInstitution'; @@ -38,16 +39,47 @@ export * from './dehydratedSource'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './eccontribution'; +export * from './ecmaxcontribution'; +export * from './euCordisProjectResponse'; export * from './euOrganizationProjectSummary'; export * from './euOrganizationProjectSummaryPage'; export * from './filterInformation'; export * from './filterProperties'; +export * from './fp7EurosciVoc'; +export * from './fp7LegalBasis'; +export * from './fp7Organization'; +export * from './fp7ProjectDetails'; +export * from './fp7ProjectIPR'; +export * from './fp7Publication'; +export * from './fp7ReportSummary'; +export * from './fp7Topic'; +export * from './fp7WebLink'; export * from './funderByAuthor'; export * from './fundersByAuthorResponse'; export * from './fundingProject'; export * from './fundingProjectPage'; export * from './fwci'; export * from './groupByResult'; +export * from './h2020Deliverable'; +export * from './h2020ErcPI'; +export * from './h2020EurosciVoc'; +export * from './h2020LegalBasis'; +export * from './h2020Organization'; +export * from './h2020ProjectDetails'; +export * from './h2020Publication'; +export * from './h2020ReportSummary'; +export * from './h2020Topic'; +export * from './h2020WebLink'; +export * from './hEUDeliverable'; +export * from './hEUEurosciVoc'; +export * from './hEULegalBasis'; +export * from './hEUOrganization'; +export * from './hEUProjectDetails'; +export * from './hEUPublication'; +export * from './hEUReportSummary'; +export * from './hEUTopic'; +export * from './hEUWebLink'; export * from './hTTPValidationError'; export * from './identityGrant'; export * from './institution'; @@ -69,6 +101,7 @@ export * from './matchedOfficer'; export * from './mentionedPerson'; export * from './meta'; export * from './model2YrMeanCitedness'; +export * from './neteccontribution'; export * from './newsArticle'; export * from './newsArticleDetail'; export * from './newsPage'; @@ -95,6 +128,7 @@ export * from './topics'; export * from './topicsByTime'; export * from './topicsByYear'; export * from './topicsListResponse'; +export * from './totalcost'; export * from './universityRanking'; export * from './universityTopicData'; export * from './user'; diff --git a/webapp/src/app/api/model/neteccontribution.ts b/webapp/src/app/api/model/neteccontribution.ts new file mode 100644 index 00000000..925189cf --- /dev/null +++ b/webapp/src/app/api/model/neteccontribution.ts @@ -0,0 +1,14 @@ +/** + * 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 Neteccontribution { +} + diff --git a/webapp/src/app/api/model/totalcost.ts b/webapp/src/app/api/model/totalcost.ts new file mode 100644 index 00000000..d4a48a9a --- /dev/null +++ b/webapp/src/app/api/model/totalcost.ts @@ -0,0 +1,14 @@ +/** + * 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 Totalcost { +} + From 52a259a92719e12211ad8d10f9fcc36d089772ef Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:08:49 +0200 Subject: [PATCH 18/81] refactored EU Cordis projects component --- .../eu-details.component.html | 729 +++++++++++++----- .../eu-details.component.scss | 577 ++++++++++++++ .../eu-cordis-details/eu-details.component.ts | 262 +++++-- 3 files changed, 1340 insertions(+), 228 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 2f30b6a0..9a51d3ae 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -12,58 +12,76 @@
EU Projekt + @if (euProject.programType) { + + {{ + euProject.programType === 'fp7' + ? 'FP7' + : euProject.programType === 'h2020' + ? 'H2020' + : euProject.programType === 'heu' + ? 'Horizon Europe' + : '' + }} + + } ID: {{ euProject.id }} - @if (euProject.rcn) { - RCN: {{ euProject.rcn }} - } - @if (euProject.acronym) { - {{ euProject.acronym }} - }

{{ euProject.title || 'Ohne Titel' }}

@if (euProject.frameworkProgramme) {

- Rahmenprogramm: - - {{ getFrameworkDisplay(euProject.frameworkProgramme) }} - + {{ + getFrameworkDisplay(euProject.frameworkProgramme) + }}

}
@if (euProject.status) { -
+
circle {{ getStatusDisplay(euProject.status) }}
} @if (euProject.fundingScheme) { -
+
assignment - {{ getFundingSchemeDisplay(euProject.fundingScheme) }} + {{ + getFundingSchemeDisplay(euProject.fundingScheme) + }}
} @if (euProject.grantDoi) { - + link DOI: {{ euProject.grantDoi }} }
- +
calendar_today
- {{ euProject.startDate || 'N/A' }} - Startdatum + {{ formatDate(euProject.startDate) || 'N/A' }} + Förderbeginn
event_busy
- {{ euProject.endDate || 'N/A' }} - Enddatum + {{ formatDate(euProject.endDate) || 'N/A' }} + Förderende
@@ -91,199 +109,546 @@
} - @if (euProject.masterCall) { + @if (euProject.organizationCount !== undefined) {
- call_split + business
- {{ euProject.masterCall }} - Master Call + {{ euProject.organizationCount }} + Organisationen +
+
+ } + @if (euProject.publicationCount !== undefined) { +
+ description +
+ {{ euProject.publicationCount }} + Publikationen
}
- - @if (euProject.objective) { - -
+ +
+ + @if (euProject.organizations && euProject.organizations.length > 0) { + + } + @if (euProject.publications && euProject.publications.length > 0) { + + } + @if (euProject.iprs && euProject.iprs.length > 0) { + + } + @if (euProject.deliverables && euProject.deliverables.length > 0) { + + } +
+ + +
+ + @if (activeTab === 'overview') { +
+
+
+ @if (euProject.objective) { + +
+ description +

Projektziel

+
+

{{ euProject.objective }}

+
+ } + + @if (getFormattedTopics(euProject.topics).length > 0) { + +
+ topic +

Themen

+ {{ + getFormattedTopics(euProject.topics).length + }} +
+
+ @for ( + topic of getFormattedTopics(euProject.topics); + track topic + ) { +
+ {{ topic }} +
+ } +
+
+ } + + + @if (getKeywords(euProject.keywords).length > 0) { + +
+ tag +

Schlüsselwörter

+ {{ + getKeywords(euProject.keywords).length + }} +
+
+ @for ( + keyword of getKeywords(euProject.keywords); + track keyword + ) { +
+ {{ keyword }} +
+ } +
+
+ } + + + @if (euProject.eurosciVoc && euProject.eurosciVoc.length > 0) { + +
+ science +

EuroSciVoc

+ {{ + euProject.eurosciVoc.length + }} +
+
+ @for (voc of euProject.eurosciVoc; track voc.id) { +
+ {{ voc.code }} + {{ voc.title }} +
+ } +
+
+ } +
+ + +
-

{{ euProject.objective }}

- - } + } -
-
- - @if (euProject.topics) { + + @if (activeTab === 'organizations' && euProject.organizations) { +
- topic -

Themen

- {{ getFormattedTopics(euProject.topics).length }} + business +

Organisationen ({{ euProject.organizations.length }})

-
- @for (topic of getFormattedTopics(euProject.topics); track topic) { -
- {{ topic }} - search +
+ @for (org of euProject.organizations; track org.organisationID) { +
+
{{ getInitials(org.name) }}
+
+
+ {{ + org.name || org.shortName || 'Unbekannte Organisation' + }} +
+
+ @if (org.shortName) { + {{ org.shortName }} + } + @if (org.role) { + {{ org.role }} + } + @if (org.country) { + {{ org.country }} + } + @if (org.sme) { + SME + } + @if (org.city) { + {{ org.city }} + } +
+
+ @if (org.ecContribution) { +
+ EU-Beitrag: + {{ + formatCurrency(org.ecContribution) + }} +
+ } + @if (org.totalCost) { +
+ Kosten: + {{ + formatCurrency(org.totalCost) + }} +
+ }
}
- } +
+ } - - @if (getKeywords(euProject.keywords).length > 0) { + + @if (activeTab === 'publications' && euProject.publications) { +
- tag -

Schlüsselwörter

- {{ getKeywords(euProject.keywords).length }} + description +

Publikationen ({{ euProject.publications.length }})

-
- @for (keyword of getKeywords(euProject.keywords); track keyword) { -
- {{ keyword }} - search +
+ @for (pub of euProject.publications; track pub.doi) { +
+
+ article +
+
+
{{ pub.title || 'Kein Titel' }}
+
+ {{ pub.authors || 'Autoren unbekannt' }} +
+
+ @if (pub.journalTitle) { + {{ pub.journalTitle }} + } + @if (pub.publishedYear) { + ({{ pub.publishedYear }}) + } + @if (pub.publisher) { + {{ pub.publisher }} + } +
+
+
+ @if (pub.doi) { + + open_in_new + + } + @if (pub.repositoryUrl) { + + folder_open + + } +
}
- } -
+
+ } -
+ } - - -
- schedule -

Zeitliche Übersicht

-
-
-
-
Startdatum
-
{{ euProject.startDate || 'N/A' }}
+ + @if (activeTab === 'deliverables' && euProject.deliverables) { +
+ +
+ assignment +

Deliverables ({{ euProject.deliverables.length }})

-
-
Enddatum
-
{{ euProject.endDate || 'N/A' }}
+
+ @for (deliv of euProject.deliverables; track deliv.url) { +
+
+ file_present +
+
+
+ {{ deliv.description || 'Ohne Beschreibung' }} +
+
+ @if (deliv.deliverableType) { + {{ + deliv.deliverableType + }} + } + @if (deliv.url) { + + open_in_new + Zum Deliverable + + } +
+
+
+ }
- @if (euProject.ecSignatureDate) { -
-
EU-Unterzeichnung
-
{{ euProject.ecSignatureDate }}
-
- } - @if (euProject.contentUpdateDate) { -
-
Letzte Aktualisierung
-
{{ euProject.contentUpdateDate }}
-
- } - @if (euProject.grantDoi) { - - } -
-
- + +
+ } } @else {
@@ -293,4 +658,4 @@
} - \ No newline at end of file + diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss index 4a26295b..bbb60de8 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -616,4 +616,581 @@ h1 { width: 100%; justify-content: center; } +} +// Add these to your existing SCSS file + +// Program badges +.program-badge { + display: inline-block; + padding: 4px 12px; + border-radius: var(--sg-radius-sm); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.5px; + + &.fp7 { + background: #e8eaf6; + color: #283593; + } + + &.h2020 { + background: #e3f2fd; + color: #0d47a1; + } + + &.heu { + background: #e8f5e9; + color: #1b5e20; + } +} + +// Tabs +.tabs-container { + display: flex; + gap: 4px; + padding: 0 4px; + margin-bottom: 24px; + background: #f8fafc; + border-radius: var(--sg-radius-md); + border: 1px solid #d9e2f0; + overflow-x: auto; +} + +.tab-btn { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + background: transparent; + border: none; + border-radius: var(--sg-radius-sm); + color: var(--sg-text-muted); + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; + white-space: nowrap; + + &:hover { + background: rgba(0, 0, 0, 0.04); + color: var(--sg-text); + } + + &.active { + background: #fff; + color: var(--sg-primary, #0066cc); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); + } + + mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.tab-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 20px; + height: 20px; + padding: 0 6px; + background: #e8edf5; + border-radius: 10px; + color: var(--sg-text-muted); + font-size: 11px; + font-weight: 600; +} + +.tab-content { + animation: fadeIn 0.3s ease; +} + +@keyframes fadeIn { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } +} + +// Organizations +.organizations-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.organization-item { + display: flex; + align-items: center; + gap: 16px; + padding: 14px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + cursor: pointer; + transition: all 0.2s; + + &:hover { + background: #f8fafc; + border-color: #b8c5d6; + transform: translateY(-1px); + } +} + +.org-avatar { + display: flex; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; + flex-shrink: 0; + background: #e8edf5; + border-radius: 50%; + color: var(--sg-text); + font-weight: 600; + font-size: 14px; +} + +.org-info { + flex: 1; + min-width: 0; +} + +.org-name { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} + +.org-details { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 12px; + color: var(--sg-text-muted); + + .org-short { + font-weight: 500; + color: var(--sg-text); + } + + .org-role { + padding: 1px 8px; + background: #e8edf5; + border-radius: var(--sg-radius-sm); + color: var(--sg-text); + } + + .org-country { + padding: 1px 8px; + background: #e3f2fd; + border-radius: var(--sg-radius-sm); + color: #0d47a1; + } + + .org-sme-badge { + padding: 1px 8px; + background: #fff3e0; + border-radius: var(--sg-radius-sm); + color: #e65100; + font-weight: 600; + } + + .org-city { + color: var(--sg-text-muted); + } +} + +.org-contribution, +.org-cost { + display: flex; + flex-direction: column; + align-items: flex-end; + padding-left: 16px; + border-left: 1px solid #d9e2f0; + + .contribution-label, + .cost-label { + font-size: 11px; + color: var(--sg-text-muted); + } + + .contribution-value, + .cost-value { + font-weight: 600; + font-size: 14px; + color: var(--sg-text); + } +} + +// Publications +.publications-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.publication-item { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 14px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + transition: all 0.2s; + + &:hover { + background: #f8fafc; + } +} + +.pub-icon { + flex-shrink: 0; + color: var(--sg-text-muted); + + mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + } +} + +.pub-info { + flex: 1; + min-width: 0; +} + +.pub-title { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} + +.pub-authors { + color: var(--sg-text-muted); + font-size: 13px; + margin-top: 2px; +} + +.pub-meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 12px; + color: var(--sg-text-muted); + + .pub-journal { + color: var(--sg-text); + } + + .pub-year, + .pub-publisher { + color: var(--sg-text-muted); + } +} + +.pub-actions { + display: flex; + gap: 8px; + flex-shrink: 0; + + .pub-link { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: var(--sg-radius-sm); + color: var(--sg-text-muted); + transition: all 0.2s; + + &:hover { + background: #e8edf5; + color: var(--sg-primary, #0066cc); + } + + mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } + } +} + +// IPRs +.iprs-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.ipr-item { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 14px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + transition: all 0.2s; + + &:hover { + background: #f8fafc; + } +} + +.ipr-icon { + flex-shrink: 0; + color: #f39c12; + + mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + } +} + +.ipr-info { + flex: 1; + min-width: 0; +} + +.ipr-title { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} + +.ipr-details { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 12px; + + .ipr-type { + padding: 1px 8px; + background: #fff3e0; + border-radius: var(--sg-radius-sm); + color: #e65100; + font-weight: 500; + } + + .ipr-patent-type { + padding: 1px 8px; + background: #e8eaf6; + border-radius: var(--sg-radius-sm); + color: #283593; + } + + .ipr-applicant { + color: var(--sg-text-muted); + } +} + +.ipr-identifiers { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 11px; + color: var(--sg-text-muted); + + .ipr-app-id, + .ipr-award-id { + padding: 1px 8px; + background: #f5f7fa; + border-radius: var(--sg-radius-sm); + } +} + +// Deliverables +.deliverables-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.deliverable-item { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 14px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + transition: all 0.2s; + + &:hover { + background: #f8fafc; + } +} + +.deliv-icon { + flex-shrink: 0; + color: #7b1fa2; + + mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + } +} + +.deliv-info { + flex: 1; + min-width: 0; +} + +.deliv-description { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} + +.deliv-meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 12px; + align-items: center; + + .deliv-type { + padding: 1px 8px; + background: #f3e5f5; + border-radius: var(--sg-radius-sm); + color: #7b1fa2; + } + + .deliv-link { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--sg-primary, #0066cc); + text-decoration: none; + + &:hover { + text-decoration: underline; + } + + mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + } + } +} + +// EuroSciVoc +.eurosci-voc-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + padding: 16px 20px 20px; +} + +.eurosci-voc-item { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: #f8fafc; + border-radius: var(--sg-radius-sm); + border: 1px solid #d9e2f0; + + .voc-code { + font-weight: 600; + font-size: 12px; + color: var(--sg-text-muted); + background: #e8edf5; + padding: 2px 8px; + border-radius: var(--sg-radius-sm); + } + + .voc-title { + font-size: 13px; + color: var(--sg-text); + } +} + +// ERC PIs +.erc-pi-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 8px; +} + +.erc-pi-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 14px; + background: #f8fafc; + border-radius: var(--sg-radius-sm); + border: 1px solid #d9e2f0; + + .pi-name { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; + } + + .pi-title { + color: var(--sg-text-muted); + font-size: 13px; + } +} + +// Responsive +@media (max-width: 992px) { + .eurosci-voc-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 768px) { + .tabs-container { + gap: 2px; + padding: 0 2px; + } + + .tab-btn { + padding: 8px 12px; + font-size: 12px; + + mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + } + } + + .organization-item, + .publication-item, + .ipr-item, + .deliverable-item { + flex-wrap: wrap; + } + + .org-contribution, + .org-cost { + width: 100%; + padding-left: 0; + padding-top: 8px; + border-left: none; + border-top: 1px solid #d9e2f0; + flex-direction: row; + gap: 8px; + align-items: center; + } } \ No newline at end of file diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index 0c4020a9..6c9ee825 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -4,25 +4,146 @@ import { CommonModule } from '@angular/common'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { MatChipsModule } from '@angular/material/chips'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { Router } from '@angular/router'; +import { formatGermanDate } from '../../../shared/utils/formatters'; +// Type definitions for the enriched project +interface Organization { + name?: string; + shortName?: string; + role?: string; + country?: string; + city?: string; + ecContribution?: number; + totalCost?: number; + activityType?: string; + sme?: boolean; + organisationID?: string; +} + +interface Publication { + title?: string; + authors?: string; + doi?: string; + journalTitle?: string; + publishedYear?: number; + publisher?: string; + repositoryUrl?: string; +} + +interface Deliverable { + description?: string; + deliverableType?: string; + url?: string; +} + +interface Ipr { + title?: string; + type?: string; + applicantName?: string; + applicationIdentifier?: string; + awardIdentifier?: string; + patentType?: string; +} + +interface ErcPI { + firstName?: string; + lastName?: string; + title?: string; + organisationID?: string; +} + +interface EnrichedProject { + // Core project fields + id?: string; + title?: string; + acronym?: string; + rcn?: string; + status?: string; + startDate?: string; + endDate?: string; + ecMaxContribution?: number; + totalCost?: number; + ecSignatureDate?: string; + contentUpdateDate?: string; + grantDoi?: string; + frameworkProgramme?: string; + fundingScheme?: string; + masterCall?: string; + subCall?: string; + objective?: string; + topics?: string; + keywords?: string; + nature?: string; + legalBasis?: string; + + // Enriched data + organizations?: Organization[]; + publications?: Publication[]; + deliverables?: Deliverable[]; + iprs?: Ipr[]; + ercPrincipalInvestigators?: ErcPI[]; + reportSummaries?: any[]; + topicsList?: any[]; + webLinks?: any[]; + eurosciVoc?: any[]; + legalBasisList?: any[]; + + // Statistics + organizationCount?: number; + publicationCount?: number; + deliverableCount?: number; + iprCount?: number; + ercPiCount?: number; + + // Program type + programType?: 'fp7' | 'h2020' | 'heu'; +} @Component({ selector: 'app-eu-details', standalone: true, - imports: [CommonModule, MatCardModule, MatIconModule, MatChipsModule], + imports: [ + CommonModule, + MatCardModule, + MatIconModule, + MatChipsModule, + MatButtonModule, + MatDividerModule, + MatTooltipModule, + ], templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', }) export class EuDetailsComponent implements OnInit { private route = inject(ActivatedRoute); - euProject: any | undefined; + euProject: EnrichedProject | undefined; + activeTab: + | 'overview' + | 'organizations' + | 'publications' + | 'iprs' + | 'deliverables' = 'overview'; constructor(private router: Router) {} ngOnInit(): void { this.route.data.subscribe(({ euSingleProject }) => { console.log('EU Project:', euSingleProject); - this.euProject = euSingleProject; + this.euProject = euSingleProject.data; + + // Determine program type + if (this.euProject) { + if (euSingleProject.iprs !== undefined) { + this.euProject.programType = 'fp7'; + } else if (euSingleProject.ercPrincipalInvestigators !== undefined) { + this.euProject.programType = 'h2020'; + } else if (euSingleProject.deliverables !== undefined) { + this.euProject.programType = 'heu'; + } + } }); } @@ -39,30 +160,43 @@ export class EuDetailsComponent implements OnInit { if (!endDate) return 'N/A'; const end = new Date(endDate); const now = new Date(); - + if (isNaN(end.getTime())) return endDate; - + return end >= now ? 'Laufend' : 'Abgeschlossen'; } formatCurrency(amount: number | null | undefined): string { if (amount === null || amount === undefined) return 'N/A'; - + return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR', minimumFractionDigits: 0, - maximumFractionDigits: 0 + maximumFractionDigits: 0, }).format(amount); } + getDuration(start: string | undefined, end: string | undefined): string { + if (!start || !end) return ''; + return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`; + } + formatDate(date: string | undefined) { + if (date) { + return formatGermanDate(date); + } + return date; + } getStatusColor(status: string | null | undefined): string { if (!status) return '#95a5a6'; - + const statusUpper = status.toUpperCase(); if (statusUpper.includes('CLOSED') || statusUpper.includes('COMPLETED')) { return '#27ae60'; - } else if (statusUpper.includes('ONGOING') || statusUpper.includes('ACTIVE')) { + } else if ( + statusUpper.includes('ONGOING') || + statusUpper.includes('ACTIVE') + ) { return '#f39c12'; } else if (statusUpper.includes('SIGNED')) { return '#3498db'; @@ -75,106 +209,142 @@ export class EuDetailsComponent implements OnInit { getStatusDisplay(status: string | null | undefined): string { if (!status) return 'N/A'; - + const statusMap: { [key: string]: string } = { - 'CLOSED': 'Abgeschlossen', - 'COMPLETED': 'Abgeschlossen', - 'ONGOING': 'Laufend', - 'ACTIVE': 'Aktiv', - 'SIGNED': 'Unterzeichnet', - 'CANCELLED': 'Abgebrochen', - 'SUSPENDED': 'Unterbrochen' + CLOSED: 'Abgeschlossen', + COMPLETED: 'Abgeschlossen', + ONGOING: 'Laufend', + ACTIVE: 'Aktiv', + SIGNED: 'Unterzeichnet', + CANCELLED: 'Abgebrochen', + SUSPENDED: 'Unterbrochen', }; - + const statusUpper = status.toUpperCase(); return statusMap[statusUpper] || status; } getFrameworkDisplay(framework: string | null | undefined): string { if (!framework) return 'N/A'; - + const frameworkMap: { [key: string]: string } = { - 'H2020': 'Horizon 2020', - 'FP7': '7. Rahmenprogramm', - 'FP6': '6. Rahmenprogramm', - 'HE': 'Horizon Europe' + HORIZON: ' Horizon Europe', + H2020: 'Horizon 2020', + FP7: '7. Rahmenprogramm', + FP6: '6. Rahmenprogramm', + HE: 'Horizon Europe', }; - + return frameworkMap[framework] || framework; } getFundingSchemeDisplay(scheme: string | null | undefined): string { if (!scheme) return 'N/A'; - + const schemeMap: { [key: string]: string } = { - 'MSCA-IF-EF-SE': 'MSCA Individual Fellowship - European Fellowship - Standard', + 'MSCA-IF-EF-SE': + 'MSCA Individual Fellowship - European Fellowship - Standard', 'MSCA-IF-EF': 'MSCA Individual Fellowship - European Fellowship', 'MSCA-IF-GF': 'MSCA Individual Fellowship - Global Fellowship', 'MSCA-IF': 'MSCA Individual Fellowship', 'MSCA-ITN': 'MSCA Innovative Training Networks', 'MSCA-RISE': 'MSCA Research and Innovation Staff Exchange', - 'MSCA-COFUND': 'MSCA Co-funding of Regional, National and International Programmes' + 'MSCA-COFUND': + 'MSCA Co-funding of Regional, National and International Programmes', }; - + return schemeMap[scheme] || scheme; } getFormattedTopics(topics: string | null | undefined): string[] { if (!topics) return []; - return topics.split(',').map(t => t.trim()); + return topics + .split(',') + .map((t) => t.trim()) + .filter((t) => t); } getKeywords(keywords: string | null | undefined): string[] { if (!keywords) return []; if (keywords === 'false') return []; - // If keywords is a string with comma-separated values if (typeof keywords === 'string') { - return keywords.split(',').map(k => k.trim()).filter(k => k && k !== 'false'); + return keywords + .split(',') + .map((k) => k.trim()) + .filter((k) => k && k !== 'false'); } return []; } + getTotalEcContribution(): number { + if (!this.euProject?.organizations) return 0; + return this.euProject.organizations + .filter((org) => org.ecContribution !== undefined) + .reduce((sum, org) => sum + (org.ecContribution || 0), 0); + } + + getOrganizationCountries(): string[] { + if (!this.euProject?.organizations) return []; + const countries = new Set( + this.euProject.organizations + .filter((org) => org.country) + .map((org) => org.country as string), + ); + return Array.from(countries); + } + + // Tab switching + setTab( + tab: + | 'overview' + | 'organizations' + | 'publications' + | 'iprs' + | 'deliverables', + ): void { + this.activeTab = tab; + } + + // Search functions searchByTopic(topic: string): void { this.router.navigate(['/eu-projects'], { - queryParams: { - topic: topic - } + queryParams: { topic: topic }, }); } searchByKeyword(keyword: string): void { this.router.navigate(['/eu-projects'], { - queryParams: { - keyword: keyword - } + queryParams: { keyword: keyword }, }); } searchByFramework(framework: string): void { this.router.navigate(['/eu-projects'], { - queryParams: { - framework: framework - } + queryParams: { framework: framework }, }); } searchByFundingScheme(scheme: string): void { this.router.navigate(['/eu-projects'], { - queryParams: { - fundingScheme: scheme - } + queryParams: { fundingScheme: scheme }, }); } searchByStatus(status: string): void { this.router.navigate(['/eu-projects'], { + queryParams: { status: status }, + }); + } + + searchForInstitutionName(institutionName: string): void { + this.router.navigate(['/institutions'], { queryParams: { - status: status - } + search: institutionName, + }, }); } goBack(): void { window.history.back(); } -} \ No newline at end of file +} From 89fc34996ef4f610ea40e98615f870ca8e9210a6 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:09:27 +0200 Subject: [PATCH 19/81] BUND projects component adjustments --- .../bund-details/bund-details.component.html | 34 +++++++++++-------- .../bund-details/bund-details.component.ts | 28 +++++++-------- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/webapp/src/app/modules/projects/bund-details/bund-details.component.html b/webapp/src/app/modules/projects/bund-details/bund-details.component.html index 9b0df147..1c9f4132 100644 --- a/webapp/src/app/modules/projects/bund-details/bund-details.component.html +++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.html @@ -46,14 +46,21 @@ calendar_today
{{ getStartDate() || 'N/A' }} - Startdatum + Förderbeginn
event_busy
{{ getFundingStatus(getEndDate()) }} - Enddatum + Förderende +
+
+
+ access_time +
+ {{ getStatusDisplay(bundProject.funding_end_date) }} + Status
@if (bundProject.funding_amount) { @@ -77,18 +84,17 @@ - @if (bundProject.description) { - -
- description -

Beschreibung

-
-

{{ bundProject.description }}

-
- } -
+ @if (bundProject.description) { + +
+ description +

Beschreibung

+
+

{{ bundProject.description }}

+
+ } @if (getAssociatedPersons().length > 0) { @@ -351,11 +357,11 @@ } @if (getDuration()) { diff --git a/webapp/src/app/modules/projects/bund-details/bund-details.component.ts b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts index 5ad9007b..3a5c3f6c 100644 --- a/webapp/src/app/modules/projects/bund-details/bund-details.component.ts +++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.ts @@ -5,7 +5,7 @@ import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { BundProjectDetails } from '../../../api/model/bundProjectDetails'; import { Router } from '@angular/router'; - +import { formatGermanDate } from '../../../shared/utils/formatters'; @Component({ selector: 'app-bund-details', standalone: true, @@ -41,8 +41,8 @@ export class BundDetailsComponent implements OnInit { const year = parseInt(fundingEndDate, 10); if (isNaN(year)) return fundingEndDate; return year >= new Date().getFullYear() - ? `${fundingEndDate} (laufend)` - : `${fundingEndDate} (abgeschlossen)`; + ? `${fundingEndDate}` + : `${fundingEndDate}`; } formatCurrency(amount: number | null | undefined): string { @@ -104,15 +104,6 @@ export class BundDetailsComponent implements OnInit { // } // }); // } - private formatGermanDate(dateString: string): string { - if (!dateString) return ''; - - return new Intl.DateTimeFormat('de-DE', { - day: 'numeric', - month: 'long', - year: 'numeric', - }).format(new Date(dateString)); - } /** * All associated persons as a simple list. */ @@ -120,11 +111,11 @@ export class BundDetailsComponent implements OnInit { return this.bundProject?.associated_persons || []; } getStartDate(): string { - return this.formatGermanDate(this.bundProject?.funding_start_date ?? ''); + return formatGermanDate(this.bundProject?.funding_start_date ?? ''); } getEndDate(): string { - return this.formatGermanDate(this.bundProject?.funding_end_date ?? ''); + return formatGermanDate(this.bundProject?.funding_end_date ?? ''); } getDuration(): string { @@ -133,7 +124,7 @@ export class BundDetailsComponent implements OnInit { if (!start || !end) return ''; - return `von ${this.formatGermanDate(start)} bis ${this.formatGermanDate(end)}`; + return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`; } /** * All institutions as a simple list. @@ -156,7 +147,12 @@ export class BundDetailsComponent implements OnInit { if (!this.bundProject?.funding_amount) return 'N/A'; return this.formatCurrency(this.bundProject.funding_amount); } - + getStatusDisplay(fundingEndDate: string | null | undefined): string { + if (!fundingEndDate) return 'N/A'; + if (fundingEndDate === '2999') return 'Laufend'; + const year = parseInt(fundingEndDate, 10); + return year >= new Date().getFullYear() ? `Laufend` : `Abgeschlossen`; + } goBack(): void { window.history.back(); } From 6173db73b57c36ce64c2671d73c34d0f7fc572bc Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:10:24 +0200 Subject: [PATCH 20/81] date formatted --- .../dfg-details/dfg-details.component.html | 38 ++++++++++--------- .../dfg-details/dfg-details.component.ts | 34 +++++++++++++++-- .../eu-details.component.scss | 4 -- 3 files changed, 51 insertions(+), 25 deletions(-) diff --git a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html index 81947db7..cf9a55dd 100644 --- a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html +++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.html @@ -44,14 +44,21 @@ calendar_today
{{ dfgProject.funding_start_date || 'N/A' }} - Fördersbeginn + Förderbeginn
event_busy
{{ getFundingStatus(dfgProject.funding_end_date) }} - Fördersende + Förderende +
+
+
+ access_time +
+ {{ getStatusDisplay(dfgProject.funding_end_date) }} + Status
@@ -198,12 +204,8 @@
{{ dfgProject.funding_type || 'N/A' }}
-->
-
Fördersbeginn
-
{{ dfgProject.funding_start_date || 'N/A' }}
-
-
-
Fördersende
-
{{ getFundingStatus(dfgProject.funding_end_date) }}
+
Laufzeit
+
{{ getDuration() }}
@if (dfgProject.subproject_of) {
diff --git a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts index ab8ca4ea..ec1dac1b 100644 --- a/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts +++ b/webapp/src/app/modules/projects/dfg-details/dfg-details.component.ts @@ -36,13 +36,34 @@ export class DfgDetailsComponent implements OnInit { getFundingStatus(fundingEndDate: string | null | undefined): string { if (!fundingEndDate) return 'N/A'; - if (fundingEndDate === '2999') return 'laufend'; + if (fundingEndDate === '2999') return 'Laufend'; const year = parseInt(fundingEndDate, 10); if (isNaN(year)) return fundingEndDate; return year >= new Date().getFullYear() - ? `${fundingEndDate} (laufend)` - : `${fundingEndDate} (abgeschlossen)`; + ? `${fundingEndDate}` + : `${fundingEndDate}`; } + + getStatusDisplay(fundingEndDate: string | null | undefined): string { + if (!fundingEndDate) return 'N/A'; + if (fundingEndDate === '2999') return 'Laufend'; + const year = parseInt(fundingEndDate, 10); + return year >= new Date().getFullYear() ? `Laufend` : `Abgeschlossen`; + } + + getStatusColor(status: string | null | undefined): string { + if (!status) return '#95a5a6'; + + const statusUpper = status.toUpperCase(); + if (statusUpper.includes('Abgeschlossen')) { + return '#27ae60'; + } else if (statusUpper.includes('Laufend')) { + return '#f39c12'; + } else { + return '#95a5a6'; + } + } + searchForPersonName(personName: string): void { this.router.navigate(['/persons'], { queryParams: { @@ -70,7 +91,14 @@ export class DfgDetailsComponent implements OnInit { getInstitutions(): string[] { return this.dfgProject?.institutions || []; } + getDuration(): string { + const start = this.dfgProject?.funding_start_date; + const end = this.dfgProject?.funding_end_date; + if (!start || !end) return ''; + + return `von ${start} bis ${end}`; + } goBack(): void { window.history.back(); } diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss index bbb60de8..19553278 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -1,5 +1,3 @@ -// Complete SCSS with all styles - .detail-page { padding: 28px 32px 42px; max-width: 100%; @@ -617,8 +615,6 @@ h1 { justify-content: center; } } -// Add these to your existing SCSS file - // Program badges .program-badge { display: inline-block; From 171a7d08b73a41e7e8381c611704e7cbf0ee57f4 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:10:48 +0200 Subject: [PATCH 21/81] added external date -> german date formatter --- webapp/src/app/shared/utils/formatters.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 webapp/src/app/shared/utils/formatters.ts diff --git a/webapp/src/app/shared/utils/formatters.ts b/webapp/src/app/shared/utils/formatters.ts new file mode 100644 index 00000000..58cc03bc --- /dev/null +++ b/webapp/src/app/shared/utils/formatters.ts @@ -0,0 +1,9 @@ +export function formatGermanDate(dateString: string): string { + if (!dateString) return ''; + + return new Intl.DateTimeFormat('de-DE', { + day: 'numeric', + month: 'long', + year: 'numeric', + }).format(new Date(dateString)); +} From 443169bc90590fe554ba5e40a0786ec0a6e5d8c5 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:11:15 +0200 Subject: [PATCH 22/81] resolver adjusted for the new data model --- webapp/src/app/resolvers/eu-single-project-resolver.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/resolvers/eu-single-project-resolver.ts b/webapp/src/app/resolvers/eu-single-project-resolver.ts index 4bb3eb86..032ba63e 100644 --- a/webapp/src/app/resolvers/eu-single-project-resolver.ts +++ b/webapp/src/app/resolvers/eu-single-project-resolver.ts @@ -1,9 +1,9 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; import { ProjectsService } from '../api/api/projects.service'; -import { CordisEuProject } from '../api'; +import { EuCordisProjectResponse } from '../api'; -export const euSingleProjectResolver: ResolveFn = ( +export const euSingleProjectResolver: ResolveFn = ( route, state, ) => { From 04cb26092753a9ee1887a4549eb72e517f244af2 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:11:26 +0200 Subject: [PATCH 23/81] added models to FILES --- webapp/src/app/api/.openapi-generator/FILES | 34 +++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 0a468ed3..1f846392 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -54,6 +54,7 @@ model/cordisEuProjectPage.ts model/costUsd.ts model/customAuthor.ts model/customAuthorsListResponse.ts +model/data.ts model/dehydratedAuthor.ts model/dehydratedFunder.ts model/dehydratedInstitution.ts @@ -61,16 +62,47 @@ model/dehydratedSource.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/eccontribution.ts +model/ecmaxcontribution.ts +model/euCordisProjectResponse.ts model/euOrganizationProjectSummary.ts model/euOrganizationProjectSummaryPage.ts model/filterInformation.ts model/filterProperties.ts +model/fp7EurosciVoc.ts +model/fp7LegalBasis.ts +model/fp7Organization.ts +model/fp7ProjectDetails.ts +model/fp7ProjectIPR.ts +model/fp7Publication.ts +model/fp7ReportSummary.ts +model/fp7Topic.ts +model/fp7WebLink.ts model/funderByAuthor.ts model/fundersByAuthorResponse.ts model/fundingProject.ts model/fundingProjectPage.ts model/fwci.ts model/groupByResult.ts +model/h2020Deliverable.ts +model/h2020ErcPI.ts +model/h2020EurosciVoc.ts +model/h2020LegalBasis.ts +model/h2020Organization.ts +model/h2020ProjectDetails.ts +model/h2020Publication.ts +model/h2020ReportSummary.ts +model/h2020Topic.ts +model/h2020WebLink.ts +model/hEUDeliverable.ts +model/hEUEurosciVoc.ts +model/hEULegalBasis.ts +model/hEUOrganization.ts +model/hEUProjectDetails.ts +model/hEUPublication.ts +model/hEUReportSummary.ts +model/hEUTopic.ts +model/hEUWebLink.ts model/hTTPValidationError.ts model/identityGrant.ts model/institution.ts @@ -93,6 +125,7 @@ model/mentionedPerson.ts model/meta.ts model/model2YrMeanCitedness.ts model/models.ts +model/neteccontribution.ts model/newsArticle.ts model/newsArticleDetail.ts model/newsPage.ts @@ -119,6 +152,7 @@ model/topics.ts model/topicsByTime.ts model/topicsByYear.ts model/topicsListResponse.ts +model/totalcost.ts model/universityRanking.ts model/universityTopicData.ts model/user.ts From ce6f29292ce6755953ed6cbc321dcea5a5e5b78c Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 00:29:20 +0200 Subject: [PATCH 24/81] test --- service/src/main/inse/projects/model.py | 1 - 1 file changed, 1 deletion(-) diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 526e55af..137867ae 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -167,7 +167,6 @@ class CordisEuProjectPage(Page): default_factory=list, description="The CORDIS EU projects on this page." ) - class EuCordisProjectResponse(BaseModel): """ Response model for EU Cordis project endpoints. From 12377749c27a5a4178da840fcacdccc8b0dc6896 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Tue, 23 Jun 2026 00:30:28 +0200 Subject: [PATCH 25/81] feat(news): expand search results to include similar results --- .../main/inse/integrations/elasticsearch.py | 89 +++++++++++- service/src/main/inse/news/logic.py | 135 ++++++++++++++++-- service/src/main/inse/news/model.py | 1 + .../ui/news-list/news-list.component.html | 3 + .../ui/news-list/news-list.component.scss | 16 +++ .../ui/news-list/news-list.component.ts | 1 + 6 files changed, 230 insertions(+), 15 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 8efe92ef..90579180 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,5 +1,5 @@ import logging -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, Iterator, List, Optional, Tuple import httpx from .. import config @@ -118,6 +118,93 @@ def search( return response.json() +def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str: + """Opens a point-in-time on the given index and returns its id.""" + elasticsearch_url, api_key = _cluster_credentials(cluster) + headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} + + with httpx.Client(timeout=httpx.Timeout(30.0)) as client: + response = client.post( + f"{elasticsearch_url}/{index}/_pit", + params={"keep_alive": keep_alive}, + headers=headers, + ) + response.raise_for_status() + return response.json()["id"] + + +def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: + """Closes a previously opened point-in-time.""" + elasticsearch_url, api_key = _cluster_credentials(cluster) + headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} + + with httpx.Client(timeout=httpx.Timeout(30.0)) as client: + response = client.request( + "DELETE", + f"{elasticsearch_url}/_pit", + json={"id": pit_id}, + headers=headers, + ) + response.raise_for_status() + + +def scan( + index: str, + query: Dict, + source: Optional[List] = None, + page_size: int = 1000, + keep_alive: str = "1m", + cluster: str = "nes", +) -> Iterator[Dict[str, Any]]: + """Yields every hit matching ``query`` using a point-in-time + ``search_after``. + + Unlike ``from``/``size`` pagination, this is not bounded by + ``index.max_result_window``, so it can stream result sets larger than 10k. + """ + elasticsearch_url, api_key = _cluster_credentials(cluster) + headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} + + pit_id = open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) + search_after: Optional[List] = None + try: + with httpx.Client(timeout=httpx.Timeout(30.0)) as client: + while True: + payload: Dict[str, Any] = { + "size": page_size, + "query": query, + "pit": {"id": pit_id, "keep_alive": keep_alive}, + "sort": [{"_shard_doc": "asc"}], + "track_total_hits": False, + } + if source is not None: + payload["_source"] = source + if search_after is not None: + payload["search_after"] = search_after + + response = client.post( + f"{elasticsearch_url}/_search", json=payload, headers=headers + ) + response.raise_for_status() + result = response.json() + + hits = result.get("hits", {}).get("hits", []) + if not hits: + break + + yield from hits + + # The pit id can be refreshed between requests; keep the latest. + pit_id = result.get("pit_id", pit_id) + search_after = hits[-1].get("sort") + if search_after is None or len(hits) < page_size: + break + finally: + try: + close_point_in_time(pit_id, cluster=cluster) + except Exception: + logger.exception("Failed to close Elasticsearch point-in-time.") + + def get( index: str, doc_id: str, diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index e62958e7..fb8db1f1 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -20,6 +20,10 @@ TOPIC_QUERY_CONTENT_CHARS = 300 TOPIC_NUM_CANDIDATES = 100 TOPIC_SIMILARITY = 0.5 +RELATED_BLOCK_SIZE = 5 +RELATED_TOPIC_K = 1 +EXACT_ID_CAP = 1000 + def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage: offset = (page - 1) * page_size @@ -45,8 +49,9 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage: "encoder": "html", } + exact_query = {"match": {"full_content": query_text}} response = _run_search( - query={"match": {"full_content": query_text}}, + query=exact_query, source=["date", "maintitle", "author", "url"], size=page_size, offset=offset, @@ -54,7 +59,15 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage: highlight=highlight, ) - return _build_page(response, page, page_size) + news_page = _build_page(response, page, page_size) + + if _is_last_page(page, page_size, news_page.total): + exclude_ids = _exact_match_ids(exact_query) + news_page.results.extend( + _related_articles(query_text, exclude_ids=exclude_ids) + ) + + return news_page def get_news_by_author( author_id: str, @@ -87,7 +100,17 @@ def get_news_by_author( sort=[{"date_full": sort_order}], ) - return _build_page(response, page, page_size) + news_page = _build_page(response, page, page_size) + + if query_text and _is_last_page(page, page_size, news_page.total): + exclude_ids = _exact_match_ids(es_query) + news_page.results.extend( + _related_articles( + query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids + ) + ) + + return news_page def _find_news_ids_for_author(author_name: str) -> list: @@ -157,12 +180,17 @@ def _get_article_topics(maintitle: str | None, full_content: str | None) -> list if not query: return [] + topics = _topic_vector_search(query, TOPIC_LIMIT, ["display_name"]) + return [topic["display_name"] for topic in topics if topic.get("display_name")] + + +def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: try: from ..util import get_model - query_vector = get_model().encode(query).tolist() + query_vector = get_model().encode(query_text).tolist() except Exception: - logger.exception("Failed to encode news article text for topic search.") + logger.exception("Failed to encode text for topic vector search.") return [] try: @@ -172,24 +200,20 @@ def _get_article_topics(maintitle: str | None, full_content: str | None) -> list "knn": { "field": "display_name_vector", "query_vector": query_vector, - "k": TOPIC_LIMIT, + "k": k, "num_candidates": TOPIC_NUM_CANDIDATES, "similarity": TOPIC_SIMILARITY, }, - "_source": ["display_name"], - "size": TOPIC_LIMIT, + "_source": source_fields, + "size": k, }, cluster="nes", ) except Exception: - logger.exception("Topic vector search for news article failed.") + logger.exception("Topic vector search failed.") return [] - return [ - display_name - for hit in response.get("hits", {}).get("hits", []) - if (display_name := hit.get("_source", {}).get("display_name")) - ] + return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])] def _build_mentioned_persons(author_names: list) -> list: @@ -321,3 +345,86 @@ def _parse_hit(hit: dict) -> NewsArticle: url=source.get("url"), snippet=snippet, ) + + +def _is_last_page(page: int, page_size: int, total: int) -> bool: + return page * page_size >= total + + +def _exact_match_ids(query: dict) -> list: + try: + response = _run_search( + query=query, + source=[], + size=EXACT_ID_CAP, + offset=0, + sort=None, + ) + except Exception: + logger.exception("Failed to collect exact-match ids for dedup.") + return [] + + return [ + hit.get("_id") + for hit in response.get("hits", {}).get("hits", []) + if hit.get("_id") + ] + + +def _related_articles( + query_text: str, + exclude_ids: list | None = None, + filter_news_ids: list | None = None, + k: int = RELATED_BLOCK_SIZE, +) -> list: + related_terms = _related_search_terms(query_text) + if not related_terms: + return [] + + bool_query = { + "should": [{"match": {"full_content": term}} for term in related_terms], + "minimum_should_match": 1, + } + if exclude_ids: + bool_query["must_not"] = [{"ids": {"values": exclude_ids}}] + if filter_news_ids is not None: + bool_query["filter"] = [{"ids": {"values": filter_news_ids}}] + + try: + response = elasticsearch.search( + index="aktuell", + query={"bool": bool_query}, + source=["date", "maintitle", "author", "url"], + size=k, + offset=0, + cluster="inse", + ) + except Exception: + logger.exception("Related-articles search failed.") + return [] + + articles = [] + for hit in response.get("hits", {}).get("hits", []): + article = _parse_hit(hit) + article.related = True + articles.append(article) + + relevance_map = _get_relevance_map([article.id for article in articles]) + for article in articles: + article.relevant = relevance_map.get(article.id) + + return articles + + +def _related_search_terms(query_text: str) -> list: + topics = _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"]) + + seen = {query_text.lower()} + terms = [] + for topic in topics: + for term in [topic.get("display_name"), *(topic.get("keywords") or [])]: + if term and term.lower() not in seen: + seen.add(term.lower()) + terms.append(term) + + return terms diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index ec865fac..854e2dff 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -14,6 +14,7 @@ class NewsArticle(BaseModel): url: Optional[str] = None relevant: Optional[bool] = None snippet: Optional[str] = None + related: Optional[bool] = None class MentionedPerson(BaseModel): diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.html b/webapp/src/app/shared/ui/news-list/news-list.component.html index 91f290ea..68e59aab 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.html +++ b/webapp/src/app/shared/ui/news-list/news-list.component.html @@ -31,6 +31,9 @@ {{ article.maintitle || 'Kein Titel' }} + @if (article.related) { + Passend zu deiner Suche + } diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.scss b/webapp/src/app/shared/ui/news-list/news-list.component.scss index a8eafe84..9f936453 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.scss +++ b/webapp/src/app/shared/ui/news-list/news-list.component.scss @@ -79,6 +79,22 @@ table { } } +.related-badge { + display: flex; + width: fit-content; + align-items: center; + margin-top: 6px; + padding: 3px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + line-height: 1; + white-space: nowrap; + background: #eef3fe; + border: 1px solid #c5d6f7; + color: #2f5bd0; +} + .loading { position: absolute; inset: 0; diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.ts b/webapp/src/app/shared/ui/news-list/news-list.component.ts index ceddb449..8ffafc05 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.ts +++ b/webapp/src/app/shared/ui/news-list/news-list.component.ts @@ -25,6 +25,7 @@ export interface NewsArticleBase { maintitle?: string | null; url?: string | null; relevant?: boolean | null; + related?: boolean | null; } export type SortOrder = 'desc' | 'asc'; From e476935a5d87118c8af00ffe9c2391835e435111 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Tue, 23 Jun 2026 06:36:59 +0200 Subject: [PATCH 26/81] Retry Jenkins build From 7045d9ea7aef86abcf7e0e325e7a3bdcf5c39ae6 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 09:27:16 +0200 Subject: [PATCH 27/81] index names fixed --- .../eu_cordis_projects_enrichment_client.py | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py index 88e314cb..6852a48c 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py @@ -106,7 +106,7 @@ def _determine_program_type_from_index(index: str) -> str: index_lower = index.lower() if "fp7" in index_lower: return "fp7" - elif "horizon_2020" or () in index_lower: + elif "horizon_2020" in index_lower: return "h2020" elif "heu" in index_lower or "horizon_europe" in index_lower: return "heu" @@ -157,7 +157,7 @@ def _enrich_fp7_project( ) eurosci_voc = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_fp7_eurosci_voc", + index_pattern="cordis_eu_fp7_euroscivoc", model_class=Fp7EurosciVoc ) legal_basis_list = _fetch_related_entities( @@ -194,47 +194,47 @@ def _enrich_h2020_project( # Fetch all related data organizations = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_organizations", + index_pattern="cordis_eu_horizon_2020_organizations", model_class=H2020Organization ) publications = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_publications", + index_pattern="cordis_eu_horizon_2020_publications", model_class=H2020Publication ) deliverables = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_deliverables", + index_pattern="cordis_eu_horizon_2020_deliverables", model_class=H2020Deliverable ) report_summaries = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_report_summaries", + index_pattern="cordis_eu_horizon_2020_report_summaries", model_class=H2020ReportSummary ) topics_list = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_topics", + index_pattern="cordis_eu_horizon_2020_topics", model_class=H2020Topic ) web_links = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_web_links", + index_pattern="cordis_eu_horizon_2020_web_links", model_class=H2020WebLink ) eurosci_voc = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_eurosci_voc", + index_pattern="cordis_eu_horizon_2020_euroscivoc", model_class=H2020EurosciVoc ) legal_basis_list = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_legal_basis", + index_pattern="cordis_eu_horizon_2020_legal_basis", model_class=H2020LegalBasis ) erc_pis = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_h2020_erc_pis", + index_pattern="cordis_eu_horizon_2020_erc_pis", model_class=H2020ErcPI ) @@ -267,42 +267,43 @@ def _enrich_heu_project( # Fetch all related data organizations = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_organizations", + index_pattern="cordis_eu_horizon_europe_organizations", model_class=HEUOrganization ) + print("ORGS",organizations) publications = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_publications", + index_pattern="cordis_eu_horizon_europe_publications", model_class=HEUPublication ) deliverables = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_deliverables", + index_pattern="cordis_eu_horizon_europe_deliverables", model_class=HEUDeliverable ) report_summaries = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_report_summaries", + index_pattern="cordis_eu_horizon_europe_report_summaries", model_class=HEUReportSummary ) topics_list = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_topics", + index_pattern="cordis_eu_horizon_europe_topics", model_class=HEUTopic ) web_links = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_web_links", + index_pattern="cordis_eu_horizon_europe_web_links", model_class=HEUWebLink ) eurosci_voc = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_eurosci_voc", + index_pattern="cordis_eu_horizon_europe_euroscivoc", model_class=HEUEurosciVoc ) legal_basis_list = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_heu_legal_basis", + index_pattern="cordis_eu_horizon_europe_legal_basis", model_class=HEULegalBasis ) @@ -343,7 +344,7 @@ def _fetch_related_entities( query=query, index=index_pattern, cluster=ESCluster.INSE, - size=1 + size=10000 ) except Exception as e: logger.warning(f"Failed to fetch from {index_pattern}: {e}") From 7ad3e080b673715a9ecbff73e7d531fc5932d35c Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Tue, 23 Jun 2026 13:54:57 +0200 Subject: [PATCH 28/81] feat(news): add tooltip for relevance header in news list --- .../ui/news-list/news-list.component.html | 14 +++++++++- .../ui/news-list/news-list.component.scss | 26 +++++++++++++++++++ .../ui/news-list/news-list.component.ts | 7 +++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.html b/webapp/src/app/shared/ui/news-list/news-list.component.html index 68e59aab..7a5eb812 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.html +++ b/webapp/src/app/shared/ui/news-list/news-list.component.html @@ -38,7 +38,19 @@ - Relevanz + + + Relevanz + + info + + + @if (article.relevant === true) { diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.scss b/webapp/src/app/shared/ui/news-list/news-list.component.scss index 9f936453..e03c48de 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.scss +++ b/webapp/src/app/shared/ui/news-list/news-list.component.scss @@ -153,6 +153,32 @@ table { font-weight: 700; } +.relevance-header { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.relevance-info { + font-size: 15px; + width: 15px; + height: 15px; + color: var(--sg-text-muted); + cursor: help; + + &:hover, + &:focus { + color: var(--sg-text); + } +} + +::ng-deep .relevance-tooltip.mdc-tooltip .mdc-tooltip__surface { + max-width: 260px; + font-size: 12.5px; + line-height: 1.5; + padding: 8px 12px; +} + ::ng-deep .mat-mdc-row { height: 72px; } diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.ts b/webapp/src/app/shared/ui/news-list/news-list.component.ts index 8ffafc05..93896785 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.ts +++ b/webapp/src/app/shared/ui/news-list/news-list.component.ts @@ -16,6 +16,7 @@ import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { PaginationService } from '../../services/pagination.service'; @@ -40,6 +41,7 @@ export type SortOrder = 'desc' | 'asc'; MatPaginatorModule, MatProgressSpinnerModule, MatTableModule, + MatTooltipModule, NgTemplateOutlet, ReactiveFormsModule, RouterLink, @@ -50,6 +52,11 @@ export type SortOrder = 'desc' | 'asc'; export class NewsListComponent { readonly paginationService = inject(PaginationService); + readonly relevanceHelp = + 'Zeigt, ob ein Artikel inhaltlich über eine konkrete Person berichtet ' + + '(Relevant) oder eine allgemeine Mitteilung ohne Personenbezug ist ' + + '(Nicht relevant).'; + @Input({ required: true }) articles: NewsArticleBase[] = []; @Input({ required: true }) displayedColumns: string[] = []; @Input() total = 0; From e2c055f58c25374a0e1b3b52e57106d775917c2a Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 14:23:23 +0200 Subject: [PATCH 29/81] added queryParams <-> navbar binding --- .../eu-details.component.html | 2 +- .../eu-cordis-details/eu-details.component.ts | 259 ++++++++++-------- 2 files changed, 145 insertions(+), 116 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 9a51d3ae..d08c1dbb 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -562,7 +562,7 @@

Geistiges Eigentum (IPRs) ({{ euProject.iprs.length }})

- @for (ipr of euProject.iprs; track ipr) { + @for (ipr of euProject.iprs; track ipr.title) {
@if (ipr.type === 'PATENT') { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index 6c9ee825..58a47b81 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -1,3 +1,4 @@ +// eu-details.component.ts (updated) import { Component, OnInit, inject } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { CommonModule } from '@angular/common'; @@ -9,98 +10,10 @@ import { MatDividerModule } from '@angular/material/divider'; import { MatTooltipModule } from '@angular/material/tooltip'; import { Router } from '@angular/router'; import { formatGermanDate } from '../../../shared/utils/formatters'; -// Type definitions for the enriched project -interface Organization { - name?: string; - shortName?: string; - role?: string; - country?: string; - city?: string; - ecContribution?: number; - totalCost?: number; - activityType?: string; - sme?: boolean; - organisationID?: string; -} +import { Data } from '../../../api'; -interface Publication { - title?: string; - authors?: string; - doi?: string; - journalTitle?: string; - publishedYear?: number; - publisher?: string; - repositoryUrl?: string; -} -interface Deliverable { - description?: string; - deliverableType?: string; - url?: string; -} - -interface Ipr { - title?: string; - type?: string; - applicantName?: string; - applicationIdentifier?: string; - awardIdentifier?: string; - patentType?: string; -} - -interface ErcPI { - firstName?: string; - lastName?: string; - title?: string; - organisationID?: string; -} - -interface EnrichedProject { - // Core project fields - id?: string; - title?: string; - acronym?: string; - rcn?: string; - status?: string; - startDate?: string; - endDate?: string; - ecMaxContribution?: number; - totalCost?: number; - ecSignatureDate?: string; - contentUpdateDate?: string; - grantDoi?: string; - frameworkProgramme?: string; - fundingScheme?: string; - masterCall?: string; - subCall?: string; - objective?: string; - topics?: string; - keywords?: string; - nature?: string; - legalBasis?: string; - - // Enriched data - organizations?: Organization[]; - publications?: Publication[]; - deliverables?: Deliverable[]; - iprs?: Ipr[]; - ercPrincipalInvestigators?: ErcPI[]; - reportSummaries?: any[]; - topicsList?: any[]; - webLinks?: any[]; - eurosciVoc?: any[]; - legalBasisList?: any[]; - - // Statistics - organizationCount?: number; - publicationCount?: number; - deliverableCount?: number; - iprCount?: number; - ercPiCount?: number; - - // Program type - programType?: 'fp7' | 'h2020' | 'heu'; -} +export type TabType = 'overview' | 'organizations' | 'publications' | 'iprs' | 'deliverables'; @Component({ selector: 'app-eu-details', @@ -119,17 +32,19 @@ interface EnrichedProject { }) export class EuDetailsComponent implements OnInit { private route = inject(ActivatedRoute); - euProject: EnrichedProject | undefined; - activeTab: - | 'overview' - | 'organizations' - | 'publications' - | 'iprs' - | 'deliverables' = 'overview'; - - constructor(private router: Router) {} + private router = inject(Router); + + euProject: Data| undefined; + activeTab: TabType = 'overview'; + programType: String = "" + // Track if tabs have content + hasOrganizations = false; + hasPublications = false; + hasIprs = false; + hasDeliverables = false; ngOnInit(): void { + // Subscribe to route data for project this.route.data.subscribe(({ euSingleProject }) => { console.log('EU Project:', euSingleProject); this.euProject = euSingleProject.data; @@ -137,16 +52,139 @@ export class EuDetailsComponent implements OnInit { // Determine program type if (this.euProject) { if (euSingleProject.iprs !== undefined) { - this.euProject.programType = 'fp7'; + this.programType = 'fp7'; } else if (euSingleProject.ercPrincipalInvestigators !== undefined) { - this.euProject.programType = 'h2020'; + this.programType = 'h2020'; } else if (euSingleProject.deliverables !== undefined) { - this.euProject.programType = 'heu'; + this.programType = 'heu'; } + + // Check which tabs have content + this.hasOrganizations = this.euProject.organizations && this.euProject.organizations.length > 0 || false; + this.hasPublications = this.euProject.publications && this.euProject.publications.length > 0 || false; + this.hasIprs = this.euProject.iprs && this.euProject.iprs.length > 0 || false; + this.hasDeliverables = this.euProject.deliverables && this.euProject.deliverables.length > 0 || false; + } + }); + + // Subscribe to query params for tab synchronization + this.route.queryParams.subscribe(params => { + const tabParam = params['tab'] as TabType; + if (tabParam && this.isValidTab(tabParam)) { + // Check if the tab has content before switching + if (this.tabHasContent(tabParam)) { + this.activeTab = tabParam; + } else { + // If tab has no content, switch to overview and update URL + this.updateTabQueryParam('overview'); + } + } else { + // If no valid tab param, set to overview and update URL + this.updateTabQueryParam('overview'); } }); } + /** + * Check if a tab value is valid + */ + private isValidTab(tab: string): tab is TabType { + return ['overview', 'organizations', 'publications', 'iprs', 'deliverables'].includes(tab); + } + + /** + * Check if a tab has content to display + */ + private tabHasContent(tab: TabType): boolean { + switch (tab) { + case 'overview': + return true; + case 'organizations': + return this.hasOrganizations; + case 'publications': + return this.hasPublications; + case 'iprs': + return this.hasIprs; + case 'deliverables': + return this.hasDeliverables; + default: + return false; + } + } + + /** + * Update URL query param for tab + */ + private updateTabQueryParam(tab: TabType): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { tab: tab }, + queryParamsHandling: 'merge', // Preserve other query params + }); + } + + /** + * Set active tab and update URL + */ + setTab(tab: TabType): void { + if (this.activeTab === tab) return; + + // Check if tab has content + if (!this.tabHasContent(tab)) { + return; + } + + this.activeTab = tab; + this.updateTabQueryParam(tab); + } + + /** + * Check if a tab is active + */ + isTabActive(tab: TabType): boolean { + return this.activeTab === tab; + } + + /** + * Check if a tab should be visible (has content) + */ + shouldShowTab(tab: TabType): boolean { + return this.tabHasContent(tab); + } + + /** + * Get tab label with count + */ + getTabLabel(tab: TabType): string { + const labels: Record = { + overview: 'Übersicht', + organizations: 'Organisationen', + publications: 'Publikationen', + iprs: 'IPRs', + deliverables: 'Ergebnisse', + }; + return labels[tab]; + } + + /** + * Get tab count badge + */ + getTabCount(tab: TabType): number | null { + switch (tab) { + case 'organizations': + return this.euProject?.organizations?.length || null; + case 'publications': + return this.euProject?.publications?.length || null; + case 'iprs': + return this.euProject?.iprs?.length || null; + case 'deliverables': + return this.euProject?.deliverables?.length || null; + default: + return null; + } + } + + getInitials(name: string | null | undefined): string { if (!name) return ''; const parts = name.trim().split(/\s+/); @@ -176,17 +214,20 @@ export class EuDetailsComponent implements OnInit { maximumFractionDigits: 0, }).format(amount); } + getDuration(start: string | undefined, end: string | undefined): string { if (!start || !end) return ''; return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`; } + formatDate(date: string | undefined) { if (date) { return formatGermanDate(date); } return date; } + getStatusColor(status: string | null | undefined): string { if (!status) return '#95a5a6'; @@ -293,18 +334,6 @@ export class EuDetailsComponent implements OnInit { return Array.from(countries); } - // Tab switching - setTab( - tab: - | 'overview' - | 'organizations' - | 'publications' - | 'iprs' - | 'deliverables', - ): void { - this.activeTab = tab; - } - // Search functions searchByTopic(topic: string): void { this.router.navigate(['/eu-projects'], { @@ -347,4 +376,4 @@ export class EuDetailsComponent implements OnInit { goBack(): void { window.history.back(); } -} +} \ No newline at end of file From f617c204fdac73a288456af2ceec6e155e1a5532 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 14:23:35 +0200 Subject: [PATCH 30/81] fixed wrong index name --- .../main/inse/projects/eu_cordis_projects_enrichment_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py index 6852a48c..7871e202 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py @@ -137,7 +137,7 @@ def _enrich_fp7_project( ) iprs = _fetch_related_entities( project_ids=[project_id], - index_pattern="cordis_eu_fp7_iprs", + index_pattern="cordis_eu_fp7_project_iprs", model_class=Fp7ProjectIPR ) report_summaries = _fetch_related_entities( From 7b0270f57a36cfeffbf8c7be82458e2bcbfd4dfb Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 14:24:15 +0200 Subject: [PATCH 31/81] added colored status element --- .../bund-details/bund-details.component.html | 12 +++++++++- .../bund-details/bund-details.component.scss | 22 +++++++++++++++++++ .../bund-details/bund-details.component.ts | 11 ++++++++++ .../dfg-details/dfg-details.component.html | 6 +++++ .../dfg-details/dfg-details.component.scss | 22 +++++++++++++++++++ .../dfg-details/dfg-details.component.ts | 9 ++++---- 6 files changed, 76 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/projects/bund-details/bund-details.component.html b/webapp/src/app/modules/projects/bund-details/bund-details.component.html index 1c9f4132..fcceb4bd 100644 --- a/webapp/src/app/modules/projects/bund-details/bund-details.component.html +++ b/webapp/src/app/modules/projects/bund-details/bund-details.component.html @@ -26,6 +26,14 @@

}
+
+ circle + {{ getStatusDisplay(bundProject.funding_end_date) }} +
@@ -220,7 +216,7 @@ } - @if (getKeywords(euProject.keywords).length > 0) { + + @if (getKeywordChips().length > 0) { + +
+ tag +

Schlüsselwörter

+ {{ + getKeywordChips().length + }} +
+
+ @for ( + keyword of getKeywordChips(); + track keyword.id || keyword.label + ) { + + + } +
+
} @@ -255,9 +278,39 @@
@for (voc of euProject.eurosciVoc; track voc.id) { -
- {{ voc.code }} - {{ voc.title }} +
+
+ @if (voc.path) { + @for ( + segment of getPathSegments(voc.path); + track segment + ) { + {{ segment }} + @if (!$last) { + chevron_right + } + } + } @else { + {{ + voc.code || 'N/A' + }} + } +
+ @if (voc.code) { + {{ voc.code }} + } + @if (voc.description) { + {{ + voc.description + }} + } + @if (voc.path) { + search + }
}
@@ -334,13 +387,13 @@ @if (euProject.ecMaxContribution) {
Max. EU-Beitrag
-
{{ formatCurrency(euProject.ecMaxContribution) }}
+
{{ formatCurr(euProject.ecMaxContribution) }}
} @if (euProject.totalCost) {
Gesamtkosten
-
{{ formatCurrency(euProject.totalCost) }}
+
{{ formatCurr(euProject.totalCost) }}
} @if (euProject.ecSignatureDate) { @@ -367,7 +420,12 @@
Laufzeit
-
{{ getDuration(euProject.startDate,euProject.endDate) || 'N/A' }}
+
+ {{ + getDuration(euProject.startDate, euProject.endDate) || + 'N/A' + }} +
@if (euProject.ecSignatureDate) {
@@ -400,7 +458,7 @@ @if ( - euProject.programType === 'h2020' && + programType === 'h2020' && euProject.ercPrincipalInvestigators && euProject.ercPrincipalInvestigators.length > 0 ) { @@ -434,7 +492,7 @@
} - + + + + @if (activeTab === 'organizations' && euProject.organizations) { + } diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss index 19553278..60c230aa 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -163,7 +163,7 @@ h1 { .status-badge:hover { transform: translateY(-1px); - box-shadow: 0 2px 8px rgba(0,0,0,0.15); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); } .status-badge mat-icon { @@ -376,49 +376,20 @@ h1 { opacity: 1; } -.keywords-grid { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 10px; - padding: 16px 20px 20px; -} - -.keyword-item { +.interest-tags { display: flex; - align-items: center; - justify-content: space-between; - padding: 10px 14px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; - cursor: pointer; - transition: all 0.2s; - position: relative; + flex-wrap: wrap; + gap: 12px; + padding: 16px 20px 12px; } - -.keyword-item:hover { - background: #f8fafc; - border-color: #b8c5d6; - transform: translateY(-1px); -} - -.keyword-value { - color: var(--sg-text); - font-size: 13px; - word-break: break-word; -} - -.keyword-item .search-icon { +.interest-tags .interest-empty { + padding: 9px 16px; + border: 1px solid #e2e8f0; + border-style: dashed; + border-radius: 7px; color: var(--sg-text-muted); - width: 16px; - height: 16px; - font-size: 16px; - opacity: 0; - transition: opacity 0.2s; -} - -.keyword-item:hover .search-icon { - opacity: 1; + font-size: 13px; + font-weight: 600; } .details-list { @@ -541,20 +512,11 @@ h1 { font-size: 16px; } -// Utility function for date formatting -.format-date { - // Handled in component -} - -@media (max-width: 992px) { +@media (max-width: 1116px) { .content-grid { grid-template-columns: 1fr; gap: 20px; } - - .keywords-grid { - grid-template-columns: 1fr 1fr; - } } @media (max-width: 768px) { @@ -585,16 +547,16 @@ h1 { grid-template-columns: 1fr; gap: 4px; } - + .eyebrow { gap: 8px; } - + .topics-grid { grid-template-columns: 1fr; } - - .keywords-grid { + + .interest-tags { grid-template-columns: 1fr; } } @@ -607,7 +569,7 @@ h1 { .hero-actions { flex-direction: column; } - + .status-badge, .scheme-info, .doi-link { @@ -624,17 +586,17 @@ h1 { font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; - + &.fp7 { background: #e8eaf6; color: #283593; } - + &.h2020 { background: #e3f2fd; color: #0d47a1; } - + &.heu { background: #e8f5e9; color: #1b5e20; @@ -667,18 +629,18 @@ h1 { cursor: pointer; transition: all 0.2s; white-space: nowrap; - + &:hover { background: rgba(0, 0, 0, 0.04); color: var(--sg-text); } - + &.active { background: #fff; color: var(--sg-primary, #0066cc); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); } - + mat-icon { width: 20px; height: 20px; @@ -705,123 +667,15 @@ h1 { } @keyframes fadeIn { - from { opacity: 0; transform: translateY(8px); } - to { opacity: 1; transform: translateY(0); } -} - -// Organizations -.organizations-list { - padding: 16px 20px 20px; - display: flex; - flex-direction: column; - gap: 12px; -} - -.organization-item { - display: flex; - align-items: center; - gap: 16px; - padding: 14px 16px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; - cursor: pointer; - transition: all 0.2s; - - &:hover { - background: #f8fafc; - border-color: #b8c5d6; - transform: translateY(-1px); + from { + opacity: 0; + transform: translateY(8px); + } + to { + opacity: 1; + transform: translateY(0); } } - -.org-avatar { - display: flex; - align-items: center; - justify-content: center; - width: 40px; - height: 40px; - flex-shrink: 0; - background: #e8edf5; - border-radius: 50%; - color: var(--sg-text); - font-weight: 600; - font-size: 14px; -} - -.org-info { - flex: 1; - min-width: 0; -} - -.org-name { - font-weight: 500; - color: var(--sg-text); - font-size: 14px; -} - -.org-details { - display: flex; - flex-wrap: wrap; - gap: 8px; - margin-top: 4px; - font-size: 12px; - color: var(--sg-text-muted); - - .org-short { - font-weight: 500; - color: var(--sg-text); - } - - .org-role { - padding: 1px 8px; - background: #e8edf5; - border-radius: var(--sg-radius-sm); - color: var(--sg-text); - } - - .org-country { - padding: 1px 8px; - background: #e3f2fd; - border-radius: var(--sg-radius-sm); - color: #0d47a1; - } - - .org-sme-badge { - padding: 1px 8px; - background: #fff3e0; - border-radius: var(--sg-radius-sm); - color: #e65100; - font-weight: 600; - } - - .org-city { - color: var(--sg-text-muted); - } -} - -.org-contribution, -.org-cost { - display: flex; - flex-direction: column; - align-items: flex-end; - padding-left: 16px; - border-left: 1px solid #d9e2f0; - - .contribution-label, - .cost-label { - font-size: 11px; - color: var(--sg-text-muted); - } - - .contribution-value, - .cost-value { - font-weight: 600; - font-size: 14px; - color: var(--sg-text); - } -} - // Publications .publications-list { padding: 16px 20px 20px; @@ -839,7 +693,7 @@ h1 { border-radius: var(--sg-radius-sm); background: #fff; transition: all 0.2s; - + &:hover { background: #f8fafc; } @@ -848,7 +702,7 @@ h1 { .pub-icon { flex-shrink: 0; color: var(--sg-text-muted); - + mat-icon { width: 24px; height: 24px; @@ -880,11 +734,11 @@ h1 { margin-top: 4px; font-size: 12px; color: var(--sg-text-muted); - + .pub-journal { color: var(--sg-text); } - + .pub-year, .pub-publisher { color: var(--sg-text-muted); @@ -895,7 +749,7 @@ h1 { display: flex; gap: 8px; flex-shrink: 0; - + .pub-link { display: flex; align-items: center; @@ -905,12 +759,12 @@ h1 { border-radius: var(--sg-radius-sm); color: var(--sg-text-muted); transition: all 0.2s; - + &:hover { background: #e8edf5; color: var(--sg-primary, #0066cc); } - + mat-icon { width: 18px; height: 18px; @@ -936,7 +790,7 @@ h1 { border-radius: var(--sg-radius-sm); background: #fff; transition: all 0.2s; - + &:hover { background: #f8fafc; } @@ -945,7 +799,7 @@ h1 { .ipr-icon { flex-shrink: 0; color: #f39c12; - + mat-icon { width: 24px; height: 24px; @@ -970,7 +824,7 @@ h1 { gap: 8px; margin-top: 4px; font-size: 12px; - + .ipr-type { padding: 1px 8px; background: #fff3e0; @@ -978,14 +832,14 @@ h1 { color: #e65100; font-weight: 500; } - + .ipr-patent-type { padding: 1px 8px; background: #e8eaf6; border-radius: var(--sg-radius-sm); color: #283593; } - + .ipr-applicant { color: var(--sg-text-muted); } @@ -998,7 +852,7 @@ h1 { margin-top: 4px; font-size: 11px; color: var(--sg-text-muted); - + .ipr-app-id, .ipr-award-id { padding: 1px 8px; @@ -1024,7 +878,7 @@ h1 { border-radius: var(--sg-radius-sm); background: #fff; transition: all 0.2s; - + &:hover { background: #f8fafc; } @@ -1033,7 +887,7 @@ h1 { .deliv-icon { flex-shrink: 0; color: #7b1fa2; - + mat-icon { width: 24px; height: 24px; @@ -1059,25 +913,25 @@ h1 { margin-top: 4px; font-size: 12px; align-items: center; - + .deliv-type { padding: 1px 8px; background: #f3e5f5; border-radius: var(--sg-radius-sm); color: #7b1fa2; } - + .deliv-link { display: inline-flex; align-items: center; gap: 4px; color: var(--sg-primary, #0066cc); text-decoration: none; - + &:hover { text-decoration: underline; } - + mat-icon { width: 16px; height: 16px; @@ -1088,33 +942,156 @@ h1 { // EuroSciVoc .eurosci-voc-grid { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 8px; + display: flex; + flex-direction: column; + gap: 12px; padding: 16px 20px 20px; } .eurosci-voc-item { display: flex; align-items: center; - gap: 8px; - padding: 8px 12px; + gap: 12px; + padding: 12px 16px; background: #f8fafc; - border-radius: var(--sg-radius-sm); - border: 1px solid #d9e2f0; - - .voc-code { - font-weight: 600; - font-size: 12px; - color: var(--sg-text-muted); - background: #e8edf5; - padding: 2px 8px; - border-radius: var(--sg-radius-sm); + border: 1px solid #e6e9ed; + border-radius: 8px; + flex-wrap: wrap; +} + +.eurosci-voc-item.clickable:hover { + background: #f0f3f7; + border-color: #b8c5d6; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); +} + +.eurosci-voc-item .voc-path { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; + flex: 1; + min-width: 200px; +} + +.eurosci-voc-item .path-segment { + font-size: 13px; + font-weight: 500; + color: #1a1a1a; + padding: 2px 8px; + border-radius: 4px; + background: #fff; + border: 1px solid #e6e9ed; +} + +.eurosci-voc-item .path-segment:last-child { + background: #e8f0fe; + border-color: #c5d8f0; + color: #005a9c; + font-weight: 600; +} + +.eurosci-voc-item .path-separator { + width: 16px; + height: 16px; + font-size: 16px; + color: #6b7a8a; +} + +.eurosci-voc-item .voc-code { + font-size: 12px; + color: #6b7a8a; + font-family: monospace; + background: #eef2f7; + padding: 2px 8px; + border-radius: 4px; + white-space: nowrap; +} + +.eurosci-voc-item .voc-description { + font-size: 13px; + color: #6b7a8a; + font-style: italic; +} + +// Alternative: Horizontal chip-style layout +.eurosci-voc-grid-chips { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 16px 20px 20px; +} + +.eurosci-voc-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + background: #f8fafc; + border: 1px solid #e6e9ed; + border-radius: 20px; + font-size: 13px; +} + +.eurosci-voc-chip:hover { + background: #f0f3f7; + border-color: #b8c5d6; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); +} + +.eurosci-voc-chip .chip-path { + display: flex; + align-items: center; + gap: 4px; +} + +.eurosci-voc-chip .chip-segment { + font-weight: 500; +} + +.eurosci-voc-chip .chip-separator { + font-size: 12px; + color: #6b7a8a; +} + +.eurosci-voc-chip .chip-segment:last-child { + color: #005a9c; +} + +// Responsive +@media (max-width: 768px) { + .eurosci-voc-item { + flex-direction: column; + align-items: flex-start; + gap: 8px; } - - .voc-title { - font-size: 13px; - color: var(--sg-text); + + .eurosci-voc-item .voc-path { + min-width: 100%; + } + + .eurosci-voc-item .search-icon { + opacity: 1; + align-self: flex-end; + } + + .eurosci-voc-item .path-segment { + font-size: 12px; + } +} + +@media (max-width: 480px) { + .eurosci-voc-item { + padding: 10px 12px; + } + + .eurosci-voc-item .path-segment { + font-size: 11px; + padding: 1px 6px; + } + + .eurosci-voc-item .voc-code { + font-size: 10px; } } @@ -1134,13 +1111,13 @@ h1 { background: #f8fafc; border-radius: var(--sg-radius-sm); border: 1px solid #d9e2f0; - + .pi-name { font-weight: 500; color: var(--sg-text); font-size: 14px; } - + .pi-title { color: var(--sg-text-muted); font-size: 13px; @@ -1159,34 +1136,21 @@ h1 { gap: 2px; padding: 0 2px; } - + .tab-btn { padding: 8px 12px; font-size: 12px; - + mat-icon { width: 16px; height: 16px; font-size: 16px; } } - - .organization-item, + .publication-item, .ipr-item, .deliverable-item { flex-wrap: wrap; } - - .org-contribution, - .org-cost { - width: 100%; - padding-left: 0; - padding-top: 8px; - border-left: none; - border-top: 1px solid #d9e2f0; - flex-direction: row; - gap: 8px; - align-items: center; - } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index 58a47b81..558b9851 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -9,11 +9,19 @@ import { MatButtonModule } from '@angular/material/button'; import { MatDividerModule } from '@angular/material/divider'; import { MatTooltipModule } from '@angular/material/tooltip'; import { Router } from '@angular/router'; -import { formatGermanDate } from '../../../shared/utils/formatters'; -import { Data } from '../../../api'; - - -export type TabType = 'overview' | 'organizations' | 'publications' | 'iprs' | 'deliverables'; +import { + formatGermanDate, + formatCurrency, +} from '../../../shared/utils/formatters'; +import { EuProjectData } from '../../../api/model/euProjectData'; +import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; +import { OrganizationsTableComponent } from './organizations-table/organizations-table/organizations-table.component'; +export type TabType = + | 'overview' + | 'organizations' + | 'publications' + | 'iprs' + | 'deliverables'; @Component({ selector: 'app-eu-details', @@ -26,6 +34,8 @@ export type TabType = 'overview' | 'organizations' | 'publications' | 'iprs' | ' MatButtonModule, MatDividerModule, MatTooltipModule, + TopicChipComponent, + OrganizationsTableComponent, ], templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', @@ -33,21 +43,20 @@ export type TabType = 'overview' | 'organizations' | 'publications' | 'iprs' | ' export class EuDetailsComponent implements OnInit { private route = inject(ActivatedRoute); private router = inject(Router); - - euProject: Data| undefined; + + euProject: EuProjectData | undefined; activeTab: TabType = 'overview'; - programType: String = "" + programType: String = ''; // Track if tabs have content hasOrganizations = false; hasPublications = false; hasIprs = false; hasDeliverables = false; - ngOnInit(): void { // Subscribe to route data for project this.route.data.subscribe(({ euSingleProject }) => { console.log('EU Project:', euSingleProject); - this.euProject = euSingleProject.data; + this.euProject = euSingleProject.eu_project_data; // Determine program type if (this.euProject) { @@ -58,28 +67,34 @@ export class EuDetailsComponent implements OnInit { } else if (euSingleProject.deliverables !== undefined) { this.programType = 'heu'; } - // Check which tabs have content - this.hasOrganizations = this.euProject.organizations && this.euProject.organizations.length > 0 || false; - this.hasPublications = this.euProject.publications && this.euProject.publications.length > 0 || false; - this.hasIprs = this.euProject.iprs && this.euProject.iprs.length > 0 || false; - this.hasDeliverables = this.euProject.deliverables && this.euProject.deliverables.length > 0 || false; + this.hasOrganizations = + (this.euProject.organizations && + this.euProject.organizations.length > 0) || + false; + this.hasPublications = + (this.euProject.publications && + this.euProject.publications.length > 0) || + false; + this.hasIprs = + (this.euProject.iprs && this.euProject.iprs.length > 0) || false; + this.hasDeliverables = + (this.euProject.deliverables && + this.euProject.deliverables.length > 0) || + false; } }); // Subscribe to query params for tab synchronization - this.route.queryParams.subscribe(params => { + this.route.queryParams.subscribe((params) => { const tabParam = params['tab'] as TabType; if (tabParam && this.isValidTab(tabParam)) { - // Check if the tab has content before switching if (this.tabHasContent(tabParam)) { this.activeTab = tabParam; } else { - // If tab has no content, switch to overview and update URL this.updateTabQueryParam('overview'); } } else { - // If no valid tab param, set to overview and update URL this.updateTabQueryParam('overview'); } }); @@ -89,7 +104,13 @@ export class EuDetailsComponent implements OnInit { * Check if a tab value is valid */ private isValidTab(tab: string): tab is TabType { - return ['overview', 'organizations', 'publications', 'iprs', 'deliverables'].includes(tab); + return [ + 'overview', + 'organizations', + 'publications', + 'iprs', + 'deliverables', + ].includes(tab); } /** @@ -128,12 +149,12 @@ export class EuDetailsComponent implements OnInit { */ setTab(tab: TabType): void { if (this.activeTab === tab) return; - + // Check if tab has content if (!this.tabHasContent(tab)) { return; } - + this.activeTab = tab; this.updateTabQueryParam(tab); } @@ -145,13 +166,6 @@ export class EuDetailsComponent implements OnInit { return this.activeTab === tab; } - /** - * Check if a tab should be visible (has content) - */ - shouldShowTab(tab: TabType): boolean { - return this.tabHasContent(tab); - } - /** * Get tab label with count */ @@ -184,16 +198,6 @@ export class EuDetailsComponent implements OnInit { } } - - getInitials(name: string | null | undefined): string { - if (!name) return ''; - const parts = name.trim().split(/\s+/); - if (parts.length > 1) { - return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); - } - return parts[0][0].toUpperCase(); - } - getFundingStatus(endDate: string | null | undefined): string { if (!endDate) return 'N/A'; const end = new Date(endDate); @@ -204,17 +208,6 @@ export class EuDetailsComponent implements OnInit { return end >= now ? 'Laufend' : 'Abgeschlossen'; } - formatCurrency(amount: number | null | undefined): string { - if (amount === null || amount === undefined) return 'N/A'; - - return new Intl.NumberFormat('de-DE', { - style: 'currency', - currency: 'EUR', - minimumFractionDigits: 0, - maximumFractionDigits: 0, - }).format(amount); - } - getDuration(start: string | undefined, end: string | undefined): string { if (!start || !end) return ''; @@ -228,6 +221,13 @@ export class EuDetailsComponent implements OnInit { return date; } + formatCurr(value: number | undefined | null) { + if (value) { + return formatCurrency(value); + } + return value; + } + getStatusColor(status: string | null | undefined): string { if (!status) return '#95a5a6'; @@ -317,6 +317,62 @@ export class EuDetailsComponent implements OnInit { return []; } + /** + * Get keywords mapped to topic chip format + */ + getKeywordChips(): { + label: string; + count?: number; + description?: string; + subfieldName?: string; + fieldName?: string; + domainName?: string; + color?: string; + id?: string; + }[] { + const keywords = this.getKeywords(this.euProject?.keywords); + if (keywords.length === 0) return []; + + // Simple keyword list + return keywords.map((keyword, index) => ({ + label: keyword, + count: 1, + description: `Schlüsselwort: ${keyword}`, + subfieldName: '', + fieldName: '', + domainName: '', + color: this.getKeywordColor(index), + id: keyword, + })); + } + + /** + * Get color for keyword based on index + */ + private getKeywordColor(index: number): string { + const colors = [ + '#3498db', // Blue + '#e67e22', // Orange + '#27ae60', // Green + '#8e44ad', // Purple + '#e74c3c', // Red + '#1abc9c', // Teal + '#f39c12', // Gold + '#2c3e50', // Navy + ]; + return colors[index % colors.length]; + } + + /** + * Get path segments from a path string + * Example: "natural sciences/chemical sciences/polymer sciences" + * => ["natural sciences", "chemical sciences", "polymer sciences"] + */ + getPathSegments(path: string | undefined): string[] { + if (!path) return []; + return path.split('/').filter((segment) => segment.trim()); + } + getTotalEcContribution(): number { if (!this.euProject?.organizations) return 0; return this.euProject.organizations @@ -364,16 +420,4 @@ export class EuDetailsComponent implements OnInit { queryParams: { status: status }, }); } - - searchForInstitutionName(institutionName: string): void { - this.router.navigate(['/institutions'], { - queryParams: { - search: institutionName, - }, - }); - } - - goBack(): void { - window.history.back(); - } -} \ No newline at end of file +} From 577a927e20961c416342321e11ee61b68ac79639 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 11:28:52 +0200 Subject: [PATCH 41/81] created separated component for organization table for EU Cordis Projects --- .../organizations-table.component.html | 126 ++++++++++++++++ .../organizations-table.component.scss | 137 ++++++++++++++++++ .../organizations-table.component.ts | 50 +++++++ 3 files changed, 313 insertions(+) create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html new file mode 100644 index 00000000..b1a68c07 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html @@ -0,0 +1,126 @@ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name +
+ {{ + org.name || org.shortName || 'Unbekannte Organisation' + }} +
+
Rolle + @if (org.role) { + {{ org.role }} + } @else { + — + } + Stadt + @if (org.city) { + + {{ org.city }} + + + + } @else { + — + } + EU-Beitrag + @if (org.ecContribution) { + {{ + formatCurr(org.ecContribution) + }} + } @else { + — + } + Aktivitätstyp + @if (org.activityType) { + {{ org.activityType }} + } @else { + — + } + SME + @if (org.sme) { + SME + } @else { + — + } + URL + @if (org.organizationURL) { + + open_in_new + + } @else { + — + } +
+
+
+
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss new file mode 100644 index 00000000..a9c7c11a --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss @@ -0,0 +1,137 @@ + +// Organizations + +.organizations-tab { + .card { + margin-bottom: 24px; + } + + .organizations-table-wrapper { + padding: 0 20px 20px; + overflow-x: auto; + + table { + width: 100%; + border-radius: 8px; + overflow: hidden; + } + + .mat-mdc-header-cell { + font-weight: 600; + color: #6b7a8a; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.5px; + background: #f8fafc; + border-bottom: 2px solid #e6e9ed; + padding: 12px 16px; + } + + .mat-mdc-cell { + padding: 12px 16px; + border-bottom: 1px solid #f0f2f5; + font-size: 13px; + } + + .mat-mdc-row { + transition: background 0.2s ease; + } + + .mat-mdc-row:hover { + background: #f8fafc; + } + } + + .org-name-cell { + display: flex; + align-items: center; + gap: 24px; + cursor: pointer; + } + + .org-name-text { + font-weight: 500; + color: #1a1a1a; + } + + .org-name-cell:hover .org-name-text { + color: #005a9c; + text-decoration: underline; + } + + .role-chip { + display: inline-block; + padding: 2px 10px; + background: #e8edf5; + border-radius: 12px; + font-size: 12px; + color: #6b7a8a; + } + + .country-chip { + display: inline-flex; + align-items: center; + gap: 10px; + font-size: 13px; + } + + .currency-value { + font-weight: 500; + color: #1a1a1a; + } + + .empty-value { + color: #6b7a8a; + } + + .activity-chip { + display: inline-block; + padding: 2px 10px; + background: #f0f3f7; + border-radius: 12px; + font-size: 12px; + color: #6b7a8a; + } + + .sme-badge { + display: inline-block; + padding: 2px 8px; + background: #e8f5e9; + color: #2e7d32; + border-radius: 4px; + font-weight: 500; + font-size: 12px; + } + .url-badge { + display: inline-block; + padding: 2px 8px; + background: #e8f5e9; + color: #2e7d32; + border-radius: 4px; + font-weight: 500; + font-size: 12px; + } +} + +@media (max-width: 768px) { + .organizations-tab { + .organizations-table-wrapper { + padding: 0 12px 12px; + } + + .mat-mdc-header-cell, + .mat-mdc-cell { + padding: 8px 10px; + font-size: 12px; + } + .country-flag { + font-size: 18px; + line-height: 1; + } + .org-avatar-small { + width: 24px; + height: 24px; + font-size: 10px; + } + } +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts new file mode 100644 index 00000000..7bc5e3e8 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts @@ -0,0 +1,50 @@ +import { Component, inject,Input } from '@angular/core'; +import { MatTableModule } from '@angular/material/table'; +import { Router } from '@angular/router'; +import { formatCurrency } from '../../../../../shared/utils/formatters'; +import { MatIcon } from '@angular/material/icon'; +import { MatCard } from '@angular/material/card'; +import { HEUOrganization } from '../../../../../api'; +@Component({ + selector: 'app-organizations-table', + imports: [MatTableModule,MatIcon,MatCard], + templateUrl: './organizations-table.component.html', + styleUrl: './organizations-table.component.scss', +}) +export class OrganizationsTableComponent { + private router = inject(Router); + + @Input() orgs!: HEUOrganization[]; + + // Displayed columns for the organizations table + organizationDisplayedColumns: string[] = [ + 'name', + 'role', + 'country', + 'ecContribution', + 'activityType', + 'sme', + 'organizationURL', + ]; + + searchForInstitutionName(institutionName: string): void { + this.router.navigate(['/institutions'], { + queryParams: { + search: institutionName, + }, + }); + } + getSvgByCountryCode(code: string) { + const codeLower = code.toLowerCase(); + if (codeLower === 'uk') { + return 'gb'; + } + return codeLower; + } + formatCurr(value: number | undefined | null) { + if (value) { + return formatCurrency(value); + } + return value; + } +} From fa3209d2532af1cdbe07c1af438ffd7bfe4ae919 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 11:29:08 +0200 Subject: [PATCH 42/81] added currency formatter --- webapp/src/app/shared/utils/formatters.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/webapp/src/app/shared/utils/formatters.ts b/webapp/src/app/shared/utils/formatters.ts index 58cc03bc..3131672a 100644 --- a/webapp/src/app/shared/utils/formatters.ts +++ b/webapp/src/app/shared/utils/formatters.ts @@ -7,3 +7,14 @@ export function formatGermanDate(dateString: string): string { year: 'numeric', }).format(new Date(dateString)); } + +export function formatCurrency(amount: number | null | undefined): string { + if (amount === null || amount === undefined) return 'N/A'; + + return new Intl.NumberFormat('de-DE', { + style: 'currency', + currency: 'EUR', + minimumFractionDigits: 0, + maximumFractionDigits: 0, + }).format(amount); +} From a7e4039342b1253ded15160eb7ecf762958a3969 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 19:12:07 +0200 Subject: [PATCH 43/81] added searching for work by DOI and Title fallback --- service/src/main/inse/works/logic.py | 18 ++--- service/src/main/inse/works/search_client.py | 77 +++++++++++++++----- service/src/main/inse/works/service.py | 18 +++-- 3 files changed, 75 insertions(+), 38 deletions(-) diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 9d5918cf..3bd7a9a2 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -197,22 +197,16 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: async def get_work( work_id: str, + title:str, client: OpenAlexWorksSearchClient | None = None, ) -> Work: search_client = client or OpenAlexWorksSearchClient() - try: - data = await search_client.search_work(work_id) - except MissingApiKeyError as exc: - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="OpenAlex works search is not configured.", - ) from exc - except httpx.HTTPError as exc: - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + + data = await search_client.search_work(work_id) elements, _ = _parse_full_work_search_response(data) + if (not elements) and title: + response_by_title = await search_client.search_for_work_by_title(title=title) + elements, _ = _parse_full_work_search_response(response_by_title) if not elements: raise HTTPException( status_code=HTTP_404_NOT_FOUND, diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index fe60c665..93188678 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -7,10 +7,10 @@ import logging from typing import Any import httpx - +import urllib from .. import config - - +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex class MissingApiKeyError(Exception): pass @@ -164,23 +164,62 @@ class OpenAlexWorksSearchClient: response.raise_for_status() return response.json() - async def search_work(self, work_id: str) -> dict[str, Any]: + + async def search_work(self, identifier: str) -> dict[str, Any]: + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + decoded_id = urllib.parse.unquote(identifier) + body = { + "query": { + "bool": { + "should": [ + { + "term": { + "_id": { + "value": decoded_id, + "boost": 5 + } + } + }, + { + "term": { + "doi": { + "value": "https://doi.org/" + decoded_id.lower(), + "boost": 3 + } + } + } + ], + "minimum_should_match": 1 + } + } + } + print(body) + response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) + return response + + async def search_for_work_by_title( + self, + title: str, + ) -> dict[str, Any]: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}" - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json={ - "size": 1, - "query": {"term": {"id": indexed_work_id}}, + query_clauses = [ + {"match_phrase": {"title": title}}, + ] + + body = { + "query": { + "bool": { + "must": query_clauses, }, - ) - response.raise_for_status() - return response.json() + }, + "sort": [ + {"publication_year": {"order": "desc", "missing": "_last"}}, + {"cited_by_count": {"order": "desc", "missing": "_last"}}, + ], + } + response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) + + return response \ No newline at end of file diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index e0d84c57..38d44230 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -4,7 +4,7 @@ REST API for publication works. """ -from typing import Annotated +from typing import Annotated, Optional from fastapi import APIRouter from fastapi import Depends @@ -123,17 +123,21 @@ async def get_topics_by_time_by_author( @router.get( - "/detail/{work_id}", + "/detail/{identifier}", operation_id="getWork", response_model=Work, - summary="Returns one publication.", + summary="Returns one publication by OpenAlex ID or DOI.", ) -async def get_work( - work_id: Annotated[ - str, Path(description="The OpenAlex work id, for example W2741809807.") +async def get_work_by_identifier( + identifier: Annotated[ + str, Path(description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.") ], + title: Annotated[ + Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?") + ] = "", principal: security.Principal = Depends( security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) ), ): - return await logic.get_work(work_id) + print("RUN SERVICE") + return await logic.get_work(identifier,title=title) \ No newline at end of file From 19af4e1abcac4ed3502331fed97b9b2a0ad0c8f9 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 19:12:33 +0200 Subject: [PATCH 44/81] regenerated service --- service/src/main/inse/works/service.py | 1 - webapp/src/app/api/api/works.service.ts | 33 +++++++++++++++++-------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py index 38d44230..42399bad 100644 --- a/service/src/main/inse/works/service.py +++ b/service/src/main/inse/works/service.py @@ -139,5 +139,4 @@ async def get_work_by_identifier( security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"]) ), ): - print("RUN SERVICE") return await logic.get_work(identifier,title=title) \ No newline at end of file diff --git a/webapp/src/app/api/api/works.service.ts b/webapp/src/app/api/api/works.service.ts index 20d855a3..82f38cbe 100644 --- a/webapp/src/app/api/api/works.service.ts +++ b/webapp/src/app/api/api/works.service.ts @@ -619,14 +619,16 @@ export class WorksService extends BaseService { } /** - * Returns one publication. - * @endpoint get /api/works/detail/{work_id} - * @param workId The OpenAlex work id, for example W2741809807. + * 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( - workId: string, + identifier: string, + title?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -636,7 +638,8 @@ export class WorksService extends BaseService { }, ): Observable; public getWork( - workId: string, + identifier: string, + title?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -646,7 +649,8 @@ export class WorksService extends BaseService { }, ): Observable>; public getWork( - workId: string, + identifier: string, + title?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -656,7 +660,8 @@ export class WorksService extends BaseService { }, ): Observable>; public getWork( - workId: string, + identifier: string, + title?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -665,12 +670,19 @@ export class WorksService extends BaseService { transferCache?: boolean; }, ): Observable { - if (workId === null || workId === undefined) { + if (identifier === null || identifier === undefined) { throw new Error( - 'Required parameter workId was null or undefined when calling getWork.', + '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; // authentication (bearer) required @@ -709,10 +721,11 @@ export class WorksService extends BaseService { } } - let localVarPath = `/api/works/detail/${this.configuration.encodeParam({ name: 'workId', value: workId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + 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, From de35748ba733db529142273c86f1470b695ed7c5 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 19:13:07 +0200 Subject: [PATCH 45/81] added resolver for work search --- webapp/src/app/app.routes.ts | 5 ++- .../publication-detail.component.ts | 44 +++++-------------- .../src/app/resolvers/publication-resolver.ts | 16 +++++++ 3 files changed, 31 insertions(+), 34 deletions(-) create mode 100644 webapp/src/app/resolvers/publication-resolver.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a4021d4f..734b521b 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -17,7 +17,7 @@ import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects- import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver'; import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver'; import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'; - +import { publicationResolver } from './resolvers/publication-resolver'; export const routes: Routes = [ { path: '', @@ -106,6 +106,9 @@ export const routes: Routes = [ import('./modules/publication-detail/publication-detail.component').then( (mod) => mod.PublicationDetailComponent, ), + resolve: { + publication: publicationResolver, + }, }, { path: 'projects/dfg/:id', 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 2eeb7feb..c2850656 100644 --- a/webapp/src/app/modules/publication-detail/publication-detail.component.ts +++ b/webapp/src/app/modules/publication-detail/publication-detail.component.ts @@ -8,7 +8,6 @@ import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { ActivatedRoute, RouterLink } from '@angular/router'; import { finalize } from 'rxjs'; - import { Authorship, Location as ApiLocation, @@ -54,18 +53,18 @@ export class PublicationDetailComponent implements OnInit { notFound = false; ngOnInit(): void { - this.route.paramMap - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe((params) => { - const publicationId = params.get('publicationId'); - if (!publicationId) { - this.loading = false; - this.notFound = true; - return; - } + this.loading = true; - this.loadPublication(publicationId); - }); + this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: ({ publication }) => { + this.publication = publication; + this.loading = false; + }, + error: () => { + this.notFound = true; + this.loading = false; + }, + }); } navigateBack(): void { @@ -157,27 +156,6 @@ export class PublicationDetailComponent implements OnInit { return 'Kein Open Access'; } - private loadPublication(publicationId: string): void { - this.loading = true; - this.notFound = false; - this.publication = null; - - const basePath = this.worksService.configuration.basePath ?? ''; - this.httpClient - .get( - `${basePath}/api/works/detail/${encodeURIComponent(publicationId)}`, - ) - .pipe(finalize(() => (this.loading = false))) - .subscribe({ - next: (publication) => { - this.publication = publication; - }, - error: () => { - this.notFound = true; - }, - }); - } - private doiUrl(doi: string | null | undefined): string | null { if (!doi) return null; return doi.startsWith('http') ? doi : `https://doi.org/${doi}`; diff --git a/webapp/src/app/resolvers/publication-resolver.ts b/webapp/src/app/resolvers/publication-resolver.ts new file mode 100644 index 00000000..d0e1111e --- /dev/null +++ b/webapp/src/app/resolvers/publication-resolver.ts @@ -0,0 +1,16 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { WorksService,Work } from '../api'; + +export const publicationResolver: ResolveFn = (route) => { + + const id = route.paramMap.get('publicationId'); + const title = route.queryParamMap.get('title') ?? ''; + const worksService = inject(WorksService); + + if (!id) { + throw new Error('Publication id is required'); + } + + return worksService.getWork(id, title); +}; From d23e8474aee132dfdffc8b758bb51d3cf5ef7ebb Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 19:13:38 +0200 Subject: [PATCH 46/81] added searchForPublication function to publications list --- .../eu-details.component.html | 2 +- .../eu-cordis-details/eu-details.component.ts | 342 ++++++++++++------ 2 files changed, 240 insertions(+), 104 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index b8ff2eea..367eda5c 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -568,7 +568,7 @@
@for (pub of euProject.publications; track pub.doi) { -
+
article
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index 558b9851..a73c2e04 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -1,6 +1,6 @@ -// eu-details.component.ts (updated) -import { Component, OnInit, inject } from '@angular/core'; -import { ActivatedRoute } from '@angular/router'; +// eu-details.component.ts (refactored) +import { Component, OnInit, inject, OnDestroy } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; import { CommonModule } from '@angular/common'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; @@ -8,7 +8,7 @@ import { MatChipsModule } from '@angular/material/chips'; import { MatButtonModule } from '@angular/material/button'; import { MatDividerModule } from '@angular/material/divider'; import { MatTooltipModule } from '@angular/material/tooltip'; -import { Router } from '@angular/router'; +import { Subscription } from 'rxjs'; import { formatGermanDate, formatCurrency, @@ -16,6 +16,8 @@ import { import { EuProjectData } from '../../../api/model/euProjectData'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; import { OrganizationsTableComponent } from './organizations-table/organizations-table/organizations-table.component'; +import { HEUPublication } from '../../../api'; + export type TabType = | 'overview' | 'organizations' @@ -40,77 +42,123 @@ export type TabType = templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', }) -export class EuDetailsComponent implements OnInit { +export class EuDetailsComponent implements OnInit, OnDestroy { private route = inject(ActivatedRoute); private router = inject(Router); + // Data euProject: EuProjectData | undefined; + programType: string = ''; + + // UI State activeTab: TabType = 'overview'; - programType: String = ''; - // Track if tabs have content + isLoading = true; + + // Tab content flags hasOrganizations = false; hasPublications = false; hasIprs = false; hasDeliverables = false; + + // Subscriptions + private subscriptions: Subscription = new Subscription(); + + // Tab configuration + private readonly tabConfig: Record = { + overview: { label: 'Übersicht', icon: 'info', order: 0 }, + organizations: { label: 'Organisationen', icon: 'business', order: 1 }, + publications: { label: 'Publikationen', icon: 'article', order: 2 }, + iprs: { label: 'IPRs', icon: 'gavel', order: 3 }, + deliverables: { label: 'Ergebnisse', icon: 'assignment', order: 4 } + }; + ngOnInit(): void { - // Subscribe to route data for project - this.route.data.subscribe(({ euSingleProject }) => { - console.log('EU Project:', euSingleProject); - this.euProject = euSingleProject.eu_project_data; + // Subscribe to route data + this.subscriptions.add( + this.route.data.subscribe(({ euSingleProject }) => { + console.log('EU Project:', euSingleProject); + this.euProject = euSingleProject.eu_project_data; + this.isLoading = false; - // Determine program type - if (this.euProject) { - if (euSingleProject.iprs !== undefined) { - this.programType = 'fp7'; - } else if (euSingleProject.ercPrincipalInvestigators !== undefined) { - this.programType = 'h2020'; - } else if (euSingleProject.deliverables !== undefined) { - this.programType = 'heu'; + if (this.euProject) { + this.determineProgramType(euSingleProject); + this.updateTabContentFlags(); + this.handleTabFromQueryParams(); } - // Check which tabs have content - this.hasOrganizations = - (this.euProject.organizations && - this.euProject.organizations.length > 0) || - false; - this.hasPublications = - (this.euProject.publications && - this.euProject.publications.length > 0) || - false; - this.hasIprs = - (this.euProject.iprs && this.euProject.iprs.length > 0) || false; - this.hasDeliverables = - (this.euProject.deliverables && - this.euProject.deliverables.length > 0) || - false; - } - }); + }) + ); - // Subscribe to query params for tab synchronization - this.route.queryParams.subscribe((params) => { - const tabParam = params['tab'] as TabType; - if (tabParam && this.isValidTab(tabParam)) { - if (this.tabHasContent(tabParam)) { - this.activeTab = tabParam; - } else { + // Subscribe to query params changes + this.subscriptions.add( + this.route.queryParams.subscribe((params) => { + // Only handle if data is already loaded + if (this.euProject) { + this.handleTabFromQueryParams(params); + } + }) + ); + } + + ngOnDestroy(): void { + this.subscriptions.unsubscribe(); + } + + // ============= PRIVATE METHODS ============= + + /** + * Determine program type based on available data + */ + private determineProgramType(euSingleProject: any): void { + if (euSingleProject.iprs !== undefined) { + this.programType = 'fp7'; + } else if (euSingleProject.ercPrincipalInvestigators !== undefined) { + this.programType = 'h2020'; + } else if (euSingleProject.deliverables !== undefined) { + this.programType = 'heu'; + } + } + + /** + * Update flags for which tabs have content + */ + private updateTabContentFlags(): void { + this.hasOrganizations = + (this.euProject?.organizations && this.euProject.organizations.length > 0) || false; + this.hasPublications = + (this.euProject?.publications && this.euProject.publications.length > 0) || false; + this.hasIprs = + (this.euProject?.iprs && this.euProject.iprs.length > 0) || false; + this.hasDeliverables = + (this.euProject?.deliverables && this.euProject.deliverables.length > 0) || false; + } + + /** + * Handle tab selection from query params + */ + private handleTabFromQueryParams(params?: any): void { + const queryParams = params || this.route.snapshot.queryParams; + const tabParam = queryParams['tab'] as TabType; + + if (tabParam && this.isValidTab(tabParam)) { + if (this.tabHasContent(tabParam)) { + this.activeTab = tabParam; + } else { + // Only update if it's a different tab + if (this.activeTab !== 'overview') { this.updateTabQueryParam('overview'); } - } else { - this.updateTabQueryParam('overview'); } - }); + } else if (!queryParams['tab'] && this.activeTab !== 'overview') { + // Set default tab only if no tab param exists + this.updateTabQueryParam('overview'); + } } /** * Check if a tab value is valid */ private isValidTab(tab: string): tab is TabType { - return [ - 'overview', - 'organizations', - 'publications', - 'iprs', - 'deliverables', - ].includes(tab); + return ['overview', 'organizations', 'publications', 'iprs', 'deliverables'].includes(tab); } /** @@ -137,21 +185,45 @@ export class EuDetailsComponent implements OnInit { * Update URL query param for tab */ private updateTabQueryParam(tab: TabType): void { + // Prevent unnecessary navigation + const currentTab = this.route.snapshot.queryParams['tab']; + if (currentTab === tab) return; + this.router.navigate([], { relativeTo: this.route, queryParams: { tab: tab }, - queryParamsHandling: 'merge', // Preserve other query params - }); + queryParamsHandling: 'merge', + }).catch(err => console.error('Tab navigation failed:', err)); } + /** + * Get color for keyword based on index + */ + private getKeywordColor(index: number): string { + const colors = [ + '#3498db', // Blue + '#e67e22', // Orange + '#27ae60', // Green + '#8e44ad', // Purple + '#e74c3c', // Red + '#1abc9c', // Teal + '#f39c12', // Gold + '#2c3e50', // Navy + ]; + return colors[index % colors.length]; + } + + // ============= PUBLIC METHODS ============= + /** * Set active tab and update URL */ setTab(tab: TabType): void { if (this.activeTab === tab) return; - + // Check if tab has content if (!this.tabHasContent(tab)) { + console.warn(`Tab "${tab}" has no content`); return; } @@ -166,18 +238,25 @@ export class EuDetailsComponent implements OnInit { return this.activeTab === tab; } + /** + * Check if tab is visible (has content) + */ + isTabVisible(tab: TabType): boolean { + return this.tabHasContent(tab); + } + /** * Get tab label with count */ getTabLabel(tab: TabType): string { - const labels: Record = { - overview: 'Übersicht', - organizations: 'Organisationen', - publications: 'Publikationen', - iprs: 'IPRs', - deliverables: 'Ergebnisse', - }; - return labels[tab]; + return this.tabConfig[tab].label; + } + + /** + * Get tab icon + */ + getTabIcon(tab: TabType): string { + return this.tabConfig[tab].icon; } /** @@ -198,6 +277,17 @@ export class EuDetailsComponent implements OnInit { } } + /** + * Get sorted tabs that have content + */ + getVisibleTabs(): TabType[] { + return (['overview', 'organizations', 'publications', 'iprs', 'deliverables'] as TabType[]) + .filter(tab => this.tabHasContent(tab)) + .sort((a, b) => this.tabConfig[a].order - this.tabConfig[b].order); + } + + // ============= FORMATTING METHODS ============= + getFundingStatus(endDate: string | null | undefined): string { if (!endDate) return 'N/A'; const end = new Date(endDate); @@ -210,22 +300,21 @@ export class EuDetailsComponent implements OnInit { getDuration(start: string | undefined, end: string | undefined): string { if (!start || !end) return ''; - return `von ${formatGermanDate(start)} bis ${formatGermanDate(end)}`; } - formatDate(date: string | undefined) { + formatDate(date: string | undefined): string | undefined { if (date) { return formatGermanDate(date); } return date; } - formatCurr(value: number | undefined | null) { + formatCurr(value: number | undefined | null): string | null | undefined { if (value) { return formatCurrency(value); } - return value; + return String(value); } getStatusColor(status: string | null | undefined): string { @@ -234,10 +323,7 @@ export class EuDetailsComponent implements OnInit { const statusUpper = status.toUpperCase(); if (statusUpper.includes('CLOSED') || statusUpper.includes('COMPLETED')) { return '#27ae60'; - } else if ( - statusUpper.includes('ONGOING') || - statusUpper.includes('ACTIVE') - ) { + } else if (statusUpper.includes('ONGOING') || statusUpper.includes('ACTIVE')) { return '#f39c12'; } else if (statusUpper.includes('SIGNED')) { return '#3498db'; @@ -283,15 +369,13 @@ export class EuDetailsComponent implements OnInit { if (!scheme) return 'N/A'; const schemeMap: { [key: string]: string } = { - 'MSCA-IF-EF-SE': - 'MSCA Individual Fellowship - European Fellowship - Standard', + 'MSCA-IF-EF-SE': 'MSCA Individual Fellowship - European Fellowship - Standard', 'MSCA-IF-EF': 'MSCA Individual Fellowship - European Fellowship', 'MSCA-IF-GF': 'MSCA Individual Fellowship - Global Fellowship', 'MSCA-IF': 'MSCA Individual Fellowship', 'MSCA-ITN': 'MSCA Innovative Training Networks', 'MSCA-RISE': 'MSCA Research and Innovation Staff Exchange', - 'MSCA-COFUND': - 'MSCA Co-funding of Regional, National and International Programmes', + 'MSCA-COFUND': 'MSCA Co-funding of Regional, National and International Programmes', }; return schemeMap[scheme] || scheme; @@ -333,7 +417,6 @@ export class EuDetailsComponent implements OnInit { const keywords = this.getKeywords(this.euProject?.keywords); if (keywords.length === 0) return []; - // Simple keyword list return keywords.map((keyword, index) => ({ label: keyword, count: 1, @@ -346,27 +429,8 @@ export class EuDetailsComponent implements OnInit { })); } - /** - * Get color for keyword based on index - */ - private getKeywordColor(index: number): string { - const colors = [ - '#3498db', // Blue - '#e67e22', // Orange - '#27ae60', // Green - '#8e44ad', // Purple - '#e74c3c', // Red - '#1abc9c', // Teal - '#f39c12', // Gold - '#2c3e50', // Navy - ]; - return colors[index % colors.length]; - } - /** * Get path segments from a path string - * Example: "natural sciences/chemical sciences/polymer sciences" - * => ["natural sciences", "chemical sciences", "polymer sciences"] */ getPathSegments(path: string | undefined): string[] { if (!path) return []; @@ -390,34 +454,106 @@ export class EuDetailsComponent implements OnInit { return Array.from(countries); } - // Search functions + // ============= SEARCH / NAVIGATION METHODS ============= + + /** + * Navigate to projects with topic filter + */ searchByTopic(topic: string): void { + if (!topic) { + console.warn('Cannot search with empty topic'); + return; + } + this.router.navigate(['/eu-projects'], { queryParams: { topic: topic }, - }); + }).catch(err => console.error('Navigation to topic failed:', err)); } + /** + * Navigate to projects with keyword filter + */ searchByKeyword(keyword: string): void { + if (!keyword) { + console.warn('Cannot search with empty keyword'); + return; + } + this.router.navigate(['/eu-projects'], { queryParams: { keyword: keyword }, - }); + }).catch(err => console.error('Navigation to keyword failed:', err)); } + /** + * Navigate to projects with framework filter + */ searchByFramework(framework: string): void { + if (!framework) { + console.warn('Cannot search with empty framework'); + return; + } + this.router.navigate(['/eu-projects'], { queryParams: { framework: framework }, - }); + }).catch(err => console.error('Navigation to framework failed:', err)); } + /** + * Navigate to projects with funding scheme filter + */ searchByFundingScheme(scheme: string): void { + if (!scheme) { + console.warn('Cannot search with empty funding scheme'); + return; + } + this.router.navigate(['/eu-projects'], { queryParams: { fundingScheme: scheme }, - }); + }).catch(err => console.error('Navigation to funding scheme failed:', err)); } + /** + * Navigate to projects with status filter + */ searchByStatus(status: string): void { + if (!status) { + console.warn('Cannot search with empty status'); + return; + } + this.router.navigate(['/eu-projects'], { queryParams: { status: status }, - }); + }).catch(err => console.error('Navigation to status failed:', err)); } -} + + /** + * Navigate to publication details + */ + searchForPublication(pub: HEUPublication): void { + if (!pub) { + console.warn('Cannot navigate with empty publication'); + return; + } + + const doi = pub.doi?.trim() ?? "unknown"; + + // Encode DOI and navigate + const encodedDoi = encodeURIComponent(doi); + + this.router.navigate(['/publication', encodedDoi], { + queryParams: { + title: pub.title || '' + }, + }).catch(err => console.error('Navigation to publication failed:', err)); + } + + /** + * Navigate back to projects list with optional filter + */ + goBack(filters?: { [key: string]: any }): void { + this.router.navigate(['/eu-projects'], { + queryParams: filters || {}, + queryParamsHandling: 'merge', + }).catch(err => console.error('Navigation back failed:', err)); + } +} \ No newline at end of file From f3bfffc4c642f673a23ae501eb495e94b47964c6 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 25 Jun 2026 19:23:18 +0200 Subject: [PATCH 47/81] feat(patents): add global patents page with search, filter, pagination and detail view --- service/src/main/inse/main.py | 2 + .../elastic_search_all_patents_client.py | 133 +++++ service/src/main/inse/patents/logic.py | 556 ++++++++++-------- service/src/main/inse/patents/model.py | 6 + service/src/main/inse/patents/service.py | 31 +- webapp/src/app/api/api/patents.service.ts | 74 ++- webapp/src/app/app.routes.ts | 101 +--- .../modules/patents/patents.component.html | 248 ++++++++ .../modules/patents/patents.component.scss | 280 +++++++++ .../app/modules/patents/patents.component.ts | 310 ++++++++++ .../shared/ui/app-menu/app-menu.component.ts | 7 + 11 files changed, 1396 insertions(+), 352 deletions(-) create mode 100644 service/src/main/inse/patents/elastic_search_all_patents_client.py create mode 100644 webapp/src/app/modules/patents/patents.component.html create mode 100644 webapp/src/app/modules/patents/patents.component.scss create mode 100644 webapp/src/app/modules/patents/patents.component.ts diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 7dae7575..4c51d74c 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -32,6 +32,7 @@ from inse.institutions.router import router as institutions_router from . import config from .account.service import router as account_router from .service import router as service_router +from inse.patents.service import router as patents_service_router, patents_router as patents_all_router logger = logging.getLogger(__name__) @@ -58,6 +59,7 @@ app.include_router(account_router) app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) +app.include_router(patents_all_router) app.add_middleware( ETagCacheMiddleware, diff --git a/service/src/main/inse/patents/elastic_search_all_patents_client.py b/service/src/main/inse/patents/elastic_search_all_patents_client.py new file mode 100644 index 00000000..4584f40b --- /dev/null +++ b/service/src/main/inse/patents/elastic_search_all_patents_client.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + HTTP client for fetching all patents from EPO and USPTO Elasticsearch indices. +""" +from typing import Any + +import httpx + +from .. import config +from .elastic_search_client import MissingApiKeyError + +EPO_INDEX = "epo_index_1.0" +USPTO_INDEX = "uspto_patents_3.0" + + +class AllPatentsSearchClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float = 30.0, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key + self.timeout = timeout + self.transport = transport + + def _headers(self) -> dict[str, str]: + if not self.api_key: + raise MissingApiKeyError("Patent Elasticsearch API key is not configured.") + return { + "Authorization": f"ApiKey {self.api_key}", + "Content-Type": "application/json", + } + + def epo_query( + self, + page: int = 0, + size: int = 10, + search: str | None = None, + sort_direction: str = "desc", + ) -> dict[str, Any]: + sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"] + + if search and search.strip(): + term = search.strip() + doc_number = term.upper().removeprefix("EP") + query: dict[str, Any] = { + "bool": { + "should": [ + {"match_phrase": {"title_en": {"query": term}}}, + {"match_phrase": {"title_de": {"query": term}}}, + {"term": {"doc_number": doc_number}}, + ], + "minimum_should_match": 1, + } + } + else: + query = {"match_all": {}} + + return { + "from": page * size, + "size": size, + "track_total_hits": True, + "sort": sort, + "_source": [ + "doc_number", "country", "kind", "date_publication", + "date_publication_year", "application_number", + "application_filing_date", "title_en", "title_de", + "abstract", "inventors_name", "applicants_name", "ipc", "cpc", + ], + "query": query, + } + + def uspto_query( + self, + page: int = 0, + size: int = 10, + search: str | None = None, + sort_direction: str = "desc", + ) -> dict[str, Any]: + sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"] + + if search and search.strip(): + term = search.strip() + pub_number = term.upper().removeprefix("US") + query: dict[str, Any] = { + "bool": { + "should": [ + {"match_phrase": {"title": {"query": term}}}, + {"term": {"publication_number": pub_number}}, + ], + "minimum_should_match": 1, + } + } + else: + query = {"match_all": {}} + + return { + "from": page * size, + "size": size, + "track_total_hits": True, + "sort": sort, + "_source": [ + "publication_number", "country", "publication_date", + "publication_year", "application_number", "application_date", + "application_type", "title", "abstract", "inventors_names", + "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", + ], + "query": query, + } + + async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: + return await self._search(EPO_INDEX, payload) + + async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]: + return await self._search(USPTO_INDEX, payload) + + async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{index}/_search", + headers=self._headers(), + json=payload, + ) + response.raise_for_status() + return response.json() \ No newline at end of file diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 65765f1f..76594b9a 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -1,248 +1,308 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - Business logic for patent matching by author name. -""" -import logging - -import httpx -from fastapi import HTTPException -from starlette.status import HTTP_502_BAD_GATEWAY -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE - -from ..persons import logic as person_logic -from ..models.openalex.author import Author -from . import model -from .elastic_search_client import MissingApiKeyError -from .elastic_search_client import PatentSearchClient -from .ipc_search_client import IpcSearchClient -from .ipc_lookup import extract_ipc_symbol -from .name_matching import name_matches - -logger = logging.getLogger(__name__) - - -async def get_patents_by_author_id( - author_id: str, - client: PatentSearchClient | None = None, - ipc_client: IpcSearchClient | None = None, -) -> model.PatentsByAuthorResponse: - search_client = client or PatentSearchClient() - ipc_search_client = ipc_client or IpcSearchClient() - - author = _get_author(author_id) - if not author: - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=None, - patent_count=0, - patents=[], - ) - - author_name = author.display_name - last_name = _extract_last_name(author_name) - first_name = _extract_first_name(author_name) - - if not last_name: - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=author_name, - patent_count=0, - patents=[], - ) - - try: - epo_data, uspto_data = await _search_both_indices( - search_client, last_name, first_name - ) - except MissingApiKeyError as exc: - raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Patent search is not configured.") from exc - except httpx.HTTPError as exc: - raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, - detail="Patent search request failed.") from exc - - all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) - - if first_name and last_name: - all_patents = _filter_patents_by_name(all_patents, first_name, last_name) - - all_patents = _deduplicate_patents(all_patents) - - await _enrich_patents_classifications(all_patents, ipc_search_client) - - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=author_name, - patent_count=len(all_patents), - patents=all_patents, - ) - - -async def _search_both_indices(client, last_name, first_name): - import asyncio - epo_result, uspto_result = await asyncio.gather( - client.search_epo(client.epo_query_by_inventor(last_name, first_name)), - client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)), - ) - return epo_result, uspto_result - - -def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: - patents = [] - for hit in data.get("hits", {}).get("hits", []): - src = hit.get("_source", {}) - inventors = src.get("inventors_name") or [] - applicants = src.get("applicants_name") or [] - ipc = src.get("ipc") or [] - cpc = src.get("cpc") or [] - patents.append(model.PatentEntry( - patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", - source="EPO", - title=src.get("title_en") or src.get("title_de"), - abstract=src.get("abstract"), - publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, - publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, - application_number=src.get("application_number"), - application_date=src.get("application_filing_date"), - kind=src.get("kind"), - inventors=inventors if isinstance(inventors, list) else [inventors], - assignees=applicants if isinstance(applicants, list) else [applicants], - ipc=_to_classification_strings(ipc), - cpc=_to_classification_strings(cpc), - country=src.get("country", "EP"), - )) - return patents - - -def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: - patents = [] - for hit in data.get("hits", {}).get("hits", []): - src = hit.get("_source", {}) - inventors = src.get("inventors_names") or [] - assignees = src.get("assignees_orgs") or [] - ipc = src.get("ipcr") or [] - cpc = src.get("cpc") or [] - patents.append(model.PatentEntry( - patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}", - source="USPTO", - title=src.get("title"), - abstract=src.get("abstract"), - publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, - publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, - application_number=src.get("application_number"), - application_date=str(src.get("application_date")) if src.get("application_date") else None, - application_type=src.get("application_type"), - number_of_claims=src.get("number_of_claims"), - status=src.get("status"), - inventors=inventors if isinstance(inventors, list) else [inventors], - assignees=assignees if isinstance(assignees, list) else [assignees], - ipc=_to_classification_strings(ipc), - cpc=_to_classification_strings(cpc), - country=src.get("country", "US"), - )) - return patents - - -def _to_classification_strings(value) -> list[str]: - if not value: - return [] - items = value if isinstance(value, list) else [value] - return [str(item).strip() for item in items if item and str(item).strip()] - - -def _descriptions_for_raw_codes( - raw_codes: list[str], - resolved: dict[str, model.IpcClassification], -) -> list[model.IpcClassification]: - return [ - resolved[extract_ipc_symbol(raw)] - for raw in raw_codes - if extract_ipc_symbol(raw) in resolved - ] - - -async def _enrich_patents_classifications( - patents: list[model.PatentEntry], - ipc_client: IpcSearchClient, -) -> None: - symbols = list(dict.fromkeys( - extract_ipc_symbol(raw) - for patent in patents - for raw in (*patent.ipc, *patent.cpc) - )) - if not symbols: - return - - try: - resolved = await ipc_client.resolve_symbols(symbols) - except MissingApiKeyError: - logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.") - return - except httpx.HTTPError as exc: - logger.warning("Classification enrichment failed: %s", exc) - return - except Exception as exc: - logger.exception("Classification enrichment failed unexpectedly: %s", exc) - return - - for patent in patents: - patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved) - patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved) - - -def _filter_patents_by_name( - patents: list[model.PatentEntry], - first_name: str, - last_name: str, -) -> list[model.PatentEntry]: - """Keep patents where at least one inventor matches the author name.""" - return [ - patent for patent in patents - if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors) - ] - - -def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]: - """Remove exact duplicate hits while keeping distinct publication stages.""" - seen: set[tuple[str, str, str, str]] = set() - deduplicated: list[model.PatentEntry] = [] - - for patent in patents: - key = _patent_dedup_key(patent) - if key in seen: - continue - seen.add(key) - deduplicated.append(patent) - - return deduplicated - - -def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]: - stage = patent.kind or patent.application_type or "" - return ( - patent.source, - patent.patent_id, - patent.publication_date or "", - stage, - ) - - -def _get_author(author_id: str) -> Author | None: - short_id = author_id.replace("https://openalex.org/", "") - result = person_logic.search_persons(author_id=short_id) - return result.results[0] if result.results else None - - -def _extract_last_name(name: str | None) -> str | None: - if not name: - return None - parts = name.strip().split() - return parts[-1] if parts else None - - -def _extract_first_name(name: str | None) -> str | None: - if not name: - return None - parts = name.strip().split() - return parts[0] if len(parts) > 1 else None \ No newline at end of file +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Business logic for patent matching by author name. +""" +import logging +import asyncio + +import httpx +from fastapi import HTTPException +from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_503_SERVICE_UNAVAILABLE + +from ..persons import logic as person_logic +from ..models.openalex.author import Author +from . import model +from .elastic_search_client import MissingApiKeyError +from .elastic_search_client import PatentSearchClient +from .elastic_search_all_patents_client import AllPatentsSearchClient +from .ipc_search_client import IpcSearchClient +from .ipc_lookup import extract_ipc_symbol +from .name_matching import name_matches + +logger = logging.getLogger(__name__) + + +async def get_patents_by_author_id( + author_id: str, + client: PatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, +) -> model.PatentsByAuthorResponse: + search_client = client or PatentSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() + + author = _get_author(author_id) + if not author: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=None, + patent_count=0, + patents=[], + ) + + author_name = author.display_name + last_name = _extract_last_name(author_name) + first_name = _extract_first_name(author_name) + + if not last_name: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=0, + patents=[], + ) + + try: + epo_data, uspto_data = await _search_both_indices( + search_client, last_name, first_name + ) + except MissingApiKeyError as exc: + raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.") from exc + except httpx.HTTPError as exc: + raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, + detail="Patent search request failed.") from exc + + all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) + + if first_name and last_name: + all_patents = _filter_patents_by_name(all_patents, first_name, last_name) + + all_patents = _deduplicate_patents(all_patents) + + await _enrich_patents_classifications(all_patents, ipc_search_client) + + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=len(all_patents), + patents=all_patents, + ) + + +async def _search_both_indices(client, last_name, first_name): + epo_result, uspto_result = await asyncio.gather( + client.search_epo(client.epo_query_by_inventor(last_name, first_name)), + client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)), + ) + return epo_result, uspto_result + + +def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: + patents = [] + for hit in data.get("hits", {}).get("hits", []): + src = hit.get("_source", {}) + inventors = src.get("inventors_name") or [] + applicants = src.get("applicants_name") or [] + ipc = src.get("ipc") or [] + cpc = src.get("cpc") or [] + patents.append(model.PatentEntry( + patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", + source="EPO", + title=src.get("title_en") or src.get("title_de"), + abstract=src.get("abstract"), + publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, + publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, + application_number=src.get("application_number"), + application_date=src.get("application_filing_date"), + kind=src.get("kind"), + inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None], + assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None], + ipc=_to_classification_strings(ipc), + cpc=_to_classification_strings(cpc), + country=src.get("country", "EP"), + )) + return patents + + +def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: + patents = [] + for hit in data.get("hits", {}).get("hits", []): + src = hit.get("_source", {}) + inventors = src.get("inventors_names") or [] + assignees = src.get("assignees_orgs") or [] + ipc = src.get("ipcr") or [] + cpc = src.get("cpc") or [] + patents.append(model.PatentEntry( + patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}", + source="USPTO", + title=src.get("title"), + abstract=src.get("abstract"), + publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, + publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, + application_number=src.get("application_number"), + application_date=str(src.get("application_date")) if src.get("application_date") else None, + application_type=src.get("application_type"), + number_of_claims=src.get("number_of_claims"), + status=src.get("status"), + inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None], + assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None], + ipc=_to_classification_strings(ipc), + cpc=_to_classification_strings(cpc), + country=src.get("country", "US"), + )) + return patents + + +def _to_classification_strings(value) -> list[str]: + if not value: + return [] + items = value if isinstance(value, list) else [value] + return [str(item).strip() for item in items if item and str(item).strip()] + + +def _descriptions_for_raw_codes( + raw_codes: list[str], + resolved: dict[str, model.IpcClassification], +) -> list[model.IpcClassification]: + return [ + resolved[extract_ipc_symbol(raw)] + for raw in raw_codes + if extract_ipc_symbol(raw) in resolved + ] + + +async def _enrich_patents_classifications( + patents: list[model.PatentEntry], + ipc_client: IpcSearchClient, +) -> None: + symbols = list(dict.fromkeys( + extract_ipc_symbol(raw) + for patent in patents + for raw in (*patent.ipc, *patent.cpc) + )) + if not symbols: + return + + try: + resolved = await ipc_client.resolve_symbols(symbols) + except MissingApiKeyError: + logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.") + return + except httpx.HTTPError as exc: + logger.warning("Classification enrichment failed: %s", exc) + return + except Exception as exc: + logger.exception("Classification enrichment failed unexpectedly: %s", exc) + return + + for patent in patents: + patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved) + patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved) + + +def _filter_patents_by_name( + patents: list[model.PatentEntry], + first_name: str, + last_name: str, +) -> list[model.PatentEntry]: + return [ + patent for patent in patents + if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors) + ] + + +def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]: + seen: set[tuple[str, str, str, str]] = set() + deduplicated: list[model.PatentEntry] = [] + + for patent in patents: + key = _patent_dedup_key(patent) + if key in seen: + continue + seen.add(key) + deduplicated.append(patent) + + return deduplicated + + +def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]: + stage = patent.kind or patent.application_type or "" + return ( + patent.source, + patent.patent_id, + patent.publication_date or "", + stage, + ) + + +def _get_author(author_id: str) -> Author | None: + short_id = author_id.replace("https://openalex.org/", "") + result = person_logic.search_persons(author_id=short_id) + return result.results[0] if result.results else None + + +def _extract_last_name(name: str | None) -> str | None: + if not name: + return None + parts = name.strip().split() + return parts[-1] if parts else None + + +def _extract_first_name(name: str | None) -> str | None: + if not name: + return None + parts = name.strip().split() + return parts[0] if len(parts) > 1 else None + + +async def get_all_patents( + page: int = 0, + size: int = 10, + search: str | None = None, + source: str | None = None, + sort_by: str = "date", + sort_direction: str = "desc", + client: PatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, +) -> model.AllPatentsResponse: + all_patents_client = AllPatentsSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() + + try: + if source == "EPO": + epo_data = await all_patents_client.search_epo( + all_patents_client.epo_query(page, size, search, sort_direction) + ) + patents = _parse_epo_hits(epo_data) + total = epo_data.get("hits", {}).get("total", {}).get("value", 0) + + elif source == "USPTO": + uspto_data = await all_patents_client.search_uspto( + all_patents_client.uspto_query(page, size, search, sort_direction) + ) + patents = _parse_uspto_hits(uspto_data) + total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) + + else: + half = size // 2 + epo_data, uspto_data = await asyncio.gather( + all_patents_client.search_epo( + all_patents_client.epo_query(page, half, search, sort_direction) + ), + all_patents_client.search_uspto( + all_patents_client.uspto_query(page, half, search, sort_direction) + ), + ) + patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) + total = ( + epo_data.get("hits", {}).get("total", {}).get("value", 0) + + uspto_data.get("hits", {}).get("total", {}).get("value", 0) + ) + + except MissingApiKeyError as exc: + raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.") from exc + except httpx.HTTPError as exc: + raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, + detail="Patent search request failed.") from exc + + await _enrich_patents_classifications(patents, ipc_search_client) + + return model.AllPatentsResponse( + total=total, + page=page, + size=size, + patents=patents, + ) \ No newline at end of file diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index f00a17c3..ad26f939 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -38,4 +38,10 @@ class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int + patents: list[PatentEntry] + +class AllPatentsResponse(BaseModel): + total: int + page: int + size: int patents: list[PatentEntry] \ No newline at end of file diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py index 53a27446..c2a8eb49 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -1,14 +1,13 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -""" - REST API for patent matching by author. -""" from fastapi import APIRouter from . import logic from . import model router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) +patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"]) + @router.get( "/{author_id}/patents", @@ -17,4 +16,28 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) summary="Get patents matched to an author by name.", ) async def get_patents_by_author(author_id: str): - return await logic.get_patents_by_author_id(author_id) + return await logic.get_patents_by_author_id(author_id) + + +@patents_router.get( + "/patents", + operation_id="getAllPatents", + response_model=model.AllPatentsResponse, + summary="Get all patents with pagination and search.", +) +async def get_all_patents( + page: int = 0, + size: int = 10, + search: str | None = None, + source: str | None = None, + sort_by: str = "date", + sort_direction: str = "desc", +): + return await logic.get_all_patents( + page=page, + size=size, + search=search, + source=source, + sort_by=sort_by, + sort_direction=sort_direction, + ) \ No newline at end of file diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 4ec5192e..7d1986e9 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,8 +1,3 @@ -/** - * Innovation Search Engine API - */ -/* tslint:disable:no-unused-variable member-ordering */ - import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, @@ -10,13 +5,10 @@ import { HttpParams, HttpResponse, HttpEvent, - HttpParameterCodec, HttpContext, } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; - -// @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; @@ -59,6 +51,13 @@ export interface PatentsByAuthorResponse { patents: PatentEntry[]; } +export interface AllPatentsResponse { + total: number; + page: number; + size: number; + patents: PatentEntry[]; +} + type GetPatentsByAuthorOptions = { httpHeaderAccept?: 'application/json'; context?: HttpContext; @@ -77,13 +76,6 @@ export class PatentsService extends BaseService { super(basePath, configuration); } - /** - * Get patents by author. - * @endpoint get /api/inse-service/authors/{author_id}/patents - * @param authorId - * @param observe - * @param reportProgress - */ public getPatentsByAuthor( authorId: string, observe?: 'body', @@ -115,7 +107,6 @@ export class PatentsService extends BaseService { } let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept(['application/json']); @@ -128,7 +119,6 @@ export class PatentsService extends BaseService { const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - const localVarTransferCache: boolean = options?.transferCache ?? true; let responseType_: 'text' | 'json' | 'blob' = 'json'; @@ -144,15 +134,17 @@ export class PatentsService extends BaseService { } } - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ - name: 'authorId', - value: authorId, - in: 'path', - style: 'simple', - explode: false, - dataType: 'string', - dataFormat: undefined, - })}/patents`; + 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( @@ -171,4 +163,34 @@ export class PatentsService extends BaseService { }, ); } + + public getAllPatents( + page: number = 0, + size: number = 10, + search?: string, + source?: string, + sortBy: string = 'date', + sortDirection: string = 'desc', + ): Observable { + let params = new HttpParams() + .set('page', String(page)) + .set('size', String(size)) + .set('sort_by', sortBy) + .set('sort_direction', sortDirection); + + if (search) params = params.set('search', search); + if (source) params = params.set('source', source); + + const localVarHeaders = this.defaultHeaders; + const { basePath, withCredentials } = this.configuration; + + return this.httpClient.get( + `${basePath}/api/inse-service/patents`, + { + params, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + }, + ); + } } diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 7976278b..9ade0a5e 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -55,30 +55,17 @@ export const routes: Routes = [ }, runGuardsAndResolvers: (to, from) => { const keys = [ - 'query', - 'page', - 'pageSize', - 'institutionName', - 'sortBy', - 'sortOrder', - 'yearFilterEnabled', - 'filterMode', - 'filterYear', + 'query', 'page', 'pageSize', 'institutionName', + 'sortBy', 'sortOrder', 'yearFilterEnabled', 'filterMode', 'filterYear', ]; - - // scalar params const scalarChanged = keys.some( (key) => to.queryParamMap.get(key) !== from.queryParamMap.get(key), ); - - // multi-value param: topics const toTopics = to.queryParamMap.getAll('topic'); const fromTopics = from.queryParamMap.getAll('topic'); - const topicsChanged = toTopics.length !== fromTopics.length || toTopics.some((t, i) => t !== fromTopics[i]); - return scalarChanged || topicsChanged; }, }, @@ -98,9 +85,7 @@ export const routes: Routes = [ import('./modules/person-projects/dfg-details/dfg-details.component').then( (mod) => mod.DfgDetailsComponent, ), - resolve: { - dfgSingleProject: dfgSingleProjectResolver, - }, + resolve: { dfgSingleProject: dfgSingleProjectResolver }, }, { path: 'projects/bund/:id', @@ -110,9 +95,7 @@ export const routes: Routes = [ import('./modules/person-projects/bund-details/bund-details.component').then( (mod) => mod.BundDetailsComponent, ), - resolve: { - bundSingleProject: bundSingleProjectResolver, - }, + resolve: { bundSingleProject: bundSingleProjectResolver }, }, { path: 'person/:id', @@ -127,11 +110,7 @@ export const routes: Routes = [ }, runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'], children: [ - { - path: '', - pathMatch: 'full', - redirectTo: 'overview', - }, + { path: '', pathMatch: 'full', redirectTo: 'overview' }, { path: 'overview', loadComponent: () => @@ -145,12 +124,9 @@ export const routes: Routes = [ import('./modules/person-projects/person-projects.component').then( (mod) => mod.PersonProjectsComponent, ), - resolve: { - dfgProjectPage: dfgProjectsResolver, - }, + resolve: { dfgProjectPage: dfgProjectsResolver }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; - return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), ); @@ -169,29 +145,18 @@ export const routes: Routes = [ import('./modules/person-network/person-network.component').then( (mod) => mod.PersonNetworkComponent, ), - resolve: { - collaborationNetwork: collaborationNetworkResolver, - }, + resolve: { collaborationNetwork: collaborationNetworkResolver }, runGuardsAndResolvers: (from, to) => { - // No need to re-run for different table view or search term const keys = [ - 'filter_by', - 'start_year', - 'end_year', - 'min_contributors', - 'max_contributors', - 'min_collaborations', - 'max_collaborations', - 'institutions', - 'topics', + 'filter_by', 'start_year', 'end_year', 'min_contributors', + 'max_contributors', 'min_collaborations', 'max_collaborations', + 'institutions', 'topics', ]; - return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), ); }, }, - { path: 'funding', loadComponent: () => @@ -222,12 +187,9 @@ export const routes: Routes = [ import('./modules/institutions/institutions.component').then( (mod) => mod.InstitutionsComponent, ), - resolve: { - institutionPage: institutionsResolver, - }, + resolve: { institutionPage: institutionsResolver }, runGuardsAndResolvers: (from, to) => { const keys = ['search', 'page', 'size', 'sort_by', 'sorting_order']; - return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), ); @@ -240,15 +202,9 @@ export const routes: Routes = [ import('./modules/institution/institution.component').then( (mod) => mod.InstitutionComponent, ), - resolve: { - institution: institutionResolver, - }, + resolve: { institution: institutionResolver }, children: [ - { - path: '', - pathMatch: 'full', - redirectTo: 'overview', - }, + { path: '', pathMatch: 'full', redirectTo: 'overview' }, { path: 'overview', loadComponent: () => @@ -265,11 +221,10 @@ export const routes: Routes = [ }, { path: 'projects', - loadComponent: () => { - return import('./modules/institution-projects/institution-projects.component').then( + loadComponent: () => + import('./modules/institution-projects/institution-projects.component').then( (mod) => mod.InstitutionProjectsComponent, - ); - }, + ), resolve: { bundProjectPage: bundProjectPageResolver, bundProjectsFunding: bundProjectsFundingResolver, @@ -278,7 +233,6 @@ export const routes: Routes = [ }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; - return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), ); @@ -293,24 +247,24 @@ export const routes: Routes = [ import('./modules/projects/projects.component').then( (mod) => mod.ProjectsComponent, ), - resolve: { - fundingProjectPage: fundingProjectPageResolver, - }, + resolve: { fundingProjectPage: fundingProjectPageResolver }, runGuardsAndResolvers: (from, to) => { const keys = [ - 'search', - 'page', - 'size', - 'selected_project_types', - 'sort_by', - 'sorting_order', + 'search', 'page', 'size', 'selected_project_types', 'sort_by', 'sorting_order', ]; - return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), ); }, }, + { + path: 'patents', + canActivate: [userGuard], + loadComponent: () => + import('./modules/patents/patents.component').then( + (mod) => mod.PatentsComponent, + ), + }, { path: 'error', loadComponent: () => @@ -327,8 +281,7 @@ export const routes: Routes = [ data: { routeStatusCode: 404, routeTitle: 'Seite nicht gefunden', - routeMessage: - 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.', + routeMessage: 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.', }, canActivate: [userGuard], }, diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html new file mode 100644 index 00000000..76c7df46 --- /dev/null +++ b/webapp/src/app/modules/patents/patents.component.html @@ -0,0 +1,248 @@ +
+

Patente

+ + + +
+ + Suche nach Titel oder Patent-Nr. + + search + + + +
+ + Alle + EPO + USPTO + + +
+ +
+
+
+ + + + @if (loading) { +
+ + Lade Patente... +
+ } @else if (error) { +

Fehler beim Laden der Patente.

+ } @else if (showDetail && selectedPatent) { +
+ + +

{{ selectedPatent.title ?? selectedPatent.patent_id }}

+ +
+ @for (row of getPatentMetadataRows(selectedPatent); track row.label) { +
+
{{ row.label }}
+
+ @if (row.variant === 'source') { + {{ row.value }} + } @else { + {{ row.value }} + } +
+
+ } +
+ + @if (selectedPatent.abstract) { +
+

Abstract

+

{{ selectedPatent.abstract }}

+
+ } + +
+

Erfinder

+
    + @for (inv of selectedPatent.inventors; track inv) { +
  • {{ inv }}
  • + } +
+
+ + @if (selectedPatent.assignees.length > 0) { +
+

Anmelder

+
    + @for (a of selectedPatent.assignees; track a) { +
  • {{ a }}
  • + } +
+
+ } + + @if (selectedPatent.ipc_descriptions.length > 0) { +
+

Klassifikation (IPC)

+
+ @for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) { +
+
+
+ @for (sym of card.symbols; track sym) { + {{ sym }} + } +
+
+ {{ card.system }} + {{ card.levelLabel }} +
+
+ @if (card.primaryDescription) { +

+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }} +

+ @if (isLongDescription(card.primaryDescription)) { + + } + } + @if (card.hierarchy.length > 0) { +
+ @for (row of card.hierarchy; track row.label) { +
+
{{ row.label }}
+
{{ row.value }}
+
+ } +
+ } +
+ } +
+
+ } @else if (selectedPatent.ipc.length > 0) { +
+

Klassifikation (IPC)

+
    + @for (ipc of selectedPatent.ipc; track ipc) { +
  • {{ ipc }}
  • + } +
+
+ } + + @if (selectedPatent.cpc_descriptions.length > 0) { +
+

Klassifikation (CPC)

+
+ @for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) { +
+
+
+ @for (sym of card.symbols; track sym) { + {{ sym }} + } +
+
+ {{ card.system }} + {{ card.levelLabel }} +
+
+ @if (card.primaryDescription) { +

+ {{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }} +

+ @if (isLongDescription(card.primaryDescription)) { + + } + } + @if (card.hierarchy.length > 0) { +
+ @for (row of card.hierarchy; track row.label) { +
+
{{ row.label }}
+
{{ row.value }}
+
+ } +
+ } +
+ } +
+
+ } @else if (selectedPatent.cpc.length > 0) { +
+

Klassifikation (CPC)

+
    + @for (cpc of selectedPatent.cpc; track cpc) { +
  • {{ cpc }}
  • + } +
+
+ } +
+ } @else if (patents.length === 0) { +
+

Keine Patente gefunden.

+
+ } @else { +
+ @for (patent of patents; track patent.patent_id + (patent.publication_date ?? '')) { + + + {{ patent.title ?? patent.patent_id }} + + {{ patent.source }} + + + + + + + + + + + + + + } +
+ } + + + + @if (!showDetail) { + + } +
diff --git a/webapp/src/app/modules/patents/patents.component.scss b/webapp/src/app/modules/patents/patents.component.scss new file mode 100644 index 00000000..e19ca6e1 --- /dev/null +++ b/webapp/src/app/modules/patents/patents.component.scss @@ -0,0 +1,280 @@ +.content { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem; +} + +h1 { + margin: 0; + font-size: 2rem; + font-weight: 700; + padding: 1rem 0 0; +} + +.sorting { + display: flex; + justify-content: flex-end; + gap: 0.5rem; + + select { + padding: 0.75rem; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + font-size: 1rem; + cursor: pointer; + } +} + +.search-and-filter { + padding: 0 1rem; + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.filter-row { + display: flex; + justify-content: space-between; + align-items: center; +} + +.state-message { + display: flex; + align-items: center; + gap: 12px; + padding: 24px 1rem; + color: #666; + font-size: 14px; + + &.error { color: #c0392b; } +} + +.cards { + display: grid; + gap: 1.5rem; + grid-template-columns: repeat(4, 1fr); + padding: 0 1rem; +} + +@media (max-width: 900px) { + .cards { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (max-width: 600px) { + .cards { + grid-template-columns: 1fr; + } +} + +mat-paginator { + background-color: var(--sg-background); +} + +.card { + padding: 0.5rem; + background-color: var(--sg-background); + transition: transform 0.3s ease; + display: flex; + flex-direction: column; + gap: 0.5rem; + + &:hover { + cursor: pointer; + transform: scale(1.05); + } + + mat-card-title { + font-size: 14px; + font-weight: 600; + line-height: 1.4; + } +} + +.card-content { + display: flex; + flex-direction: column; + justify-content: flex-end; + gap: 0.5rem; + flex: 1; +} + +.card-metadata { + display: flex; + flex-direction: column; + gap: 0.2rem; + font-size: 0.9rem; + color: var(--sg-text-secondary); +} + +mat-card-actions { + padding-top: 0.5rem; + display: flex; + gap: 0.5rem; + + button { + width: 100%; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + } +} + +.source-badge { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 700; + + &--epo { background: #effaf3; color: #24834f; border: 1px solid #bdebcf; } + &--uspto { background: #f0f6ff; color: #0b63ce; border: 1px solid #bdd4ff; } +} + +.no-results { + text-align: center; + padding: 2rem; + color: var(--sg-text-secondary); +} + +.detail-view { + padding: 1rem; + + h2 { margin: 0 0 1rem; font-size: 1.4rem; color: #333; line-height: 1.4; } + h4 { margin: 16px 0 8px; font-size: 14px; color: #555; font-weight: 600; } + p { font-size: 13px; color: #444; line-height: 1.6; margin: 0; } +} + +.back-btn { + display: inline-flex; + align-items: center; + gap: 0.4rem; + margin-bottom: 1rem; + padding: 0.5rem 0.85rem; + border: 1px solid #d6e3f8; + border-radius: 999px; + background: #f8fbff; + color: #2563eb; + font-size: 0.9rem; + font-weight: 600; + cursor: pointer; + + &:hover { background: #eef5ff; border-color: #bcd3f7; } +} + +.patent-meta__list { + margin: 12px 0 20px; + border: 1px solid #e2e8f4; + border-radius: 12px; + background: linear-gradient(180deg, #fff 0%, #f8faff 100%); + overflow: hidden; +} + +.patent-meta__row { + display: grid; + grid-template-columns: minmax(130px, 38%) 1fr; + gap: 12px 16px; + align-items: center; + padding: 11px 16px; + border-top: 1px solid #eef2f8; + + &:first-child { border-top: 0; } + + dt { margin: 0; font-size: 12px; font-weight: 500; color: #64748b; } + dd { margin: 0; font-size: 14px; font-weight: 600; color: #1e293b; word-break: break-word; } +} + +.detail-section { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #eee; +} + +.tag-list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; + + &--compact .tag { font-size: 0.75rem; padding: 3px 8px; } +} + +.tag { + padding: 4px 10px; + border-radius: 999px; + background: #f0f6ff; + border: 1px solid #dbeafe; + color: #1e40af; + font-size: 0.8rem; +} + +.classification-section { + &--ipc .classification-card { background: #f0f6ff; border-color: #bfdbfe; } + &--ipc .classification-badge--system { background: #dbeafe; color: #1d4ed8; } + &--cpc .classification-card { background: #f0fdf4; border-color: #bbf7d0; } + &--cpc .classification-badge--system { background: #dcfce7; color: #15803d; } +} + +.classification-cards { display: flex; flex-direction: column; gap: 10px; } + +.classification-card { + padding: 12px 14px; + border-radius: 10px; + border: 1px solid #dbeafe; +} + +.classification-card__header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; +} + +.classification-card__codes { display: flex; flex-wrap: wrap; gap: 6px; } +.classification-card__badges { display: flex; flex-wrap: wrap; gap: 6px; } +.classification-code { font-size: 0.9rem; font-weight: 700; color: #0f172a; } + +.classification-badge { + display: inline-flex; + align-items: center; + padding: 2px 8px; + border-radius: 999px; + font-size: 0.68rem; + font-weight: 700; + text-transform: uppercase; +} + +.classification-badge--level { background: #e2e8f0; color: #475569; } +.classification-summary { margin: 10px 0 0; font-size: 0.84rem; line-height: 1.5; color: #334155; } + +.classification-toggle { + margin-top: 6px; + padding: 0; + border: 0; + background: none; + color: #2563eb; + font-size: 0.78rem; + cursor: pointer; + &:hover { text-decoration: underline; } +} + +.classification-hierarchy { + margin: 10px 0 0; + padding-top: 10px; + border-top: 1px solid rgba(15, 23, 42, 0.08); +} + +.classification-hierarchy__row { + display: grid; + grid-template-columns: 88px 1fr; + gap: 8px; + margin-bottom: 6px; + + dt { margin: 0; font-size: 0.72rem; font-weight: 700; color: #64748b; text-transform: uppercase; } + dd { margin: 0; font-size: 0.8rem; line-height: 1.45; color: #334155; } +} diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts new file mode 100644 index 00000000..ebb39b9d --- /dev/null +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -0,0 +1,310 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute, Router, RouterModule } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatDividerModule } from '@angular/material/divider'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; +import { + PatentsService, + PatentEntry, + IpcClassification, +} from '../../api/api/patents.service'; + +type SourceFilter = 'all' | 'EPO' | 'USPTO'; +type ClassificationSystem = 'IPC' | 'CPC'; + +interface ClassificationCard { + key: string; + symbols: string[]; + system: ClassificationSystem; + levelLabel: string; + primaryDescription: string | null; + hierarchy: { label: string; value: string }[]; +} + +const DESCRIPTION_PREVIEW_LENGTH = 140; + +@Component({ + selector: 'app-patents', + imports: [ + CommonModule, + RouterModule, + MatIconModule, + MatButtonModule, + MatCardModule, + MatFormFieldModule, + MatInputModule, + MatPaginatorModule, + MatProgressSpinnerModule, + MatChipsModule, + MatDividerModule, + ], + templateUrl: './patents.component.html', + styleUrl: './patents.component.scss', +}) +export class PatentsComponent implements OnInit { + private router = inject(Router); + private route = inject(ActivatedRoute); + private patentsApi = inject(PatentsService); + + patents: PatentEntry[] = []; + total = 0; + page = 0; + pageSize = 10; + + loading = true; + error = false; + + searchTerm = ''; + activeFilter: SourceFilter = 'all'; + sortDirection: string = 'desc'; + + selectedPatent: PatentEntry | null = null; + showDetail = false; + private expandedClassificationKeys = new Set(); + + private searchSubject = new Subject(); + + constructor() { + this.searchSubject + .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed()) + .subscribe((term) => { + this.searchTerm = term; + this.page = 0; + this.selectedPatent = null; + this.showDetail = false; + this.loadPatents(); + this.updateQueryParams(); + }); + } + + ngOnInit(): void { + const qp = this.route.snapshot.queryParamMap; + this.searchTerm = qp.get('search') ?? ''; + this.page = parseInt(qp.get('page') ?? '0', 10); + this.pageSize = parseInt(qp.get('size') ?? '10', 10); + const f = qp.get('source'); + if (f === 'EPO' || f === 'USPTO') this.activeFilter = f; + const d = qp.get('sort_direction'); + if (d === 'asc' || d === 'desc') this.sortDirection = d; + + this.loadPatents(); + } + + private loadPatents(): void { + this.loading = true; + this.error = false; + const source = this.activeFilter === 'all' ? undefined : this.activeFilter; + + this.patentsApi + .getAllPatents(this.page, this.pageSize, this.searchTerm || undefined, source, 'date', this.sortDirection) + .subscribe({ + next: (res) => { + this.patents = res.patents; + this.total = res.total; + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + + onSearchInput(event: Event): void { + this.searchSubject.next((event.target as HTMLInputElement).value); + } + + clearSearch(): void { + this.searchTerm = ''; + this.page = 0; + this.selectedPatent = null; + this.showDetail = false; + this.loadPatents(); + this.updateQueryParams(); + } + + setFilterFromChip(event: any): void { + const val = event.value; + this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all'; + this.page = 0; + this.selectedPatent = null; + this.showDetail = false; + this.loadPatents(); + this.updateQueryParams(); + } + + setSortDirection(direction: string): void { + this.sortDirection = direction; + this.loadPatents(); + this.updateQueryParams(); + } + + handlePageChange(event: PageEvent): void { + this.page = event.pageIndex; + this.pageSize = event.pageSize; + this.selectedPatent = null; + this.showDetail = false; + this.loadPatents(); + this.updateQueryParams(); + } + + selectPatent(patent: PatentEntry): void { + this.selectedPatent = patent; + this.showDetail = true; + this.expandedClassificationKeys.clear(); + } + + closeDetail(): void { + this.showDetail = false; + this.selectedPatent = null; + this.expandedClassificationKeys.clear(); + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + search: this.searchTerm || null, + page: this.page, + size: this.pageSize, + source: this.activeFilter === 'all' ? null : this.activeFilter, + sort_direction: this.sortDirection, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + formatDate(date: string | null): string { + if (!date) return '-'; + const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); + const parsed = new Date(d); + if (isNaN(parsed.getTime())) return date; + return new Intl.DateTimeFormat('de-DE').format(parsed); + } + + getPublicationStageLabel(patent: PatentEntry): string | null { + return patent.kind ?? patent.application_type ?? null; + } + + getPatentMetadataRows(patent: PatentEntry) { + const rows: { label: string; value: string; variant?: 'source' }[] = []; + rows.push({ label: 'Quelle', value: patent.source, variant: 'source' }); + rows.push({ label: 'Patent-Nr.', value: patent.patent_id }); + if (patent.publication_date) + rows.push({ label: 'Veröffentlichungsdatum', value: this.formatDate(patent.publication_date) }); + if (patent.application_number) + rows.push({ label: 'Anmeldungsnummer', value: patent.application_number }); + if (patent.application_date) + rows.push({ label: 'Anmeldedatum', value: this.formatDate(patent.application_date) }); + const stage = this.getPublicationStageLabel(patent); + if (stage) + rows.push({ label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp', value: this.formatMetadataLabel(stage) }); + if (patent.number_of_claims != null) + rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) }); + if (patent.status) + rows.push({ label: 'Status', value: this.formatMetadataLabel(patent.status) }); + return rows; + } + + private formatMetadataLabel(value: string): string { + return value.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase()); + } + + getClassificationCards( + entries: IpcClassification[] | undefined, + system: ClassificationSystem, + ): ClassificationCard[] { + if (!entries?.length) return []; + const merged = new Map(); + for (const entry of entries) { + const card = this.buildClassificationCard(entry, system); + const mergeKey = card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key; + const existing = merged.get(mergeKey); + if (existing) { + for (const s of card.symbols) { + if (!existing.symbols.includes(s)) existing.symbols.push(s); + } + continue; + } + merged.set(mergeKey, card); + } + return [...merged.values()]; + } + + toggleClassificationExpanded(key: string): void { + this.expandedClassificationKeys.has(key) + ? this.expandedClassificationKeys.delete(key) + : this.expandedClassificationKeys.add(key); + } + + isClassificationExpanded(key: string): boolean { + return this.expandedClassificationKeys.has(key); + } + + isLongDescription(text: string | null): boolean { + return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH; + } + + getDescriptionPreview(text: string | null): string { + if (!text) return ''; + return text.length <= DESCRIPTION_PREVIEW_LENGTH + ? text + : `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`; + } + + private buildClassificationCard(entry: IpcClassification, system: ClassificationSystem): ClassificationCard { + const level = this.getClassificationLevel(entry); + const primaryDescription = this.extractDescriptionText(entry[level.field]); + return { + key: `${system}-${entry.symbol}`, + symbols: [entry.symbol], + system, + levelLabel: level.label, + primaryDescription, + hierarchy: this.buildHierarchyRows(entry, primaryDescription), + }; + } + + private getClassificationLevel(entry: IpcClassification): { label: string; field: keyof IpcClassification } { + if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' }; + if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' }; + if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' }; + if (entry.section) return { label: 'Sektion', field: 'section' }; + return { label: 'Code', field: 'symbol' }; + } + + private buildHierarchyRows(entry: IpcClassification, primaryDescription: string | null) { + const rows: { label: string; value: string }[] = []; + const seen = new Set(); + const addRow = (label: string, raw: string | null) => { + const value = this.extractDescriptionText(raw); + if (!value) return; + const norm = value.toLocaleLowerCase('en'); + if (seen.has(norm) || norm === primaryDescription?.toLocaleLowerCase('en')) return; + seen.add(norm); + rows.push({ label, value }); + }; + addRow('Sektion', entry.section); + addRow('Klasse', entry.class); + addRow('Unterklasse', entry.subclass); + return rows; + } + + private extractDescriptionText(value: string | null | undefined): string | null { + if (!value?.trim()) return null; + const text = value.includes(' - ') ? value.split(' - ').slice(1).join(' - ').trim() : value.trim(); + if (!text) return null; + const first = text.split(/[;|]/)[0]?.trim() ?? text; + return first === first.toUpperCase() ? first.charAt(0) + first.slice(1).toLowerCase() : first; + } +} 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 8072d88f..40544bf7 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 @@ -30,6 +30,7 @@ export class AppMenuComponent { collapsed = input(false); canCollapse = input(false); toggleCollapsed = output(); + navItems = [ { label: 'Dashboard', @@ -73,6 +74,12 @@ export class AppMenuComponent { sorting_order: 'asc', }, }, + { + label: 'Patente', + icon: 'lightbulb', + route: '/patents', + disabled: false, + }, ]; constructor( From 99b9d52a24732ebd0876000040d254112acbfb59 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 25 Jun 2026 20:19:51 +0200 Subject: [PATCH 48/81] fix(patents): remove duplicate interface exports --- webapp/src/app/api/api/patents.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 7d1986e9..1d316235 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -22,7 +22,7 @@ export interface IpcClassification { subgroup: string | null; } -export interface PatentEntry { +interface PatentEntry { patent_id: string; source: string; title: string | null; @@ -44,7 +44,7 @@ export interface PatentEntry { country: string | null; } -export interface PatentsByAuthorResponse { +interface PatentsByAuthorResponse { author_id: string; author_name: string | null; patent_count: number; From c835f878369a307d237477f7c601384938147263 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 25 Jun 2026 20:21:37 +0200 Subject: [PATCH 49/81] fix(patents): re-export PatentEntry --- webapp/src/app/api/api/patents.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 1d316235..ea88b25d 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -22,7 +22,7 @@ export interface IpcClassification { subgroup: string | null; } -interface PatentEntry { +export interface PatentEntry { patent_id: string; source: string; title: string | null; From 2babbef08affeb60cdcf368b51362a1bd490cd55 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 25 Jun 2026 20:31:07 +0200 Subject: [PATCH 50/81] fix(patents): move interfaces to model file --- webapp/src/app/api/api/patents.service.ts | 35 ++----------------- webapp/src/app/api/model/patentEntry.ts | 42 ++++++++++++++--------- 2 files changed, 27 insertions(+), 50 deletions(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index ea88b25d..80ecb189 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,7 +1,6 @@ import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, - HttpHeaders, HttpParams, HttpResponse, HttpEvent, @@ -12,39 +11,9 @@ import { Observable } from 'rxjs'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; +import { IpcClassification, PatentEntry } from '../model/patentEntry'; -export interface IpcClassification { - symbol: string; - section: string | null; - class: string | null; - subclass: string | null; - main_group: string | null; - subgroup: string | null; -} - -export interface PatentEntry { - patent_id: string; - source: string; - title: string | null; - abstract: string | null; - publication_date: string | null; - publication_year: string | null; - application_number: string | null; - application_date: string | null; - kind: string | null; - application_type: string | null; - number_of_claims: number | null; - status: string | null; - inventors: string[]; - assignees: string[]; - ipc: string[]; - ipc_descriptions: IpcClassification[]; - cpc: string[]; - cpc_descriptions: IpcClassification[]; - country: string | null; -} - -interface PatentsByAuthorResponse { +export interface PatentsByAuthorResponse { author_id: string; author_name: string | null; patent_count: number; diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index a6a3619c..94f21db2 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -1,22 +1,30 @@ -/** - * 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 IpcClassification { + symbol: string; + section: string | null; + class: string | null; + subclass: string | null; + main_group: string | null; + subgroup: string | null; +} export interface PatentEntry { patent_id: string; source: string; - title?: string | null; - abstract?: string | null; - publication_date?: string | null; - publication_year?: string | null; - inventors?: Array; - assignees?: Array; - ipc?: Array; - country?: string | null; + title: string | null; + abstract: string | null; + publication_date: string | null; + publication_year: string | null; + application_number: string | null; + application_date: string | null; + kind: string | null; + application_type: string | null; + number_of_claims: number | null; + status: string | null; + inventors: string[]; + assignees: string[]; + ipc: string[]; + ipc_descriptions: IpcClassification[]; + cpc: string[]; + cpc_descriptions: IpcClassification[]; + country: string | null; } From 785c5345d4aa7a5fafea0b98eafebb673a114ead Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 25 Jun 2026 20:44:49 +0200 Subject: [PATCH 51/81] m --- webapp/src/app/api/api/patents.service.ts | 15 ++++---- webapp/src/app/api/model/patentEntry.ts | 42 +++++++++-------------- 2 files changed, 25 insertions(+), 32 deletions(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 80ecb189..69026ffa 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,6 +1,7 @@ import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, + HttpHeaders, HttpParams, HttpResponse, HttpEvent, @@ -11,14 +12,14 @@ import { Observable } from 'rxjs'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { IpcClassification, PatentEntry } from '../model/patentEntry'; +import { PatentEntry } from '../model/patentEntry'; +import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; + + + + + -export interface PatentsByAuthorResponse { - author_id: string; - author_name: string | null; - patent_count: number; - patents: PatentEntry[]; -} export interface AllPatentsResponse { total: number; diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index 94f21db2..a6a3619c 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -1,30 +1,22 @@ -export interface IpcClassification { - symbol: string; - section: string | null; - class: string | null; - subclass: string | null; - main_group: string | null; - subgroup: string | null; -} +/** + * 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 PatentEntry { patent_id: string; source: string; - title: string | null; - abstract: string | null; - publication_date: string | null; - publication_year: string | null; - application_number: string | null; - application_date: string | null; - kind: string | null; - application_type: string | null; - number_of_claims: number | null; - status: string | null; - inventors: string[]; - assignees: string[]; - ipc: string[]; - ipc_descriptions: IpcClassification[]; - cpc: string[]; - cpc_descriptions: IpcClassification[]; - country: string | null; + title?: string | null; + abstract?: string | null; + publication_date?: string | null; + publication_year?: string | null; + inventors?: Array; + assignees?: Array; + ipc?: Array; + country?: string | null; } From 6b7da05b2ff1811038cb888d086bc15f804ac591 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Thu, 25 Jun 2026 21:01:18 +0200 Subject: [PATCH 52/81] fix(patents): restore model types and fix component imports --- webapp/src/app/api/model/patentEntry.ts | 42 +++++++++++-------- .../app/modules/patents/patents.component.ts | 7 +--- .../person-patents.component.ts | 3 +- 3 files changed, 29 insertions(+), 23 deletions(-) diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index a6a3619c..94f21db2 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -1,22 +1,30 @@ -/** - * 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 IpcClassification { + symbol: string; + section: string | null; + class: string | null; + subclass: string | null; + main_group: string | null; + subgroup: string | null; +} export interface PatentEntry { patent_id: string; source: string; - title?: string | null; - abstract?: string | null; - publication_date?: string | null; - publication_year?: string | null; - inventors?: Array; - assignees?: Array; - ipc?: Array; - country?: string | null; + title: string | null; + abstract: string | null; + publication_date: string | null; + publication_year: string | null; + application_number: string | null; + application_date: string | null; + kind: string | null; + application_type: string | null; + number_of_claims: number | null; + status: string | null; + inventors: string[]; + assignees: string[]; + ipc: string[]; + ipc_descriptions: IpcClassification[]; + cpc: string[]; + cpc_descriptions: IpcClassification[]; + country: string | null; } diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index ebb39b9d..d946a0e5 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -12,11 +12,8 @@ import { MatChipsModule } from '@angular/material/chips'; import { MatDividerModule } from '@angular/material/divider'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; -import { - PatentsService, - PatentEntry, - IpcClassification, -} from '../../api/api/patents.service'; +import { PatentsService } from '../../api/api/patents.service'; +import { PatentEntry, IpcClassification } from '../../api/model/patentEntry'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index e4cb9912..a28131fa 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,7 +1,8 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { PatentsService, PatentEntry, IpcClassification } from '../../api/api/patents.service'; +import { PatentsService } from '../../api/api/patents.service'; +import { PatentEntry, IpcClassification } from '../../api/model/patentEntry'; type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; From 493a28155dfe461fe42685f2914e44f66ace0213 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 25 Jun 2026 21:14:28 +0200 Subject: [PATCH 53/81] style(navigation): change patents icon to workspace_premium --- webapp/src/app/shared/ui/app-menu/app-menu.component.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 03675c90..295aae4c 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 @@ -92,7 +92,7 @@ export class AppMenuComponent { }, { label: 'Patente', - icon: 'lightbulb', + icon: 'workspace_premium', route: '/patents', disabled: false, }, From f9fc8addceac1b4f2c4a85f14cda81ebfcfb20fc Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 21:47:43 +0200 Subject: [PATCH 54/81] moved publications table to a separate component --- .../eu-details.component.html | 10 +- .../eu-details.component.scss | 16 +- .../eu-cordis-details/eu-details.component.ts | 175 +++++++------ .../publications-table.component.html | 141 +++++++++++ .../publications-table.component.scss | 233 ++++++++++++++++++ .../publications-table.component.ts | 87 +++++++ 6 files changed, 576 insertions(+), 86 deletions(-) create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 367eda5c..782e5acd 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -557,8 +557,10 @@ @if (activeTab === 'organizations' && euProject.organizations) { } - - + @if (activeTab === 'publications' && euProject.publications) { + + } + @if (activeTab === 'iprs' && euProject.iprs) { @@ -626,7 +628,7 @@
@for (ipr of euProject.iprs; track ipr.title) { -
+
@if (ipr.type === 'PATENT') { emoji_events diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss index 60c230aa..4728e222 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -269,13 +269,13 @@ h1 { padding: 0; } -.section-header { - display: flex; - align-items: center; - gap: 10px; - padding: 16px 20px 12px; - border-bottom: 1px solid #f0f2f5; -} + .section-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid #e6e9ed; + } .section-header mat-icon { color: var(--sg-text-muted); @@ -286,7 +286,7 @@ h1 { .section-header h2 { margin: 0; - font-size: 16px; + font-size: 18px; font-weight: 600; color: var(--sg-text); } diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index a73c2e04..449bae54 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -16,8 +16,8 @@ import { import { EuProjectData } from '../../../api/model/euProjectData'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; import { OrganizationsTableComponent } from './organizations-table/organizations-table/organizations-table.component'; -import { HEUPublication } from '../../../api'; - +import { Fp7ProjectIPR } from '../../../api'; +import { PublicationsTableComponent } from './publications-table/publications-table.component'; export type TabType = | 'overview' | 'organizations' @@ -38,6 +38,7 @@ export type TabType = MatTooltipModule, TopicChipComponent, OrganizationsTableComponent, + PublicationsTableComponent ], templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', @@ -49,27 +50,30 @@ export class EuDetailsComponent implements OnInit, OnDestroy { // Data euProject: EuProjectData | undefined; programType: string = ''; - + // UI State activeTab: TabType = 'overview'; isLoading = true; - + // Tab content flags hasOrganizations = false; hasPublications = false; hasIprs = false; hasDeliverables = false; - + // Subscriptions private subscriptions: Subscription = new Subscription(); // Tab configuration - private readonly tabConfig: Record = { + private readonly tabConfig: Record< + TabType, + { label: string; icon: string; order: number } + > = { overview: { label: 'Übersicht', icon: 'info', order: 0 }, organizations: { label: 'Organisationen', icon: 'business', order: 1 }, publications: { label: 'Publikationen', icon: 'article', order: 2 }, iprs: { label: 'IPRs', icon: 'gavel', order: 3 }, - deliverables: { label: 'Ergebnisse', icon: 'assignment', order: 4 } + deliverables: { label: 'Ergebnisse', icon: 'assignment', order: 4 }, }; ngOnInit(): void { @@ -85,7 +89,7 @@ export class EuDetailsComponent implements OnInit, OnDestroy { this.updateTabContentFlags(); this.handleTabFromQueryParams(); } - }) + }), ); // Subscribe to query params changes @@ -95,7 +99,7 @@ export class EuDetailsComponent implements OnInit, OnDestroy { if (this.euProject) { this.handleTabFromQueryParams(params); } - }) + }), ); } @@ -122,14 +126,20 @@ export class EuDetailsComponent implements OnInit, OnDestroy { * Update flags for which tabs have content */ private updateTabContentFlags(): void { - this.hasOrganizations = - (this.euProject?.organizations && this.euProject.organizations.length > 0) || false; - this.hasPublications = - (this.euProject?.publications && this.euProject.publications.length > 0) || false; - this.hasIprs = + this.hasOrganizations = + (this.euProject?.organizations && + this.euProject.organizations.length > 0) || + false; + this.hasPublications = + (this.euProject?.publications && + this.euProject.publications.length > 0) || + false; + this.hasIprs = (this.euProject?.iprs && this.euProject.iprs.length > 0) || false; - this.hasDeliverables = - (this.euProject?.deliverables && this.euProject.deliverables.length > 0) || false; + this.hasDeliverables = + (this.euProject?.deliverables && + this.euProject.deliverables.length > 0) || + false; } /** @@ -138,7 +148,7 @@ export class EuDetailsComponent implements OnInit, OnDestroy { private handleTabFromQueryParams(params?: any): void { const queryParams = params || this.route.snapshot.queryParams; const tabParam = queryParams['tab'] as TabType; - + if (tabParam && this.isValidTab(tabParam)) { if (this.tabHasContent(tabParam)) { this.activeTab = tabParam; @@ -158,7 +168,13 @@ export class EuDetailsComponent implements OnInit, OnDestroy { * Check if a tab value is valid */ private isValidTab(tab: string): tab is TabType { - return ['overview', 'organizations', 'publications', 'iprs', 'deliverables'].includes(tab); + return [ + 'overview', + 'organizations', + 'publications', + 'iprs', + 'deliverables', + ].includes(tab); } /** @@ -189,11 +205,13 @@ export class EuDetailsComponent implements OnInit, OnDestroy { const currentTab = this.route.snapshot.queryParams['tab']; if (currentTab === tab) return; - this.router.navigate([], { - relativeTo: this.route, - queryParams: { tab: tab }, - queryParamsHandling: 'merge', - }).catch(err => console.error('Tab navigation failed:', err)); + this.router + .navigate([], { + relativeTo: this.route, + queryParams: { tab: tab }, + queryParamsHandling: 'merge', + }) + .catch((err) => console.error('Tab navigation failed:', err)); } /** @@ -220,7 +238,7 @@ export class EuDetailsComponent implements OnInit, OnDestroy { */ setTab(tab: TabType): void { if (this.activeTab === tab) return; - + // Check if tab has content if (!this.tabHasContent(tab)) { console.warn(`Tab "${tab}" has no content`); @@ -281,8 +299,16 @@ export class EuDetailsComponent implements OnInit, OnDestroy { * Get sorted tabs that have content */ getVisibleTabs(): TabType[] { - return (['overview', 'organizations', 'publications', 'iprs', 'deliverables'] as TabType[]) - .filter(tab => this.tabHasContent(tab)) + return ( + [ + 'overview', + 'organizations', + 'publications', + 'iprs', + 'deliverables', + ] as TabType[] + ) + .filter((tab) => this.tabHasContent(tab)) .sort((a, b) => this.tabConfig[a].order - this.tabConfig[b].order); } @@ -323,7 +349,10 @@ export class EuDetailsComponent implements OnInit, OnDestroy { const statusUpper = status.toUpperCase(); if (statusUpper.includes('CLOSED') || statusUpper.includes('COMPLETED')) { return '#27ae60'; - } else if (statusUpper.includes('ONGOING') || statusUpper.includes('ACTIVE')) { + } else if ( + statusUpper.includes('ONGOING') || + statusUpper.includes('ACTIVE') + ) { return '#f39c12'; } else if (statusUpper.includes('SIGNED')) { return '#3498db'; @@ -369,13 +398,15 @@ export class EuDetailsComponent implements OnInit, OnDestroy { if (!scheme) return 'N/A'; const schemeMap: { [key: string]: string } = { - 'MSCA-IF-EF-SE': 'MSCA Individual Fellowship - European Fellowship - Standard', + 'MSCA-IF-EF-SE': + 'MSCA Individual Fellowship - European Fellowship - Standard', 'MSCA-IF-EF': 'MSCA Individual Fellowship - European Fellowship', 'MSCA-IF-GF': 'MSCA Individual Fellowship - Global Fellowship', 'MSCA-IF': 'MSCA Individual Fellowship', 'MSCA-ITN': 'MSCA Innovative Training Networks', 'MSCA-RISE': 'MSCA Research and Innovation Staff Exchange', - 'MSCA-COFUND': 'MSCA Co-funding of Regional, National and International Programmes', + 'MSCA-COFUND': + 'MSCA Co-funding of Regional, National and International Programmes', }; return schemeMap[scheme] || scheme; @@ -464,10 +495,12 @@ export class EuDetailsComponent implements OnInit, OnDestroy { console.warn('Cannot search with empty topic'); return; } - - this.router.navigate(['/eu-projects'], { - queryParams: { topic: topic }, - }).catch(err => console.error('Navigation to topic failed:', err)); + + this.router + .navigate(['/eu-projects'], { + queryParams: { topic: topic }, + }) + .catch((err) => console.error('Navigation to topic failed:', err)); } /** @@ -478,10 +511,12 @@ export class EuDetailsComponent implements OnInit, OnDestroy { console.warn('Cannot search with empty keyword'); return; } - - this.router.navigate(['/eu-projects'], { - queryParams: { keyword: keyword }, - }).catch(err => console.error('Navigation to keyword failed:', err)); + + this.router + .navigate(['/eu-projects'], { + queryParams: { keyword: keyword }, + }) + .catch((err) => console.error('Navigation to keyword failed:', err)); } /** @@ -492,10 +527,12 @@ export class EuDetailsComponent implements OnInit, OnDestroy { console.warn('Cannot search with empty framework'); return; } - - this.router.navigate(['/eu-projects'], { - queryParams: { framework: framework }, - }).catch(err => console.error('Navigation to framework failed:', err)); + + this.router + .navigate(['/eu-projects'], { + queryParams: { framework: framework }, + }) + .catch((err) => console.error('Navigation to framework failed:', err)); } /** @@ -506,10 +543,14 @@ export class EuDetailsComponent implements OnInit, OnDestroy { console.warn('Cannot search with empty funding scheme'); return; } - - this.router.navigate(['/eu-projects'], { - queryParams: { fundingScheme: scheme }, - }).catch(err => console.error('Navigation to funding scheme failed:', err)); + + this.router + .navigate(['/eu-projects'], { + queryParams: { fundingScheme: scheme }, + }) + .catch((err) => + console.error('Navigation to funding scheme failed:', err), + ); } /** @@ -520,40 +561,26 @@ export class EuDetailsComponent implements OnInit, OnDestroy { console.warn('Cannot search with empty status'); return; } - - this.router.navigate(['/eu-projects'], { - queryParams: { status: status }, - }).catch(err => console.error('Navigation to status failed:', err)); + + this.router + .navigate(['/eu-projects'], { + queryParams: { status: status }, + }) + .catch((err) => console.error('Navigation to status failed:', err)); } - /** - * Navigate to publication details - */ - searchForPublication(pub: HEUPublication): void { - if (!pub) { - console.warn('Cannot navigate with empty publication'); - return; - } - - const doi = pub.doi?.trim() ?? "unknown"; - - // Encode DOI and navigate - const encodedDoi = encodeURIComponent(doi); - - this.router.navigate(['/publication', encodedDoi], { - queryParams: { - title: pub.title || '' - }, - }).catch(err => console.error('Navigation to publication failed:', err)); + searchForPatent(patent: Fp7ProjectIPR) { + console.log(patent) } - /** * Navigate back to projects list with optional filter */ goBack(filters?: { [key: string]: any }): void { - this.router.navigate(['/eu-projects'], { - queryParams: filters || {}, - queryParamsHandling: 'merge', - }).catch(err => console.error('Navigation back failed:', err)); + this.router + .navigate(['/eu-projects'], { + queryParams: filters || {}, + queryParamsHandling: 'merge', + }) + .catch((err) => console.error('Navigation back failed:', err)); } -} \ No newline at end of file +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html new file mode 100644 index 00000000..79cda076 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.html @@ -0,0 +1,141 @@ +
+ + @if (showHeader) { +
+ description +

{{ headerTitle }} ({{ getPublicationCount() }})

+
+ } +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Titel +
+ + {{ pub.title || 'Kein Titel' }} + +
+
Autoren + @if (pub.authors) { + @let authorList = parseAuthors(pub.authors); + @if (authorList.length > 0) { +
+ @for (author of authorList; track author; let last = $last) { + + + {{ author }} + + @if (!last) { + , + } + + } +
+ } @else { + — + } + } @else { + — + } +
Zeitschrift + @if (pub.journalTitle) { + {{ pub.journalTitle }} + } @else { + — + } + Jahr + @if (pub.publishedYear) { + {{ pub.publishedYear }} + } @else { + — + } + Verlag + @if (pub.publisher) { + {{ pub.publisher }} + } @else { + — + } + Links + +
+
+
+
\ No newline at end of file diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss new file mode 100644 index 00000000..f84c64b4 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss @@ -0,0 +1,233 @@ +// Publications Table + +.publications-tab { + .card { + margin-bottom: 24px; + } + + .section-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid #e6e9ed; + + mat-icon { + color: #6b7a8a; + font-size: 24px; + width: 24px; + height: 24px; + } + + h2 { + margin: 0; + font-size: 18px; + font-weight: 600; + color: #1a1a1a; + } + } + + table { + width: 100%; + border-radius: 8px; + overflow: hidden; + } + + .mat-mdc-header-cell { + font-weight: 600; + color: #6b7a8a; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.5px; + background: #f8fafc; + border-bottom: 2px solid #e6e9ed; + padding: 12px 16px; + } + + .mat-mdc-cell { + padding: 12px 16px; + border-bottom: 1px solid #f0f2f5; + font-size: 13px; + } + + .mat-mdc-row { + transition: background 0.2s ease; + cursor: pointer; + } + + .mat-mdc-row:hover { + background: #f8fafc; + } + + .pub-title-cell { + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; + } + + .pub-title-text { + font-weight: 500; + color: #1a1a1a; + line-height: 1.4; + } + + .pub-title-cell:hover .pub-title-text { + color: #005a9c; + text-decoration: underline; + } + + .authors-text { + color: #4a5a6a; + font-size: 13px; + color: #1a1a1a; + line-height: 1.4; + } + .author-name:hover { + color: #005a9c; + text-decoration: underline; + } + + .journal-chip { + display: inline-block; + padding: 2px 10px; + background: #e8edf5; + border-radius: 12px; + font-size: 12px; + color: #6b7a8a; + max-width: 200px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .year-value { + font-weight: 500; + color: #1a1a1a; + } + + .publisher-text { + color: #4a5a6a; + font-size: 13px; + } + + .empty-value { + color: #6b7a8a; + font-size: 13px; + } + + .links-container { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + } + + .link-button { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 4px 10px; + background: #f0f3f7; + border-radius: 12px; + color: #4a5a6a; + text-decoration: none; + font-size: 11px; + font-weight: 500; + transition: all 0.2s ease; + + &:hover { + background: #e8edf5; + color: #005a9c; + transform: translateY(-1px); + } + + .link-icon { + font-size: 14px; + width: 14px; + height: 14px; + color: #6b7a8a; + } + + .link-label { + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.3px; + } + } + + // Responsive styles + @media (max-width: 768px) { + .section-header { + padding: 12px 16px; + + h2 { + font-size: 16px; + } + } + + .mat-mdc-header-cell, + .mat-mdc-cell { + padding: 8px 10px; + font-size: 12px; + } + + .publicationDisplayedColumns { + // Hide less important columns on mobile + .mat-column-publisher { + display: none; + } + } + + .journal-chip { + max-width: 120px; + font-size: 11px; + } + + .link-button { + padding: 2px 8px; + font-size: 10px; + + .link-label { + display: none; + } + } + + .pub-title-text { + font-size: 13px; + } + } + + @media (max-width: 480px) { + .mat-column-journal { + display: none; + } + + .mat-column-publisher { + display: none; + } + + .mat-mdc-cell { + padding: 6px 8px; + font-size: 11px; + } + + .authors-text { + font-size: 11px; + max-width: 100px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + display: inline-block; + } + + .links-container { + gap: 4px; + } + + .link-button { + padding: 2px 6px; + font-size: 9px; + } + } +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts new file mode 100644 index 00000000..44f5af5e --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.ts @@ -0,0 +1,87 @@ +import { Component, computed, inject, Input } from '@angular/core'; +import { MatTableModule } from '@angular/material/table'; +import { Router } from '@angular/router'; +import { MatIcon } from '@angular/material/icon'; +import { MatCard } from '@angular/material/card'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { CommonModule } from '@angular/common'; +import { HEUPublication } from '../../../../api'; + +@Component({ + selector: 'app-publications-table', + imports: [CommonModule, MatTableModule, MatIcon, MatCard, MatTooltipModule], + templateUrl: './publications-table.component.html', + styleUrl: './publications-table.component.scss', +}) +export class PublicationsTableComponent { + private router = inject(Router); + + @Input() publications: HEUPublication[] = []; + @Input() showHeader: boolean = true; + @Input() headerTitle: string = 'Publikationen'; + + // Displayed columns for the publications table + publicationDisplayedColumns: string[] = [ + 'title', + 'authors', + 'journal', + 'year', + 'publisher', + 'links', + ]; + author_names = computed(() => 'keka'); + /** + * Navigate to publication details + */ + searchForPublication(pub: HEUPublication): void { + if (!pub) { + console.warn('Cannot navigate with empty publication'); + return; + } + + const doi = pub.doi?.trim() ?? 'unknown'; + + // Encode DOI and navigate + const encodedDoi = encodeURIComponent(doi); + + this.router + .navigate(['/publication', encodedDoi], { + queryParams: { + title: pub.title || '', + }, + }) + .catch((err) => console.error('Navigation to publication failed:', err)); + } + + getPublicationCount(): number { + return this.publications?.length || 0; + } + searchForPersonName(personName: string): void { + this.router.navigate(['/persons'], { + queryParams: { + query: personName, + }, + }); + } + // Parse authors string into array of individual authors + parseAuthors(authorsString: string | undefined): string[] { + if (!authorsString) return []; + + // Common separators: 'and', ',', ';', '&' + // Also handle cases like "Author1, Author2 and Author3" + let authors = authorsString; + + // Replace ' and ' with ', ' for consistent splitting + authors = authors.replace(/\s+and\s+/g, ', '); + + // Split by common separators + let authorList = authors.split(/[,;]\s*/); + + // Clean up each author name + authorList = authorList + .map((author) => author.trim()) + .filter((author) => author.length > 0); + + return authorList; + } +} From 5f158053d37fb02f496abada9e26298ae69690d3 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 21:48:05 +0200 Subject: [PATCH 55/81] organizations table ui adjusted --- .../organizations-table.component.html | 49 +++--- .../organizations-table.component.scss | 157 ++++++++++++++++-- .../organizations-table.component.ts | 5 + 3 files changed, 170 insertions(+), 41 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html index b1a68c07..1e5bfd19 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.html @@ -1,6 +1,10 @@
- -
+ +
+ business +

Organisationen ({{ orgs.length || 0 }})

+
+
@@ -62,20 +66,6 @@ - - - @@ -99,20 +89,25 @@ } + @@ -123,4 +118,4 @@
Aktivitätstyp URL - @if (org.organizationURL) { - - open_in_new - - } @else { - — - } +
-
+
\ No newline at end of file diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss index a9c7c11a..0ed8015c 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.scss @@ -1,4 +1,3 @@ - // Organizations .organizations-tab { @@ -6,9 +5,29 @@ margin-bottom: 24px; } + .section-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid #e6e9ed; + + mat-icon { + color: #6b7a8a; + font-size: 24px; + width: 24px; + height: 24px; + } + + h2 { + margin: 0; + font-size: 18px; + font-weight: 600; + color: #1a1a1a; + } + } + .organizations-table-wrapper { - padding: 0 20px 20px; - overflow-x: auto; table { width: 100%; @@ -75,6 +94,11 @@ font-size: 13px; } + .country-flag { + width: auto; + height: 10px; + } + .currency-value { font-weight: 500; color: #1a1a1a; @@ -102,19 +126,54 @@ font-weight: 500; font-size: 12px; } - .url-badge { - display: inline-block; + + .links-container { + display: inline-flex; + align-items: center; + gap: 8px; + } + + .link-button { + display: inline-flex; + align-items: center; + gap: 4px; padding: 2px 8px; - background: #e8f5e9; - color: #2e7d32; + background: #f0f3f7; border-radius: 4px; - font-weight: 500; + color: #4a5a6a; + text-decoration: none; font-size: 12px; + transition: all 0.2s ease; + + &:hover { + background: #e8edf5; + color: #005a9c; + } + + .link-icon { + font-size: 16px; + width: 16px; + height: 16px; + color: #6b7a8a; + } + + .link-label { + font-size: 11px; + font-weight: 500; + } } } @media (max-width: 768px) { .organizations-tab { + .section-header { + padding: 12px 16px; + + h2 { + font-size: 16px; + } + } + .organizations-table-wrapper { padding: 0 12px 12px; } @@ -124,14 +183,84 @@ padding: 8px 10px; font-size: 12px; } + .country-flag { - font-size: 18px; - line-height: 1; + height: 8px; } - .org-avatar-small { - width: 24px; - height: 24px; - font-size: 10px; + + .role-chip, + .activity-chip { + font-size: 11px; + padding: 2px 8px; + } + + .sme-badge { + font-size: 11px; + padding: 2px 6px; + } + + .link-button { + padding: 2px 6px; + font-size: 11px; + + .link-label { + font-size: 10px; + } + + .link-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + } + + .org-name-text { + font-size: 13px; } } } + +@media (max-width: 480px) { + .organizations-tab { + .mat-column-role { + display: none; + } + + .mat-column-activityType { + display: none; + } + + .mat-mdc-cell { + padding: 6px 8px; + font-size: 11px; + } + + .country-chip { + font-size: 11px; + gap: 6px; + } + + .currency-value { + font-size: 12px; + } + + .links-container { + gap: 4px; + } + + .link-button { + padding: 2px 4px; + font-size: 10px; + + .link-label { + display: none; + } + + .link-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + } + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts index 7bc5e3e8..c5f61a8d 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/organizations-table/organizations-table/organizations-table.component.ts @@ -15,6 +15,8 @@ export class OrganizationsTableComponent { private router = inject(Router); @Input() orgs!: HEUOrganization[]; + @Input() showHeader: boolean = true; + @Input() headerTitle: string = 'Organizationen'; // Displayed columns for the organizations table organizationDisplayedColumns: string[] = [ @@ -41,6 +43,9 @@ export class OrganizationsTableComponent { } return codeLower; } + getOrgsCount(): number { + return this.orgs?.length || 0; + } formatCurr(value: number | undefined | null) { if (value) { return formatCurrency(value); From f965b2c0a22e566a7138d2a7cc46fd7720d670be Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 21:48:37 +0200 Subject: [PATCH 56/81] added new endpoint for searching patents (by id and title) --- service/src/main/inse/model.py | 3 + .../inse/patents/elastic_search_client.py | 132 +++++++++++++++--- service/src/main/inse/patents/logic.py | 26 ++++ service/src/main/inse/patents/service.py | 23 ++- .../patents/test_elastic_search_client.py | 21 ++- 5 files changed, 174 insertions(+), 31 deletions(-) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 9633207b..028d5eb7 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -55,6 +55,9 @@ class ESIndex(StrEnum): OPENALEX_AUTHORS = "openalex-authors" OPENALEX_INSTITUTIONS = "openalex-institutions" OPENALEX_PUBLICATIONS = "openalex-publications" + + EPO_INDEX = "epo_index_1.0" + USPTO_INDEX = "uspto_patents_3.0" PROJECTS_BUND_V1 = "projects_bund_v1" PROJECTS_DFG_ALL = "projects_dfg_all" diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index f10694e6..698e9d84 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -4,15 +4,13 @@ HTTP client for patent searches in EPO and USPTO Elasticsearch indices. """ from typing import Any - +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex import httpx - +import asyncio from .. import config from .name_matching import search_name_variants -EPO_INDEX = "epo_index_1.0" -USPTO_INDEX = "uspto_patents_3.0" - DEFAULT_SEARCH_SIZE = 100 @@ -168,21 +166,117 @@ class PatentSearchClient: } async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: - return await self._search(EPO_INDEX, payload) + return await self._search(ESIndex.EPO_INDEX, payload) async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]: - return await self._search(USPTO_INDEX, payload) + return await self._search(ESIndex.USPTO_INDEX, payload) async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{index}/_search", - headers=self._headers(), - json=payload, - ) - response.raise_for_status() - return response.json() \ No newline at end of file + response = elasticsearch.search(index=index,body=payload,cluster=ESCluster.INSE) + return response + + async def get_by_id_or_title( + self, + patent_id: str, + prefix: str, + title: str, + size: int = 1, + ) -> dict[str, Any]: + """Search EPO and USPTO by ID; fall back to match_phrase on title if no hits. + + Args: + patent_id: The raw document/publication number (e.g. "1234567", "US1234567A"). + prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO. + Both indices are always queried for the ID lookup. + title: Used only when the ID lookup returns zero hits. + size: Maximum number of results to return. + """ + epo_id_payload = self._epo_query_by_id(patent_id, size) + uspto_id_payload = self._uspto_query_by_id(patent_id, size) + + epo_result, uspto_result = await asyncio.gather( + self.search_epo(epo_id_payload), + self.search_uspto(uspto_id_payload), + ) + + epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0) + uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0) + + if epo_hits > 0 or uspto_hits > 0: + if prefix.upper() == "EP" and epo_hits > 0: + return epo_result + if prefix.upper() == "US" and uspto_hits > 0: + return uspto_result + return epo_result if epo_hits > 0 else uspto_result + + if prefix.upper() == "US": + payload = self._uspto_query_by_title(title, size) + return await self.search_uspto(payload) + + payload = self._epo_query_by_title(title, size) + return await self.search_epo(payload) + #query builders + + def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]: + """Term query against doc_number; strips a leading 'EP' prefix if present.""" + raw_id = patent_id.upper().removeprefix("EP") + return { + "size": size, + "_source": [ + "doc_number", "country", "kind", "date_publication", + "date_publication_year", "application_number", + "application_filing_date", "title_en", "title_de", "abstract", + "inventors_name", "applicants_name", "ipc", "cpc", + ], + "query": {"term": {"doc_number": raw_id}}, + } + + def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]: + """Term query against publication_number; tries the ID as-is.""" + return { + "size": size, + "track_total_hits": True, + "sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"], + "_source": [ + "publication_number", "country", "publication_date", + "publication_year", "application_number", "application_date", + "application_type", "title", "abstract", "inventors_names", + "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", + ], + "query": {"term": {"publication_number": patent_id}}, + } + + def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]: + """match_phrase fallback on title_en (and title_de as a should clause).""" + return { + "size": size, + "_source": [ + "doc_number", "country", "kind", "date_publication", + "date_publication_year", "application_number", + "application_filing_date", "title_en", "title_de", "abstract", + "inventors_name", "applicants_name", "ipc", "cpc", + ], + "query": { + "bool": { + "should": [ + {"match_phrase": {"title_en": title}}, + {"match_phrase": {"title_de": title}}, + {"match_phrase": {"title_fr": title}}, + ], + "minimum_should_match": 1, + } + }, + } + + def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]: + """match_phrase fallback on title.""" + return { + "size": size, + "_source": [ + "publication_number", "country", "publication_date", + "publication_year", "application_number", "application_date", + "application_type", "title", "abstract", "inventors_names", + "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", + ], + "query": {"match_phrase": {"title": title}}, + } \ No newline at end of file diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 65765f1f..3763cef8 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -9,6 +9,7 @@ import httpx from fastapi import HTTPException from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE +from starlette.status import HTTP_404_NOT_FOUND from ..persons import logic as person_logic from ..models.openalex.author import Author @@ -22,6 +23,31 @@ from .name_matching import name_matches logger = logging.getLogger(__name__) +async def get_patent( + patent_id: str, + title: str, + prefix: str, + client: PatentSearchClient | None = None, +) -> model.PatentEntry: + search_client = client or PatentSearchClient() + + data = await search_client.get_by_id_or_title( + patent_id=patent_id, + prefix=prefix, + title=title, + ) + + parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits + elements = parse(data) + + if not elements: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Patent not found.", + ) + return elements[0] + + async def get_patents_by_author_id( author_id: str, client: PatentSearchClient | None = None, diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py index 53a27446..6d84f842 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -6,7 +6,9 @@ from fastapi import APIRouter from . import logic from . import model - +from typing import Annotated, Optional +from fastapi import Path +from fastapi import Query router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) @@ -18,3 +20,22 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) ) async def get_patents_by_author(author_id: str): return await logic.get_patents_by_author_id(author_id) + +@router.get( + "/patents/{identifier}", + operation_id="getPatentByIdOrTitle", + response_model=model.PatentEntry, + summary="Returns one publication by OpenAlex ID or DOI.", +) +async def get_patent_by_identifier( + identifier: Annotated[ + str, Path(description="") + ], + prefix: Annotated[ + Optional[str], Query(description="Application Prefix (EP or US)") + ] = "", + title: Annotated[ + Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?") + ] = "", +): + return await logic.get_patent(patent_id=identifier,prefix=prefix,title=title) \ No newline at end of file diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py index 08729ea6..729e8d51 100644 --- a/service/src/main/inse/patents/test_elastic_search_client.py +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -1,5 +1,5 @@ -import httpx import pytest +from unittest.mock import patch, MagicMock from inse.patents.elastic_search_client import ( DEFAULT_SEARCH_SIZE, @@ -34,16 +34,15 @@ def test_uspto_index_is_3_0(): @pytest.mark.anyio async def test_search_epo_posts_to_correct_index(): - requests: list[str] = [] + captured: list[dict] = [] - def handler(request: httpx.Request) -> httpx.Response: - requests.append(request.url.path) - return httpx.Response(200, json={"hits": {"hits": []}}) + def fake_search(index: str, body: dict): + captured.append({"index": index, "body": body}) + return {"hits": {"hits": []}} - transport = httpx.MockTransport(handler) - client = PatentSearchClient(api_key="test-key", transport=transport) + with patch("inse.integrations.elasticsearch.search", side_effect=fake_search): + client = PatentSearchClient(api_key="test-key") + await client.search_epo(client.epo_query_by_inventor("Weber", "Christian")) - await client.search_epo(client.epo_query_by_inventor("Weber", "Christian")) - - assert len(requests) == 1 - assert requests[0].endswith(f"/{EPO_INDEX}/_search") + assert len(captured) == 1 + assert captured[0]["index"] == EPO_INDEX \ No newline at end of file From d2d194ea07c82cf50f6dfabf11e5e036ec85fe39 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 21:48:50 +0200 Subject: [PATCH 57/81] regenerated services --- webapp/src/app/api/api/patents.service.ts | 450 +++++++++++------- webapp/src/app/api/model/ipcClassification.ts | 20 + webapp/src/app/api/model/patentEntry.ts | 36 +- 3 files changed, 320 insertions(+), 186 deletions(-) create mode 100644 webapp/src/app/api/model/ipcClassification.ts diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 4ec5192e..4128de16 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,174 +1,276 @@ -/** - * Innovation Search Engine API - */ -/* 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'; - -// @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; -import { BaseService } from '../api.base.service'; - -export interface IpcClassification { - symbol: string; - section: string | null; - class: string | null; - subclass: string | null; - main_group: string | null; - subgroup: string | null; -} - -export interface PatentEntry { - patent_id: string; - source: string; - title: string | null; - abstract: string | null; - publication_date: string | null; - publication_year: string | null; - application_number: string | null; - application_date: string | null; - kind: string | null; - application_type: string | null; - number_of_claims: number | null; - status: string | null; - inventors: string[]; - assignees: string[]; - ipc: string[]; - ipc_descriptions: IpcClassification[]; - cpc: string[]; - cpc_descriptions: IpcClassification[]; - country: string | null; -} - -export interface PatentsByAuthorResponse { - author_id: string; - author_name: string | null; - patent_count: number; - patents: PatentEntry[]; -} - -type GetPatentsByAuthorOptions = { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; -}; - -@Injectable({ - 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 patents by author. - * @endpoint get /api/inse-service/authors/{author_id}/patents - * @param authorId - * @param observe - * @param reportProgress - */ - public getPatentsByAuthor( - authorId: string, - observe?: 'body', - reportProgress?: boolean, - options?: GetPatentsByAuthorOptions, - ): Observable; - public getPatentsByAuthor( - authorId: string, - observe?: 'response', - reportProgress?: boolean, - options?: GetPatentsByAuthorOptions, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe?: 'events', - reportProgress?: boolean, - options?: GetPatentsByAuthorOptions, - ): Observable>; - public getPatentsByAuthor( - authorId: string, - observe: any = 'body', - reportProgress: boolean = false, - options?: GetPatentsByAuthorOptions, - ): 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, - }, - ); - } -} +/** + * 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. + */ +/* 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'; + +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { PatentEntry } from '../model/patentEntry'; +// @ts-ignore +import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + + +@Injectable({ + providedIn: 'root', +}) +export class PatentsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } + + /** + * Returns one publication by OpenAlex ID or DOI. + * @endpoint get /api/inse-service/authors/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 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, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPatentByIdOrTitle( + identifier: string, + prefix?: string, + title?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentByIdOrTitle( + identifier: string, + prefix?: string, + title?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentByIdOrTitle( + identifier: string, + prefix?: 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 getPatentByIdOrTitle.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + prefix, + 'prefix', + ); + 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/inse-service/authors/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, + }, + ); + } +} diff --git a/webapp/src/app/api/model/ipcClassification.ts b/webapp/src/app/api/model/ipcClassification.ts new file mode 100644 index 00000000..74805329 --- /dev/null +++ b/webapp/src/app/api/model/ipcClassification.ts @@ -0,0 +1,20 @@ +/** + * 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 IpcClassification { + symbol: string; + section?: string | null; + 'class'?: string | null; + subclass?: string | null; + main_group?: string | null; + subgroup?: string | null; +} + diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index a6a3619c..5565ab9a 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -1,22 +1,34 @@ /** * 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 { IpcClassification } from './ipcClassification'; -export interface PatentEntry { - patent_id: string; - source: string; - title?: string | null; - abstract?: string | null; - publication_date?: string | null; - publication_year?: string | null; - inventors?: Array; - assignees?: Array; - ipc?: Array; - country?: string | null; + +export interface PatentEntry { + patent_id: string; + source: string; + title?: string | null; + 'abstract'?: string | null; + publication_date?: string | null; + publication_year?: string | null; + application_number?: string | null; + application_date?: string | null; + kind?: string | null; + application_type?: string | null; + number_of_claims?: number | null; + status?: string | null; + inventors?: Array; + assignees?: Array; + ipc?: Array; + ipc_descriptions?: Array; + cpc?: Array; + cpc_descriptions?: Array; + country?: string | null; } + From f2336db46cd274074b5f67aa1fb8852f7751e4d5 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 21:49:21 +0200 Subject: [PATCH 58/81] minor fixes for make the component work --- webapp/src/app/api/.openapi-generator/FILES | 1 + .../person-patents.component.html | 19 +++++-------------- .../person-patents.component.ts | 19 +++++++++++++------ 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 957f3067..ebb55315 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -111,6 +111,7 @@ model/institutionInformation.ts model/institutionNetworkNode.ts model/institutionPage.ts model/institutionsListResponse.ts +model/ipcClassification.ts model/item.ts model/itemCreate.ts model/itemPage.ts diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index b8389633..dc376937 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -53,7 +53,7 @@
- @if (selectedPatent.assignees.length > 0) { + @if (selectedPatent.assignees && selectedPatent.assignees.length > 0) {

Anmelder

    @@ -64,7 +64,7 @@
} - @if (selectedPatent.ipc_descriptions.length > 0) { + @if (selectedPatent.ipc_descriptions && selectedPatent.ipc_descriptions.length > 0) {

Klassifikation (IPC)

@@ -110,7 +110,7 @@ }
- } @else if (selectedPatent.ipc.length > 0) { + } @else if (selectedPatent.ipc && selectedPatent.ipc.length > 0) {

Klassifikation (IPC)

    @@ -121,7 +121,7 @@
} - @if (selectedPatent.cpc_descriptions.length > 0) { + @if (selectedPatent.cpc_descriptions && selectedPatent.cpc_descriptions.length > 0) {

Klassifikation (CPC)

@@ -167,16 +167,7 @@ }
- } @else if (selectedPatent.cpc.length > 0) { -
-

Klassifikation (CPC)

-
    - @for (cpc of selectedPatent.cpc; track cpc) { -
  • {{ cpc }}
  • - } -
-
- } + }
} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index e4cb9912..53bbf252 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,8 +1,9 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { PatentsService, PatentEntry, IpcClassification } from '../../api/api/patents.service'; - +import { PatentsService } from '../../api/api/patents.service'; +import { PatentEntry } from '../../api'; +import { IpcClassification } from '../../api/model/ipcClassification'; type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; @@ -171,7 +172,7 @@ export class PersonPatentsComponent implements OnInit { this.updateQueryParams(); } - formatDate(date: string | null): string { + formatDate(date: string | null | undefined): string { if (!date) return '-'; const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); return new Intl.DateTimeFormat('de-DE').format(new Date(d)); @@ -374,10 +375,16 @@ export class PersonPatentsComponent implements OnInit { seen.add(normalized); rows.push({ label, value }); }; + if (entry.section){ + addRow('Sektion', entry.section); + } + if (entry.class){ + addRow('Klasse', entry.class); + } + if (entry.subclass){ + addRow('Unterklasse', entry.subclass); + } - addRow('Sektion', entry.section); - addRow('Klasse', entry.class); - addRow('Unterklasse', entry.subclass); return rows; } From 98db289928854811f1438d6b2bfba3ccdb612d29 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 22:31:16 +0200 Subject: [PATCH 59/81] regenerated services --- webapp/src/app/api/api/patents.service.ts | 425 ++++++++++++++---- .../src/app/api/model/allPatentsResponse.ts | 19 + 2 files changed, 364 insertions(+), 80 deletions(-) create mode 100644 webapp/src/app/api/model/allPatentsResponse.ts diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index f8f78f64..a9b21b25 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -1,3 +1,14 @@ +/** + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, @@ -5,34 +16,25 @@ import { HttpParams, HttpResponse, HttpEvent, + HttpParameterCodec, HttpContext, } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; + +// @ts-ignore +import { AllPatentsResponse } from '../model/allPatentsResponse'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { PatentEntry } from '../model/patentEntry'; +// @ts-ignore +import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; + +// @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; -import { PatentEntry } from '../model/patentEntry'; -import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; - - - - - - - -export interface AllPatentsResponse { - total: number; - page: number; - size: number; - patents: PatentEntry[]; -} - -type GetPatentsByAuthorOptions = { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; -}; @Injectable({ providedIn: 'root', @@ -46,37 +48,112 @@ export class PatentsService extends BaseService { super(basePath, configuration); } - public getPatentsByAuthor( - authorId: string, + /** + * 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?: GetPatentsByAuthorOptions, - ): Observable; - public getPatentsByAuthor( - authorId: string, + 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?: GetPatentsByAuthorOptions, - ): Observable>; - public getPatentsByAuthor( - authorId: string, + 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?: GetPatentsByAuthorOptions, - ): Observable>; - public getPatentsByAuthor( - authorId: string, + 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?: GetPatentsByAuthorOptions, + 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 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']); @@ -89,6 +166,7 @@ export class PatentsService extends BaseService { const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; let responseType_: 'text' | 'json' | 'blob' = 'json'; @@ -104,18 +182,235 @@ export class PatentsService extends BaseService { } } - let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam( + let localVarPath = `/api/inse-service/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, { - name: 'authorId', - value: authorId, - in: 'path', - style: 'simple', - explode: false, - dataType: 'string', - dataFormat: undefined, + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, }, - )}/patents`; + ); + } + /** + * Returns one publication by OpenAlex ID or DOI. + * @endpoint get /api/inse-service/authors/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 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, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPatentByIdOrTitle( + identifier: string, + prefix?: string, + title?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentByIdOrTitle( + identifier: string, + prefix?: string, + title?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentByIdOrTitle( + identifier: string, + prefix?: 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 getPatentByIdOrTitle.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + prefix, + 'prefix', + ); + 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/inse-service/authors/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', @@ -133,34 +428,4 @@ export class PatentsService extends BaseService { }, ); } - - public getAllPatents( - page: number = 0, - size: number = 10, - search?: string, - source?: string, - sortBy: string = 'date', - sortDirection: string = 'desc', - ): Observable { - let params = new HttpParams() - .set('page', String(page)) - .set('size', String(size)) - .set('sort_by', sortBy) - .set('sort_direction', sortDirection); - - if (search) params = params.set('search', search); - if (source) params = params.set('source', source); - - const localVarHeaders = this.defaultHeaders; - const { basePath, withCredentials } = this.configuration; - - return this.httpClient.get( - `${basePath}/api/inse-service/patents`, - { - params, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - }, - ); - } } diff --git a/webapp/src/app/api/model/allPatentsResponse.ts b/webapp/src/app/api/model/allPatentsResponse.ts new file mode 100644 index 00000000..dfe6fb24 --- /dev/null +++ b/webapp/src/app/api/model/allPatentsResponse.ts @@ -0,0 +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 { PatentEntry } from './patentEntry'; + + +export interface AllPatentsResponse { + total: number; + page: number; + size: number; + patents: Array; +} + From 5530e5738baa656ada556f2f644d88f0b817db99 Mon Sep 17 00:00:00 2001 From: genja Date: Thu, 25 Jun 2026 22:31:40 +0200 Subject: [PATCH 60/81] search for patents added --- .../projects/eu-cordis-details/eu-details.component.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index 449bae54..27bd7922 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -38,7 +38,7 @@ export type TabType = MatTooltipModule, TopicChipComponent, OrganizationsTableComponent, - PublicationsTableComponent + PublicationsTableComponent, ], templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', @@ -569,8 +569,12 @@ export class EuDetailsComponent implements OnInit, OnDestroy { .catch((err) => console.error('Navigation to status failed:', err)); } - searchForPatent(patent: Fp7ProjectIPR) { - console.log(patent) + searchForPatent(patent:Fp7ProjectIPR): void { + this.router.navigate(['/patents'], { + queryParams: { + search: patent.title, + }, + }); } /** * Navigate back to projects list with optional filter From 78ef52e3a6e743d5688e8f91092a3e3d1251d058 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 25 Jun 2026 23:02:56 +0200 Subject: [PATCH 61/81] feat(news): initial keyword extraction from news articles --- .../main/inse/integrations/elasticsearch.py | 38 +++++++ service/src/main/inse/news/logic.py | 106 ++++++++++++++++-- service/src/main/inse/news/model.py | 1 + .../news-detail/news-detail.component.html | 14 ++- .../news-detail/news-detail.component.ts | 2 +- 5 files changed, 147 insertions(+), 14 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 27fe812a..c7343e50 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -280,3 +280,41 @@ def get( ) response.raise_for_status() return response.json() + + +def update( + index: str, + doc_id: str, + doc: Dict[str, Any], + cluster: ESCluster = ESCluster.NES, +) -> Dict[str, Any]: + elasticsearch_url, api_key = _cluster_credentials(cluster) + headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} + + with httpx.Client(timeout=httpx.Timeout(30.0)) as client: + response = client.post( + f"{elasticsearch_url}/{index}/_update/{doc_id}", + json={"doc": doc}, + headers=headers, + ) + response.raise_for_status() + return response.json() + + +def index_doc( + index: str, + doc_id: str, + document: Dict[str, Any], + cluster: ESCluster = ESCluster.NES, +) -> Dict[str, Any]: + elasticsearch_url, api_key = _cluster_credentials(cluster) + headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} + + with httpx.Client(timeout=httpx.Timeout(30.0)) as client: + response = client.put( + f"{elasticsearch_url}/{index}/_doc/{doc_id}", + json=document, + headers=headers, + ) + response.raise_for_status() + return response.json() diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 032d8bdf..b6b9d5fe 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -4,12 +4,14 @@ Business logic for the "aktuell" news index on the INSE cluster. """ +import json import logging +import re from fastapi import HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR -from ..integrations import elasticsearch +from ..integrations import elasticsearch, llm from ..persons.logic import find_ude_author_by_name, get_author_name_by_id from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage @@ -20,6 +22,15 @@ TOPIC_QUERY_CONTENT_CHARS = 300 TOPIC_NUM_CANDIDATES = 100 TOPIC_SIMILARITY = 0.5 +KEYWORD_LIMIT = 6 +KEYWORD_CONTENT_CHARS = 4000 +KEYWORD_SYSTEM_PROMPT = """\ + Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords). + Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern + des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne + weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"]. +""" + RELATED_BLOCK_SIZE = 5 RELATED_TOPIC_K = 1 EXACT_ID_CAP = 1000 @@ -231,8 +242,15 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) - relevant, authors = _get_postproc_labels(news_id) + relevant, authors, cached_keywords, postproc_id = _get_postproc_labels(news_id) topics = _get_article_topics(source.get("maintitle"), source.get("full_content")) + keywords = _get_article_keywords( + news_id, + postproc_id, + cached_keywords, + source.get("maintitle"), + source.get("full_content"), + ) return NewsArticleDetail( id=response.get("_id"), @@ -244,6 +262,7 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: relevant=relevant, authors=_build_mentioned_persons(authors), topics=topics, + keywords=keywords, ) @@ -258,6 +277,75 @@ def _get_article_topics(maintitle: str | None, full_content: str | None) -> list return [topic["display_name"] for topic in topics if topic.get("display_name")] +def _get_article_keywords( + news_id: str, + postproc_id: str | None, + cached_keywords: list, + maintitle: str | None, + full_content: str | None, +) -> list: + if cached_keywords: + return cached_keywords + + text = " ".join( + part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part + ).strip() + if not text: + return [] + + raw = llm.call( + system_prompt=KEYWORD_SYSTEM_PROMPT, + user_prompt=f"Artikel:\n{text}", + temperature=0.3, + ) + keywords = _parse_keywords(raw) + + if keywords: + _store_keywords(news_id, postproc_id, keywords) + + return keywords + + +def _parse_keywords(raw: str) -> list: + raw = (raw or "").strip() + + try: + parsed = json.loads(raw) + candidates = parsed if isinstance(parsed, list) else [] + except (json.JSONDecodeError, TypeError): + candidates = re.split(r"[,\n]", raw) + + seen = set() + keywords = [] + for item in candidates: + term = str(item).strip().strip('"').strip() + if term and term.lower() not in seen: + seen.add(term.lower()) + keywords.append(term) + + return keywords[:KEYWORD_LIMIT] + + +def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: + try: + if postproc_id: + elasticsearch.update( + index="aktuell_postproc", + doc_id=postproc_id, + doc={"keywords": keywords}, + cluster="inse", + ) + else: + elasticsearch.index_doc( + index="aktuell_postproc", + doc_id=news_id, + document={"news_id": news_id, "keywords": keywords}, + cluster="inse", + ) + except Exception: + logger.exception(f"Failed to cache keywords for {news_id}.") + + def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: try: from ..util import get_model @@ -307,28 +395,30 @@ def _build_mentioned_persons(author_names: list) -> list: return ude_persons + other_persons -def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: +def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: try: response = elasticsearch.search( index="aktuell_postproc", query={"term": {"news_id.keyword": news_id}}, - source=["relevant", "authors"], + source=["relevant", "authors", "keywords"], size=1, cluster="inse", ) except Exception: logger.exception(f"Postproc-Lookup for {news_id} failed.") - return None, [] + return None, [], [], None hits = response.get("hits", {}).get("hits", []) if not hits: - return None, [] + return None, [], [], None - postproc_source = hits[0].get("_source", {}) + hit = hits[0] + postproc_source = hit.get("_source", {}) relevant = bool(postproc_source.get("relevant", 0)) authors = postproc_source.get("authors") or [] + keywords = postproc_source.get("keywords") or [] - return relevant, authors + return relevant, authors, keywords, hit.get("_id") def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 854e2dff..b63c2bc0 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -28,6 +28,7 @@ class NewsArticleDetail(NewsArticle): relevant: Optional[bool] = None authors: List[MentionedPerson] = [] topics: List[str] = [] + keywords: List[str] = [] class NewsPage(BaseModel): diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 9df185c8..cdb886cf 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -107,17 +107,21 @@ diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index f89e16fe..e93ec298 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -24,7 +24,7 @@ interface NewsArticleDetail { full_content?: string | null; relevant?: boolean; authors?: MentionedPerson[]; - topics?: string[]; + keywords?: string[]; } @Component({ From 58871384572a5935614367a90923ea5b89fa53e7 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 25 Jun 2026 23:38:07 +0200 Subject: [PATCH 62/81] fix(news): remove misleading sort option when search is active --- .../ui/news-list/news-list.component.html | 21 +++++++------ .../ui/news-list/news-list.component.ts | 30 ++++++++++++++++--- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.html b/webapp/src/app/shared/ui/news-list/news-list.component.html index e27e43b2..e42d1783 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.html +++ b/webapp/src/app/shared/ui/news-list/news-list.component.html @@ -7,14 +7,17 @@ placeholder="Nachrichten durchsuchen..." /> - - - Neueste zuerst - Älteste zuerst - - + @if (!isSearching) { + + + Neueste zuerst + Älteste zuerst + + + } @if (showFilters) { @@ -67,7 +70,7 @@ article.maintitle || 'Kein Titel' }} @if (article.related) { - Passend zu deiner Suche + Ähnlich zu deiner Suche } diff --git a/webapp/src/app/shared/ui/news-list/news-list.component.ts b/webapp/src/app/shared/ui/news-list/news-list.component.ts index 4c9d08d4..d0c760a0 100644 --- a/webapp/src/app/shared/ui/news-list/news-list.component.ts +++ b/webapp/src/app/shared/ui/news-list/news-list.component.ts @@ -175,10 +175,32 @@ export class NewsListComponent { } articleRange(): string { - if (this.total === 0) return 'Keine Nachrichten gefunden'; + const relatedCount = this.articles.filter( + (article) => article.related, + ).length; + const matchCount = this.articles.length - relatedCount; + + if (this.total === 0 && relatedCount === 0) { + return 'Keine Nachrichten gefunden'; + } + const pageSize = this.paginationService.selection; - const start = (this.currentPage - 1) * pageSize + 1; - const end = Math.min(start + this.articles.length - 1, this.total); - return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; + const start = matchCount > 0 ? (this.currentPage - 1) * pageSize + 1 : 0; + const end = Math.min(start + matchCount - 1, this.total); + + const base = + matchCount > 0 + ? `Zeige ${start} bis ${end} von ${this.total} Nachrichten` + : 'Keine direkten Treffer'; + + if (relatedCount > 0) { + const suffix = + relatedCount === 1 + ? '1 ähnlicher Vorschlag' + : `${relatedCount} ähnliche Vorschläge`; + return `${base} · ${suffix}`; + } + + return base; } } From 79496353281fb88c6ea8a97a3b7a3fdd8ecbc361 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 26 Jun 2026 01:30:30 +0200 Subject: [PATCH 63/81] layout adjustments --- .../eu-details.component.html | 152 +----------------- .../eu-details.component.scss | 1 + .../eu-cordis-details/eu-details.component.ts | 127 +++------------ .../publications-table.component.html | 4 +- 4 files changed, 29 insertions(+), 255 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 782e5acd..9e688cb3 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -140,6 +140,7 @@ @@ -488,7 +488,7 @@
gavel -

Patente (IPRs) ({{ euProject.iprs.length }})

+

Intellectual Property Rights ({{ euProject.iprs.length }})

@for (ipr of euProject.iprs; track ipr.title) { From c9c7172f003a1f4b6c6ad96b29f79972e5eb8b63 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 26 Jun 2026 15:06:28 +0200 Subject: [PATCH 67/81] eu-details component splitted into subcomponents --- .../deliverables-cards.component.html | 33 ++ .../deliverables-cards.component.scss | 109 ++++++ .../deliverables-cards.component.ts | 17 + .../eu-details.component.html | 98 +---- .../eu-details.component.scss | 334 +++--------------- .../eu-cordis-details/eu-details.component.ts | 13 +- .../patents-cards.component.html | 49 +++ .../patents-cards.component.scss | 113 ++++++ .../patents-cards/patents-cards.component.ts | 25 ++ .../publications-table.component.scss | 3 + 10 files changed, 398 insertions(+), 396 deletions(-) create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss create mode 100644 webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts diff --git a/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html new file mode 100644 index 00000000..5a399ecb --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.html @@ -0,0 +1,33 @@ +
+ +
+ assignment +

Deliverables ({{ deliverables.length }})

+
+
+ @for (deliv of deliverables; track deliv.url) { +
+
+ file_present +
+
+
+ {{ deliv.description || 'Ohne Beschreibung' }} +
+
+ @if (deliv.deliverableType) { + {{ deliv.deliverableType }} + } + @if (deliv.url) { + + open_in_new + Zum Deliverable + + } +
+
+
+ } +
+
+
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss new file mode 100644 index 00000000..a729cc21 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.scss @@ -0,0 +1,109 @@ +// Deliverables +.deliverables-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.deliverable-item { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 14px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + transition: all 0.2s; + + &:hover { + background: #f8fafc; + } +} + +.deliv-icon { + flex-shrink: 0; + color: #7b1fa2; + + mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + } +} + +.deliv-info { + flex: 1; + min-width: 0; +} + +.deliv-description { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} + +.deliv-meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 12px; + align-items: center; + + .deliv-type { + padding: 1px 8px; + background: #f3e5f5; + border-radius: var(--sg-radius-sm); + color: #7b1fa2; + } + + .deliv-link { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--sg-primary, #0066cc); + text-decoration: none; + + &:hover { + text-decoration: underline; + } + + mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + } + } +} +.deliverable-item { + flex-wrap: wrap; +} + +.card { + margin-bottom: 24px; + border-color: #d9e2f0 !important; + border-radius: var(--sg-radius-md) !important; +} + +.section-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid #e6e9ed; +} + +.section-header mat-icon { + color: var(--sg-text-muted); + width: 22px; + height: 22px; + font-size: 22px; +} + +.section-header h2 { + margin: 0; + font-size: 18px; + font-weight: 600; + color: var(--sg-text); +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts new file mode 100644 index 00000000..99fbd049 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/deliverables-cards/deliverables-cards.component.ts @@ -0,0 +1,17 @@ +import { Component, inject } from '@angular/core'; +import { HEUDeliverable } from '../../../../api'; +import { Router } from '@angular/router'; +import { Input } from '@angular/core'; +import { MatIcon } from '@angular/material/icon'; +import { MatCard } from '@angular/material/card'; +@Component({ + selector: 'app-deliverables-cards', + imports: [MatIcon, MatCard], + templateUrl: './deliverables-cards.component.html', + styleUrl: './deliverables-cards.component.scss', +}) +export class DeliverablesCardsComponent { + @Input() deliverables: HEUDeliverable[] = []; + @Input() showHeader: boolean = true; + @Input() headerTitle: string = 'Deliverables'; +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html index 27dbfb7c..1aa56279 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.html @@ -475,108 +475,20 @@ @if (activeTab === 'organizations' && euProject.organizations) { - + } @if (activeTab === 'publications' && euProject.publications) { - + } - @if (activeTab === 'iprs' && euProject.iprs) { -
- -
- gavel -

Intellectual Property Rights ({{ euProject.iprs.length }})

-
-
- @for (ipr of euProject.iprs; track ipr.title) { -
-
- @if (ipr.type === 'PATENT') { - emoji_events - } @else { - copyright - } -
-
-
{{ ipr.title || 'Ohne Titel' }}
-
- @if (ipr.type) { - {{ ipr.type }} - } - @if (ipr.patentType) { - {{ - ipr.patentType - }} - } - @if (ipr.applicantName) { - Applicant: {{ ipr.applicantName }} - } -
-
- @if (ipr.applicationIdentifier) { - App: {{ ipr.applicationIdentifier }} - } - @if (ipr.awardIdentifier) { - Award: {{ ipr.awardIdentifier }} - } -
-
-
- } -
-
-
+ } - @if (activeTab === 'deliverables' && notEmpty(euProject.deliverables)) { -
- -
- assignment -

Deliverables ({{ euProject.deliverables?.length }})

-
-
- @for (deliv of euProject.deliverables; track deliv.url) { -
-
- file_present -
-
-
- {{ deliv.description || 'Ohne Beschreibung' }} -
-
- @if (deliv.deliverableType) { - {{ - deliv.deliverableType - }} - } - @if (deliv.url) { - - open_in_new - Zum Deliverable - - } -
-
-
- } -
-
-
+ @if (activeTab === 'deliverables' && euProject.deliverables) { + }
} @else { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss index 91fa0a59..a5a30492 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -12,31 +12,6 @@ margin-bottom: 24px; } -.back-link { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 8px 16px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; - color: var(--sg-text); - cursor: pointer; - font-size: 14px; - transition: all 0.2s; -} - -.back-link:hover { - background: #f5f7fa; - border-color: #b8c5d6; -} - -.back-link mat-icon { - width: 20px; - height: 20px; - font-size: 20px; -} - .breadcrumb { display: flex; align-items: center; @@ -93,26 +68,6 @@ font-size: 13px; } -.project-rcn { - display: inline-block; - padding: 4px 10px; - background: #e8f0fe; - color: #1a73e8; - border-radius: var(--sg-radius-sm); - font-size: 12px; - font-weight: 500; -} - -.project-acronym { - display: inline-block; - padding: 4px 10px; - background: #fff3e0; - color: #e65100; - border-radius: var(--sg-radius-sm); - font-size: 12px; - font-weight: 600; -} - h1 { margin: 0 0 8px; font-size: 26px; @@ -127,21 +82,6 @@ h1 { font-size: 14px; } -.framework-tag { - display: inline-block; - padding: 2px 10px; - background: #e8edf5; - border-radius: var(--sg-radius-sm); - color: var(--sg-text); - font-weight: 500; - cursor: pointer; - transition: all 0.2s; -} - -.framework-tag:hover { - background: #d5dde8; -} - .hero-actions { display: flex; flex-wrap: wrap; @@ -265,18 +205,14 @@ h1 { border-radius: var(--sg-radius-md) !important; } -.card ::ng-deep .mat-mdc-card-content { - padding: 0; +.section-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid #e6e9ed; } - .section-header { - display: flex; - align-items: center; - gap: 12px; - padding: 16px 20px; - border-bottom: 1px solid #e6e9ed; - } - .section-header mat-icon { color: var(--sg-text-muted); width: 22px; @@ -382,15 +318,6 @@ h1 { gap: 12px; padding: 16px 20px 12px; } -.interest-tags .interest-empty { - padding: 9px 16px; - border: 1px solid #e2e8f0; - border-style: dashed; - border-radius: 7px; - color: var(--sg-text-muted); - font-size: 13px; - font-weight: 600; -} .details-list { margin: 0; @@ -479,12 +406,6 @@ h1 { text-decoration: underline; } -.external-link .external-icon { - width: 16px; - height: 16px; - font-size: 16px; -} - .error-container { display: flex; align-items: center; @@ -577,6 +498,7 @@ h1 { justify-content: center; } } + // Program badges .program-badge { display: inline-block; @@ -676,6 +598,7 @@ h1 { transform: translateY(0); } } + // Publications .publications-list { padding: 16px 20px 20px; @@ -773,174 +696,6 @@ h1 { } } -// IPRs -.iprs-list { - padding: 16px 20px 20px; - display: flex; - flex-direction: column; - gap: 12px; -} - -.ipr-item { - cursor: pointer; - display: flex; - align-items: flex-start; - gap: 16px; - padding: 14px 16px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; - transition: all 0.2s; - - &:hover { - background: #f8fafc; - } -} - -.ipr-icon { - flex-shrink: 0; - color: #f39c12; - - mat-icon { - width: 24px; - height: 24px; - font-size: 24px; - } -} - -.ipr-info { - flex: 1; - min-width: 0; -} - -.ipr-title { - font-weight: 500; - color: var(--sg-text); - font-size: 14px; -} - -.ipr-details { - display: flex; - flex-wrap: wrap; - gap: 8px; - margin-top: 4px; - font-size: 12px; - - .ipr-type { - padding: 1px 8px; - background: #fff3e0; - border-radius: var(--sg-radius-sm); - color: #e65100; - font-weight: 500; - } - - .ipr-patent-type { - padding: 1px 8px; - background: #e8eaf6; - border-radius: var(--sg-radius-sm); - color: #283593; - } - - .ipr-applicant { - color: var(--sg-text-muted); - } -} - -.ipr-identifiers { - display: flex; - flex-wrap: wrap; - gap: 8px; - margin-top: 4px; - font-size: 11px; - color: var(--sg-text-muted); - - .ipr-app-id, - .ipr-award-id { - padding: 1px 8px; - background: #f5f7fa; - border-radius: var(--sg-radius-sm); - } -} - -// Deliverables -.deliverables-list { - padding: 16px 20px 20px; - display: flex; - flex-direction: column; - gap: 12px; -} - -.deliverable-item { - display: flex; - align-items: flex-start; - gap: 16px; - padding: 14px 16px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; - transition: all 0.2s; - - &:hover { - background: #f8fafc; - } -} - -.deliv-icon { - flex-shrink: 0; - color: #7b1fa2; - - mat-icon { - width: 24px; - height: 24px; - font-size: 24px; - } -} - -.deliv-info { - flex: 1; - min-width: 0; -} - -.deliv-description { - font-weight: 500; - color: var(--sg-text); - font-size: 14px; -} - -.deliv-meta { - display: flex; - flex-wrap: wrap; - gap: 8px; - margin-top: 4px; - font-size: 12px; - align-items: center; - - .deliv-type { - padding: 1px 8px; - background: #f3e5f5; - border-radius: var(--sg-radius-sm); - color: #7b1fa2; - } - - .deliv-link { - display: inline-flex; - align-items: center; - gap: 4px; - color: var(--sg-primary, #0066cc); - text-decoration: none; - - &:hover { - text-decoration: underline; - } - - mat-icon { - width: 16px; - height: 16px; - font-size: 16px; - } - } -} - // EuroSciVoc .eurosci-voc-grid { display: flex; @@ -1059,43 +814,6 @@ h1 { color: #005a9c; } -// Responsive -@media (max-width: 768px) { - .eurosci-voc-item { - flex-direction: column; - align-items: flex-start; - gap: 8px; - } - - .eurosci-voc-item .voc-path { - min-width: 100%; - } - - .eurosci-voc-item .search-icon { - opacity: 1; - align-self: flex-end; - } - - .eurosci-voc-item .path-segment { - font-size: 12px; - } -} - -@media (max-width: 480px) { - .eurosci-voc-item { - padding: 10px 12px; - } - - .eurosci-voc-item .path-segment { - font-size: 11px; - padding: 1px 6px; - } - - .eurosci-voc-item .voc-code { - font-size: 10px; - } -} - // ERC PIs .erc-pi-list { padding: 16px 20px 20px; @@ -1149,9 +867,37 @@ h1 { } } - .publication-item, - .ipr-item, - .deliverable-item { - flex-wrap: wrap; + .eurosci-voc-item { + flex-direction: column; + align-items: flex-start; + gap: 8px; + } + + .eurosci-voc-item .voc-path { + min-width: 100%; + } + + .eurosci-voc-item .search-icon { + opacity: 1; + align-self: flex-end; + } + + .eurosci-voc-item .path-segment { + font-size: 12px; + } +} + +@media (max-width: 480px) { + .eurosci-voc-item { + padding: 10px 12px; + } + + .eurosci-voc-item .path-segment { + font-size: 11px; + padding: 1px 6px; + } + + .eurosci-voc-item .voc-code { + font-size: 10px; } } diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts index f3c66591..dc584171 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.ts @@ -16,8 +16,9 @@ import { import { EuProjectData } from '../../../api/model/euProjectData'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; import { OrganizationsTableComponent } from './organizations-table/organizations-table/organizations-table.component'; -import { Fp7ProjectIPR } from '../../../api'; import { PublicationsTableComponent } from './publications-table/publications-table.component'; +import { PatentsCardsComponent } from './patents-cards/patents-cards.component'; +import { DeliverablesCardsComponent } from './deliverables-cards/deliverables-cards.component'; export type TabType = | 'overview' | 'organizations' @@ -39,6 +40,8 @@ export type TabType = TopicChipComponent, OrganizationsTableComponent, PublicationsTableComponent, + PatentsCardsComponent, + DeliverablesCardsComponent, ], templateUrl: './eu-details.component.html', styleUrl: './eu-details.component.scss', @@ -488,12 +491,4 @@ export class EuDetailsComponent implements OnInit, OnDestroy { } // ============= SEARCH / NAVIGATION METHODS ============= - - searchForPatent(patent: Fp7ProjectIPR): void { - this.router.navigate(['/patents'], { - queryParams: { - search: patent.title, - }, - }); - } } diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html new file mode 100644 index 00000000..8da21925 --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html @@ -0,0 +1,49 @@ +
+ +
+ gavel +

Intellectual Property Rights ({{ patents.length }})

+
+
+ @for (ipr of patents; track ipr.title) { +
+
+ @if (ipr.type === 'PATENT') { + emoji_events + } @else { + copyright + } +
+
+
{{ ipr.title || 'Ohne Titel' }}
+
+ @if (ipr.type) { + {{ ipr.type }} + } + @if (ipr.patentType) { + {{ ipr.patentType }} + } + @if (ipr.applicantName) { + Applicant: {{ ipr.applicantName }} + } +
+
+ @if (ipr.applicationIdentifier) { + App: {{ ipr.applicationIdentifier }} + } + @if (ipr.awardIdentifier) { + Award: {{ ipr.awardIdentifier }} + } +
+
+
+ } +
+
+
diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss new file mode 100644 index 00000000..43846f9a --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.scss @@ -0,0 +1,113 @@ +.section-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid #e6e9ed; +} + +.section-header mat-icon { + color: var(--sg-text-muted); + width: 22px; + height: 22px; + font-size: 22px; +} + +.section-header h2 { + margin: 0; + font-size: 18px; + font-weight: 600; + color: var(--sg-text); +} +// IPRs +.iprs-list { + padding: 16px 20px 20px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.ipr-item { + cursor: pointer; + display: flex; + align-items: flex-start; + gap: 16px; + padding: 14px 16px; + border: 1px solid #d9e2f0; + border-radius: var(--sg-radius-sm); + background: #fff; + transition: all 0.2s; + + &:hover { + background: #f8fafc; + } +} + +.ipr-icon { + flex-shrink: 0; + color: #f39c12; + + mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + } +} + +.ipr-info { + flex: 1; + min-width: 0; +} + +.ipr-title { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} + +.ipr-details { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 12px; + + .ipr-type { + padding: 1px 8px; + background: #fff3e0; + border-radius: var(--sg-radius-sm); + color: #e65100; + font-weight: 500; + } + + .ipr-patent-type { + padding: 1px 8px; + background: #e8eaf6; + border-radius: var(--sg-radius-sm); + color: #283593; + } + + .ipr-applicant { + color: var(--sg-text-muted); + } +} + +.ipr-identifiers { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; + font-size: 11px; + color: var(--sg-text-muted); + + .ipr-app-id, + .ipr-award-id { + padding: 1px 8px; + background: #f5f7fa; + border-radius: var(--sg-radius-sm); + } +} + +.ipr-item { + flex-wrap: wrap; +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts new file mode 100644 index 00000000..1d8f46ac --- /dev/null +++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts @@ -0,0 +1,25 @@ +import { Component, inject } from '@angular/core'; +import { Fp7ProjectIPR } from '../../../../api'; +import { Router } from '@angular/router'; +import { Input } from '@angular/core'; +import { MatIcon } from '@angular/material/icon'; +import { MatCard } from '@angular/material/card'; +@Component({ + selector: 'app-patents-cards', + imports: [MatIcon, MatCard], + templateUrl: './patents-cards.component.html', + styleUrl: './patents-cards.component.scss', +}) +export class PatentsCardsComponent { + @Input() patents: Fp7ProjectIPR[] = []; + @Input() showHeader: boolean = true; + @Input() headerTitle: string = 'IPRs'; + private router = inject(Router); + searchForPatent(patent: Fp7ProjectIPR): void { + this.router.navigate(['/patents'], { + queryParams: { + search: patent.title, + }, + }); + } +} diff --git a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss index f84c64b4..cc50153b 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/publications-table/publications-table.component.scss @@ -231,3 +231,6 @@ } } } +.deliverable-item { + flex-wrap: wrap; +} From dc126ba8d1c6c222b33167f74ab4fafafa7d4109 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 26 Jun 2026 15:12:40 +0200 Subject: [PATCH 68/81] made scss file even shorter --- .../eu-details.component.scss | 354 +++--------------- 1 file changed, 47 insertions(+), 307 deletions(-) diff --git a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss index a5a30492..6559f75a 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss +++ b/webapp/src/app/modules/projects/eu-cordis-details/eu-details.component.scss @@ -3,7 +3,6 @@ max-width: 100%; margin: 0 auto; } - .page-header { display: flex; align-items: center; @@ -11,7 +10,6 @@ gap: 18px; margin-bottom: 24px; } - .breadcrumb { display: flex; align-items: center; @@ -19,18 +17,15 @@ color: var(--sg-text-muted); font-size: 13px; } - .breadcrumb mat-icon { width: 18px; height: 18px; font-size: 18px; } - .breadcrumb span:last-child { color: var(--sg-text); font-weight: 500; } - .project-hero { background: #f8fafc; border: 1px solid #d9e2f0; @@ -38,11 +33,9 @@ padding: 28px 32px; margin-bottom: 28px; } - .hero-content { margin-bottom: 24px; } - .eyebrow { display: flex; align-items: center; @@ -50,7 +43,6 @@ margin-bottom: 12px; flex-wrap: wrap; } - .project-badge { display: inline-block; padding: 4px 12px; @@ -62,12 +54,10 @@ text-transform: uppercase; letter-spacing: 0.5px; } - .project-id { color: var(--sg-text-muted); font-size: 13px; } - h1 { margin: 0 0 8px; font-size: 26px; @@ -75,19 +65,16 @@ h1 { font-weight: 700; color: var(--sg-text); } - .project-framework { margin: 0 0 16px; color: var(--sg-text-muted); font-size: 14px; } - .hero-actions { display: flex; flex-wrap: wrap; gap: 10px; } - .status-badge { display: inline-flex; align-items: center; @@ -100,18 +87,15 @@ h1 { cursor: pointer; transition: all 0.2s; } - .status-badge:hover { transform: translateY(-1px); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); } - .status-badge mat-icon { width: 16px; height: 16px; font-size: 16px; } - .scheme-info { display: inline-flex; align-items: center; @@ -125,19 +109,16 @@ h1 { cursor: pointer; transition: all 0.2s; } - .scheme-info:hover { background: #f5f7fa; border-color: #b8c5d6; } - .scheme-info mat-icon { color: var(--sg-text-muted); width: 18px; height: 18px; font-size: 18px; } - .doi-link { display: inline-flex; align-items: center; @@ -151,17 +132,14 @@ h1 { font-size: 13px; transition: all 0.2s; } - .doi-link:hover { background: #d5e3fa; } - .doi-link mat-icon { width: 18px; height: 18px; font-size: 18px; } - .metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); @@ -169,42 +147,35 @@ h1 { padding-top: 20px; border-top: 1px solid #d9e2f0; } - .metric-item { display: flex; align-items: center; gap: 12px; } - .metric-item mat-icon { color: var(--sg-text-muted); width: 24px; height: 24px; font-size: 24px; } - .metric-content { display: flex; flex-direction: column; } - .metric-content strong { font-size: 15px; color: var(--sg-text); line-height: 1.3; } - .metric-content span { font-size: 12px; color: var(--sg-text-muted); } - .card { margin-bottom: 24px; border-color: #d9e2f0 !important; border-radius: var(--sg-radius-md) !important; } - .section-header { display: flex; align-items: center; @@ -212,21 +183,18 @@ h1 { padding: 16px 20px; border-bottom: 1px solid #e6e9ed; } - .section-header mat-icon { color: var(--sg-text-muted); width: 22px; height: 22px; font-size: 22px; } - .section-header h2 { margin: 0; font-size: 18px; font-weight: 600; color: var(--sg-text); } - .count-badge { display: inline-flex; align-items: center; @@ -241,7 +209,6 @@ h1 { font-size: 12px; font-weight: 500; } - .description-text { padding: 16px 20px 20px; margin: 0; @@ -249,32 +216,23 @@ h1 { font-size: 14px; line-height: 1.6; } - .content-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 24px; } - -.main-content { - display: flex; - flex-direction: column; - gap: 24px; -} - +.main-content, .sidebar { display: flex; flex-direction: column; gap: 24px; } - .topics-grid { display: grid; grid-template-columns: 1fr; gap: 10px; padding: 16px 20px 20px; } - .topic-item { display: flex; align-items: center; @@ -286,19 +244,16 @@ h1 { cursor: pointer; transition: all 0.2s; } - .topic-item:hover { background: #f8fafc; border-color: #b8c5d6; transform: translateY(-1px); } - .topic-value { color: var(--sg-text); font-size: 13px; word-break: break-word; } - .topic-item .search-icon { color: var(--sg-text-muted); width: 18px; @@ -307,23 +262,19 @@ h1 { opacity: 0; transition: opacity 0.2s; } - .topic-item:hover .search-icon { opacity: 1; } - .interest-tags { display: flex; flex-wrap: wrap; gap: 12px; padding: 16px 20px 12px; } - .details-list { margin: 0; padding: 16px 20px 20px; } - .detail-row { display: grid; grid-template-columns: 140px 1fr; @@ -331,17 +282,14 @@ h1 { padding: 8px 0; border-bottom: 1px solid #f0f2f5; } - .detail-row:last-child { - border-bottom: none; + border-bottom: 0; } - .detail-row dt { color: var(--sg-text-muted); font-size: 13px; font-weight: 500; } - .detail-row dd { margin: 0; color: var(--sg-text); @@ -351,20 +299,17 @@ h1 { align-items: center; gap: 6px; } - .detail-row dd.clickable { cursor: pointer; transition: color 0.2s; } - .detail-row dd.clickable:hover { color: var(--sg-primary, #0066cc); } - -.detail-row dd.clickable:hover .search-icon { +.detail-row dd.clickable:hover .search-icon, +.detail-row dd:hover .search-icon { opacity: 1; } - .search-icon { width: 16px; height: 16px; @@ -373,11 +318,6 @@ h1 { transition: opacity 0.2s; color: var(--sg-text-muted); } - -.detail-row dd:hover .search-icon { - opacity: 1; -} - .status-indicator { display: inline-block; padding: 2px 10px; @@ -388,11 +328,9 @@ h1 { cursor: pointer; transition: all 0.2s; } - .status-indicator:hover { transform: scale(1.05); } - .external-link { display: inline-flex; align-items: center; @@ -401,18 +339,15 @@ h1 { text-decoration: none; word-break: break-all; } - .external-link:hover { text-decoration: underline; } - .error-container { display: flex; align-items: center; justify-content: center; min-height: 400px; } - .error-state { display: flex; flex-direction: column; @@ -420,77 +355,60 @@ h1 { gap: 12px; color: var(--sg-text-muted); } - .error-state mat-icon { width: 48px; height: 48px; font-size: 48px; color: #e74c3c; } - .error-state p { margin: 0; font-size: 16px; } - @media (max-width: 1116px) { .content-grid { grid-template-columns: 1fr; gap: 20px; } } - @media (max-width: 768px) { .detail-page { padding: 16px; } - .page-header { flex-direction: column; align-items: flex-start; gap: 12px; } - .project-hero { padding: 20px; } - .metrics-grid { grid-template-columns: 1fr 1fr; gap: 12px; } - h1 { font-size: 22px; } - .detail-row { grid-template-columns: 1fr; gap: 4px; } - .eyebrow { gap: 8px; } - - .topics-grid { - grid-template-columns: 1fr; - } - + .topics-grid, .interest-tags { grid-template-columns: 1fr; } } - @media (max-width: 480px) { .metrics-grid { grid-template-columns: 1fr; } - .hero-actions { flex-direction: column; } - .status-badge, .scheme-info, .doi-link { @@ -499,7 +417,6 @@ h1 { } } -// Program badges .program-badge { display: inline-block; padding: 4px 12px; @@ -508,24 +425,20 @@ h1 { font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; - - &.fp7 { - background: #e8eaf6; - color: #283593; - } - - &.h2020 { - background: #e3f2fd; - color: #0d47a1; - } - - &.heu { - background: #e8f5e9; - color: #1b5e20; - } +} +.program-badge.fp7 { + background: #e8eaf6; + color: #283593; +} +.program-badge.h2020 { + background: #e3f2fd; + color: #0d47a1; +} +.program-badge.heu { + background: #e8f5e9; + color: #1b5e20; } -// Tabs .tabs-container { display: flex; gap: 4px; @@ -536,14 +449,13 @@ h1 { border: 1px solid #d9e2f0; overflow-x: auto; } - .tab-btn { display: flex; align-items: center; gap: 8px; padding: 12px 20px; - background: transparent; - border: none; + background: 0 0; + border: 0; border-radius: var(--sg-radius-sm); color: var(--sg-text-muted); font-size: 14px; @@ -551,25 +463,21 @@ h1 { cursor: pointer; transition: all 0.2s; white-space: nowrap; - - &:hover { - background: rgba(0, 0, 0, 0.04); - color: var(--sg-text); - } - - &.active { - background: #fff; - color: var(--sg-primary, #0066cc); - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); - } - - mat-icon { - width: 20px; - height: 20px; - font-size: 20px; - } } - +.tab-btn:hover { + background: rgba(0, 0, 0, 0.04); + color: var(--sg-text); +} +.tab-btn.active { + background: #fff; + color: var(--sg-primary, #0066cc); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); +} +.tab-btn mat-icon { + width: 20px; + height: 20px; + font-size: 20px; +} .tab-badge { display: inline-flex; align-items: center; @@ -583,11 +491,9 @@ h1 { font-size: 11px; font-weight: 600; } - .tab-content { animation: fadeIn 0.3s ease; } - @keyframes fadeIn { from { opacity: 0; @@ -598,112 +504,12 @@ h1 { transform: translateY(0); } } - -// Publications -.publications-list { - padding: 16px 20px 20px; - display: flex; - flex-direction: column; - gap: 12px; -} - -.publication-item { - display: flex; - align-items: flex-start; - gap: 16px; - padding: 14px 16px; - border: 1px solid #d9e2f0; - border-radius: var(--sg-radius-sm); - background: #fff; - transition: all 0.2s; - - &:hover { - background: #f8fafc; - } -} - -.pub-icon { - flex-shrink: 0; - color: var(--sg-text-muted); - - mat-icon { - width: 24px; - height: 24px; - font-size: 24px; - } -} - -.pub-info { - flex: 1; - min-width: 0; -} - -.pub-title { - font-weight: 500; - color: var(--sg-text); - font-size: 14px; -} - -.pub-authors { - color: var(--sg-text-muted); - font-size: 13px; - margin-top: 2px; -} - -.pub-meta { - display: flex; - flex-wrap: wrap; - gap: 8px; - margin-top: 4px; - font-size: 12px; - color: var(--sg-text-muted); - - .pub-journal { - color: var(--sg-text); - } - - .pub-year, - .pub-publisher { - color: var(--sg-text-muted); - } -} - -.pub-actions { - display: flex; - gap: 8px; - flex-shrink: 0; - - .pub-link { - display: flex; - align-items: center; - justify-content: center; - width: 32px; - height: 32px; - border-radius: var(--sg-radius-sm); - color: var(--sg-text-muted); - transition: all 0.2s; - - &:hover { - background: #e8edf5; - color: var(--sg-primary, #0066cc); - } - - mat-icon { - width: 18px; - height: 18px; - font-size: 18px; - } - } -} - -// EuroSciVoc .eurosci-voc-grid { display: flex; flex-direction: column; gap: 12px; padding: 16px 20px 20px; } - .eurosci-voc-item { display: flex; align-items: center; @@ -714,13 +520,11 @@ h1 { border-radius: 8px; flex-wrap: wrap; } - .eurosci-voc-item.clickable:hover { background: #f0f3f7; border-color: #b8c5d6; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); } - .eurosci-voc-item .voc-path { display: flex; align-items: center; @@ -729,7 +533,6 @@ h1 { flex: 1; min-width: 200px; } - .eurosci-voc-item .path-segment { font-size: 13px; font-weight: 500; @@ -739,21 +542,18 @@ h1 { background: #fff; border: 1px solid #e6e9ed; } - .eurosci-voc-item .path-segment:last-child { background: #e8f0fe; border-color: #c5d8f0; color: #005a9c; font-weight: 600; } - .eurosci-voc-item .path-separator { width: 16px; height: 16px; font-size: 16px; color: #6b7a8a; } - .eurosci-voc-item .voc-code { font-size: 12px; color: #6b7a8a; @@ -763,65 +563,18 @@ h1 { border-radius: 4px; white-space: nowrap; } - .eurosci-voc-item .voc-description { font-size: 13px; color: #6b7a8a; font-style: italic; } -// Alternative: Horizontal chip-style layout -.eurosci-voc-grid-chips { - display: flex; - flex-wrap: wrap; - gap: 8px; - padding: 16px 20px 20px; -} - -.eurosci-voc-chip { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 6px 12px; - background: #f8fafc; - border: 1px solid #e6e9ed; - border-radius: 20px; - font-size: 13px; -} - -.eurosci-voc-chip:hover { - background: #f0f3f7; - border-color: #b8c5d6; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); -} - -.eurosci-voc-chip .chip-path { - display: flex; - align-items: center; - gap: 4px; -} - -.eurosci-voc-chip .chip-segment { - font-weight: 500; -} - -.eurosci-voc-chip .chip-separator { - font-size: 12px; - color: #6b7a8a; -} - -.eurosci-voc-chip .chip-segment:last-child { - color: #005a9c; -} - -// ERC PIs .erc-pi-list { padding: 16px 20px 20px; display: flex; flex-direction: column; gap: 8px; } - .erc-pi-item { display: flex; align-items: center; @@ -830,73 +583,60 @@ h1 { background: #f8fafc; border-radius: var(--sg-radius-sm); border: 1px solid #d9e2f0; - - .pi-name { - font-weight: 500; - color: var(--sg-text); - font-size: 14px; - } - - .pi-title { - color: var(--sg-text-muted); - font-size: 13px; - } +} +.erc-pi-item .pi-name { + font-weight: 500; + color: var(--sg-text); + font-size: 14px; +} +.erc-pi-item .pi-title { + color: var(--sg-text-muted); + font-size: 13px; } -// Responsive @media (max-width: 992px) { .eurosci-voc-grid { grid-template-columns: 1fr; } } - @media (max-width: 768px) { .tabs-container { gap: 2px; padding: 0 2px; } - .tab-btn { padding: 8px 12px; font-size: 12px; - - mat-icon { - width: 16px; - height: 16px; - font-size: 16px; - } } - + .tab-btn mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + } .eurosci-voc-item { flex-direction: column; align-items: flex-start; gap: 8px; } - .eurosci-voc-item .voc-path { min-width: 100%; } - .eurosci-voc-item .search-icon { opacity: 1; align-self: flex-end; } - .eurosci-voc-item .path-segment { font-size: 12px; } } - @media (max-width: 480px) { .eurosci-voc-item { padding: 10px 12px; } - .eurosci-voc-item .path-segment { font-size: 11px; padding: 1px 6px; } - .eurosci-voc-item .voc-code { font-size: 10px; } From 4a1d07cf830a31bbc1f548375b920a7ec0fe33cc Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 28 Jun 2026 17:30:29 +0200 Subject: [PATCH 69/81] fix(news): add deletet routes and resolver after merge --- webapp/src/app/app.routes.ts | 50 ++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 631fd66e..27cbb63a 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -7,6 +7,7 @@ import { personResolver } from './resolvers/person.resolver'; import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; +import { personNewsResolver } from './resolvers/person-news.resolver'; import { institutionsResolver } from './resolvers/institutions.resolver'; import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver'; import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver'; @@ -57,8 +58,15 @@ export const routes: Routes = [ }, runGuardsAndResolvers: (to, from) => { const keys = [ - 'query', 'page', 'pageSize', 'institutionName', - 'sortBy', 'sortOrder', 'yearFilterEnabled', 'filterMode', 'filterYear', + 'query', + 'page', + 'pageSize', + 'institutionName', + 'sortBy', + 'sortOrder', + 'yearFilterEnabled', + 'filterMode', + 'filterYear', ]; const scalarChanged = keys.some( (key) => to.queryParamMap.get(key) !== from.queryParamMap.get(key), @@ -71,6 +79,20 @@ export const routes: Routes = [ return scalarChanged || topicsChanged; }, }, + { + path: 'news', + canActivate: [userGuard], + loadComponent: () => + import('./modules/news/news.component').then((mod) => mod.NewsComponent), + }, + { + path: 'news/:id', + canActivate: [userGuard], + loadComponent: () => + import('./modules/news-detail/news-detail.component').then( + (mod) => mod.NewsDetailComponent, + ), + }, { path: 'publication/:publicationId', canActivate: [userGuard], @@ -102,7 +124,7 @@ export const routes: Routes = [ ), resolve: { bundSingleProject: bundSingleProjectResolver }, }, - { + { path: 'projects/eu/:id', canActivate: [userGuard], pathMatch: 'full', @@ -165,9 +187,15 @@ export const routes: Routes = [ resolve: { collaborationNetwork: collaborationNetworkResolver }, runGuardsAndResolvers: (from, to) => { const keys = [ - 'filter_by', 'start_year', 'end_year', 'min_contributors', - 'max_contributors', 'min_collaborations', 'max_collaborations', - 'institutions', 'topics', + 'filter_by', + 'start_year', + 'end_year', + 'min_contributors', + 'max_contributors', + 'min_collaborations', + 'max_collaborations', + 'institutions', + 'topics', ]; return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), @@ -267,7 +295,12 @@ export const routes: Routes = [ resolve: { fundingProjectPage: fundingProjectPageResolver }, runGuardsAndResolvers: (from, to) => { const keys = [ - 'search', 'page', 'size', 'selected_project_types', 'sort_by', 'sorting_order', + 'search', + 'page', + 'size', + 'selected_project_types', + 'sort_by', + 'sorting_order', ]; return keys.some( (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), @@ -298,7 +331,8 @@ export const routes: Routes = [ data: { routeStatusCode: 404, routeTitle: 'Seite nicht gefunden', - routeMessage: 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.', + routeMessage: + 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.', }, canActivate: [userGuard], }, From 24d73b843434584149d286b8743249cf2bdd5481 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 11:43:45 +0200 Subject: [PATCH 70/81] remove Elastic library dependency from Dockerfile and project toml. Add global Exceptions --- service/Dockerfile | 1 - service/pyproject.toml | 1 - service/src/main/inse/exceptions.py | 15 ++ .../main/inse/integrations/elasticsearch.py | 180 ++++++++++++------ service/src/main/inse/main.py | 8 +- 5 files changed, 141 insertions(+), 64 deletions(-) diff --git a/service/Dockerfile b/service/Dockerfile index 90d1a619..1c1f95a2 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -13,7 +13,6 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "pytest~=8.1.0" \ "httpx~=0.27.0" \ "python-multipart~=0.0.19"\ - "elasticsearch~=9.4.0" \ "openai~=2.41.0" COPY [ "src/main", "/home" ] diff --git a/service/pyproject.toml b/service/pyproject.toml index 9e45ebc4..7a21303c 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -7,7 +7,6 @@ requires-python = ">=3.12" dependencies = [ "cryptography~=42.0.0", "dotenv>=0.9.9", - "elasticsearch~=9.4.0", "fastapi~=0.115.0", "httpx~=0.27.0", "openai~=2.41.0", diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py index 772a9607..ed59f58b 100644 --- a/service/src/main/inse/exceptions.py +++ b/service/src/main/inse/exceptions.py @@ -1,3 +1,18 @@ class NotFoundException(Exception): def __init__(self, message: str): super().__init__(message) + + +class ElasticsearchException(Exception): + """Base exception for all Elasticsearch integrations.""" + pass + + +class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException): + """Raised when an Elasticsearch document or index is not found.""" + pass + + +class ElasticsearchConnectionException(ElasticsearchException): + """Raised when connecting to Elasticsearch fails.""" + pass diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index c7343e50..1cb37add 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,13 +1,36 @@ import json import logging -from typing import Any, Dict, Iterator, List, Optional, Tuple +from typing import Any, Dict, AsyncIterator, List, Optional, Tuple + import httpx +from inse.exceptions import ( + ElasticsearchException, + ElasticsearchNotFoundException, + ElasticsearchConnectionException, +) from inse.model import ESCluster, ESIndex from .. import config logger = logging.getLogger(__name__) +_client: Optional[httpx.AsyncClient] = None +_loop = None + + +def get_client() -> httpx.AsyncClient: + global _client, _loop + try: + import asyncio + current_loop = asyncio.get_running_loop() + except RuntimeError: + current_loop = None + + if _client is None or _loop is not current_loop: + _client = httpx.AsyncClient(timeout=httpx.Timeout(30.0)) + _loop = current_loop + return _client + def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: """Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration. @@ -21,7 +44,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: Returns: Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster. """ - + if cluster == ESCluster.NES: if ( not config.settings.elasticsearch_url @@ -30,6 +53,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: raise ValueError( "Elasticsearch URL and API key must be set in the configuration for cluster 'nes'" ) + return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key elif cluster == ESCluster.INSE: if ( @@ -80,8 +104,18 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: return None -def search( - index: ESIndex | List[ESIndex], +def _wrap_exception(e: Exception) -> Exception: + if isinstance(e, httpx.HTTPStatusError): + if e.response.status_code == 404: + return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}") + return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}") + elif isinstance(e, httpx.RequestError): + return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}") + return ElasticsearchException(f"Unexpected Elasticsearch error: {e}") + + +async def search( + index: ESIndex | List[ESIndex] | str | List[str], query: Optional[Dict] = None, source: Optional[List] = None, size: Optional[int] = None, @@ -112,10 +146,11 @@ def search( clusters = set() if isinstance(index, list): for idx in index: - cluster_for_index = _index_to_cluster(idx) - if cluster_for_index is not None: - clusters.add(cluster_for_index) - else: + if isinstance(idx, ESIndex): + cluster_for_index = _index_to_cluster(idx) + if cluster_for_index is not None: + clusters.add(cluster_for_index) + elif isinstance(index, ESIndex): cluster_for_index = _index_to_cluster(index) if cluster_for_index is not None: clusters.add(cluster_for_index) @@ -156,111 +191,125 @@ def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided" ) - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" - ) - if isinstance(index, list): - index_str = ",".join(index) - else: - index_str = index + client = get_client() + logger.debug( + f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" + ) + if isinstance(index, list): + index_str = ",".join(str(idx) for idx in index) + else: + index_str = str(index) - response = client.post( + try: + response = await client.post( f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc -def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str: +async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str: """Opens a point-in-time on the given index and returns its id.""" elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.post( + client = get_client() + try: + response = await client.post( f"{elasticsearch_url}/{index}/_pit", params={"keep_alive": keep_alive}, headers=headers, ) response.raise_for_status() return response.json()["id"] + except Exception as exc: + raise _wrap_exception(exc) from exc -def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: +async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.request( + client = get_client() + try: + response = await client.request( "DELETE", f"{elasticsearch_url}/_pit", json={"id": pit_id}, headers=headers, ) response.raise_for_status() + except Exception as exc: + raise _wrap_exception(exc) from exc -def scan( +async def scan( index: str, query: Dict, source: Optional[List] = None, page_size: int = 1000, keep_alive: str = "1m", cluster: str = "nes", -) -> Iterator[Dict[str, Any]]: +) -> AsyncIterator[Dict[str, Any]]: """Yields every hit matching ``query`` using a point-in-time + ``search_after``. - + Unlike ``from``/``size`` pagination, this is not bounded by ``index.max_result_window``, so it can stream result sets larger than 10k. """ elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - pit_id = open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) + pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None try: - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - while True: - payload: Dict[str, Any] = { - "size": page_size, - "query": query, - "pit": {"id": pit_id, "keep_alive": keep_alive}, - "sort": [{"_shard_doc": "asc"}], - "track_total_hits": False, - } - if source is not None: - payload["_source"] = source - if search_after is not None: - payload["search_after"] = search_after + client = get_client() + while True: + payload: Dict[str, Any] = { + "size": page_size, + "query": query, + "pit": {"id": pit_id, "keep_alive": keep_alive}, + "sort": [{"_shard_doc": "asc"}], + "track_total_hits": False, + } + if source is not None: + payload["_source"] = source + if search_after is not None: + payload["search_after"] = search_after - response = client.post( + try: + response = await client.post( f"{elasticsearch_url}/_search", json=payload, headers=headers ) response.raise_for_status() - result = response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc - hits = result.get("hits", {}).get("hits", []) - if not hits: - break + result = response.json() - yield from hits + hits = result.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + yield hit # The pit id can be refreshed between requests; keep the latest. - pit_id = result.get("pit_id", pit_id) - search_after = hits[-1].get("sort") - if search_after is None or len(hits) < page_size: - break + pit_id = result.get("pit_id", pit_id) + search_after = hits[-1].get("sort") + if search_after is None or len(hits) < page_size: + break finally: try: - close_point_in_time(pit_id, cluster=cluster) + await close_point_in_time(pit_id, cluster=cluster) except Exception: logger.exception("Failed to close Elasticsearch point-in-time.") -def get( - index: ESIndex, +async def get( + index: ESIndex | str, doc_id: str, source: Optional[list] = None, cluster: ESCluster = ESCluster.NES, @@ -274,15 +323,18 @@ def get( if source is not None: params["_source_includes"] = ",".join(source) - with httpx.Client() as client: - response = client.get( + client = get_client() + try: + response = await client.get( f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc -def update( +async def update( index: str, doc_id: str, doc: Dict[str, Any], @@ -291,17 +343,20 @@ def update( elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.post( + client = get_client() + try: + response = await client.post( f"{elasticsearch_url}/{index}/_update/{doc_id}", json={"doc": doc}, headers=headers, ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc -def index_doc( +async def index_doc( index: str, doc_id: str, document: Dict[str, Any], @@ -310,11 +365,14 @@ def index_doc( elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.put( + client = get_client() + try: + response = await client.put( f"{elasticsearch_url}/{index}/_doc/{doc_id}", json=document, headers=headers, ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index e82349d9..6c339764 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -14,7 +14,7 @@ from fastapi.responses import JSONResponse, RedirectResponse from inse.collaboration_network.router import router as collaboration_network_router from inse.company_connections.service import router as company_connections_router -from inse.exceptions import NotFoundException +from inse.exceptions import NotFoundException, ElasticsearchException from inse.funders.service import router as funders_service_router from inse.projects.router import router as projects_router from inse.university_ranking.router import router as university_ranking_router @@ -83,6 +83,12 @@ async def handle_not_found(request: Request, exc: NotFoundException): return JSONResponse(status_code=404, content={"message": str(exc)}) +@app.exception_handler(ElasticsearchException) +async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException): + logger.error("Elasticsearch integration error: %s", str(exc)) + return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"}) + + @app.exception_handler(404) async def redirect(_, __): return RedirectResponse(url="/inse-webapp/") From ac27fe3cf81ce22573943a53f59cd1f41855782b Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 11:57:07 +0200 Subject: [PATCH 71/81] replaced all httpx with elastic wrapper. adjusted some logic calls with async await --- .../inse/company_connections/search_client.py | 53 +++++-------- .../inse/funders/elastic_search_client.py | 19 ++--- .../institutions_search_client.py | 24 +++--- .../elastic_search_all_patents_client.py | 16 +--- .../inse/patents/elastic_search_client.py | 2 +- service/src/main/inse/works/search_client.py | 77 ++++++++----------- 6 files changed, 74 insertions(+), 117 deletions(-) diff --git a/service/src/main/inse/company_connections/search_client.py b/service/src/main/inse/company_connections/search_client.py index 4516f4f7..ddc775c7 100644 --- a/service/src/main/inse/company_connections/search_client.py +++ b/service/src/main/inse/company_connections/search_client.py @@ -5,6 +5,11 @@ import httpx from .. import config +from inse.integrations import elasticsearch +from inse.model import ESCluster +from inse.exceptions import ElasticsearchNotFoundException + + class MissingApiKeyError(Exception): pass @@ -28,7 +33,7 @@ class CompanyConnectionsSearchClient: api_key if api_key is not None else config.settings.elasticsearch_api_key -) + ) self.openalex_index = openalex_index self.handelsregister_index = handelsregister_index self.timeout = timeout @@ -39,26 +44,15 @@ class CompanyConnectionsSearchClient: return author_id.strip().removeprefix("https://openalex.org/") async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None: - if not self.api_key: - raise MissingApiKeyError("Elasticsearch API key is not configured.") - doc_id = self.openalex_doc_id(author_id) - - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.get( - f"/{self.openalex_index}/_doc/{doc_id}", - headers={"Authorization": f"ApiKey {self.api_key}"}, + try: + return await elasticsearch.get( + index=self.openalex_index, + doc_id=doc_id, + cluster=ESCluster.NES, ) - - if response.status_code == 404: - return None - - response.raise_for_status() - return response.json() + except ElasticsearchNotFoundException: + return None async def search_handelsregister_by_officer_name( self, @@ -66,27 +60,16 @@ class CompanyConnectionsSearchClient: size: int = 10000, track_total_hits: bool = True, ) -> dict[str, Any]: - if not self.api_key: - raise MissingApiKeyError("Elasticsearch API key is not configured.") - payload = self.handelsregister_officer_name_query( officer_name=officer_name, size=size, track_total_hits=track_total_hits, ) - - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.handelsregister_index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json=payload, - ) - response.raise_for_status() - return response.json() + return await elasticsearch.search( + index=self.handelsregister_index, + body=payload, + cluster=ESCluster.INSE, + ) @staticmethod def handelsregister_officer_name_query( diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py index a411cb0a..22029054 100644 --- a/service/src/main/inse/funders/elastic_search_client.py +++ b/service/src/main/inse/funders/elastic_search_client.py @@ -8,6 +8,8 @@ from typing import Any import httpx from .. import config +from inse.integrations import elasticsearch +from inse.model import ESCluster class MissingApiKeyError(Exception): @@ -177,15 +179,8 @@ class FundedPublicationsSearchClient: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json=payload, - ) - response.raise_for_status() - return response.json() + return await elasticsearch.search( + index=self.index, + body=payload, + cluster=ESCluster.NES, + ) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 0e86c8de..975d6c4d 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -20,7 +20,7 @@ class InstitutionsSearchClient: """ pass - def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: + async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: """Retrieves an institution by its raw OpenAlex institution ID. Args: @@ -38,7 +38,7 @@ class InstitutionsSearchClient: } } - res = elasticsearch.search(index="openalex-institutions", query=query, size=1) + res = await elasticsearch.search(index="openalex-institutions", query=query, size=1) hits = res.get("hits", {}).get("hits", []) if not hits: @@ -72,7 +72,7 @@ class InstitutionsSearchClient: # TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache. return cache.get(raw_institution_id) - def get_institutions_by_name( + async def get_institutions_by_name( self, name: str, page: int = 0, @@ -122,7 +122,7 @@ class InstitutionsSearchClient: query, ) try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-institutions", offset=page * size, size=size, @@ -189,7 +189,7 @@ class InstitutionsSearchClient: query, ) - res = elasticsearch.search(index="openalex-authors", query=query) + res = await elasticsearch.search(index="openalex-authors", query=query) hits = res.get("hits", {}).get("hits", []) # Extracting display_name directly from the author document source @@ -200,7 +200,7 @@ class InstitutionsSearchClient: } return list(authors) - def search_institutions( + async def search_institutions( self, query_text: str, country_code: str | None = None, @@ -265,7 +265,7 @@ class InstitutionsSearchClient: } } - res = elasticsearch.search( + res = await elasticsearch.search( index="openalex-institutions", query=query, size=limit, @@ -288,7 +288,7 @@ class InstitutionsSearchClient: return [Institution.from_dict(hit["_source"]) for hit in hits] - def get_institution_aliases_by_oa_institution_id( + async def get_institution_aliases_by_oa_institution_id( self, raw_oa_institution_id: str ) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. @@ -299,7 +299,7 @@ class InstitutionsSearchClient: Returns: List[str]: A list of aliases for the given institution ID. """ - institution = self.get_institution_by_id(raw_oa_institution_id) + institution = await self.get_institution_by_id(raw_oa_institution_id) aliases = list( self.augment_aliases(set(institution.display_name_alternatives or [])) | self.get_predefined_institution_aliases(raw_oa_institution_id) @@ -426,7 +426,7 @@ class InstitutionsSearchClient: ) return None - def get_cordis_eu_organisation_ids_by_oa_institution_id( + async def get_cordis_eu_organisation_ids_by_oa_institution_id( self, raw_oa_institution_id: str ) -> Optional[List[str]]: """Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices. @@ -439,7 +439,7 @@ class InstitutionsSearchClient: """ institution_aliases = set( - self.get_institution_aliases_by_oa_institution_id( + await self.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id=raw_oa_institution_id ) ) @@ -476,7 +476,7 @@ class InstitutionsSearchClient: try: # IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results - response = elasticsearch.search( + response = await elasticsearch.search( index="cordis_eu_*_organizations", body=body, cluster="inse" ) except Exception as e: diff --git a/service/src/main/inse/patents/elastic_search_all_patents_client.py b/service/src/main/inse/patents/elastic_search_all_patents_client.py index 4584f40b..da4c959c 100644 --- a/service/src/main/inse/patents/elastic_search_all_patents_client.py +++ b/service/src/main/inse/patents/elastic_search_all_patents_client.py @@ -10,6 +10,9 @@ import httpx from .. import config from .elastic_search_client import MissingApiKeyError +from inse.integrations import elasticsearch +from inse.model import ESCluster + EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" @@ -119,15 +122,4 @@ class AllPatentsSearchClient: return await self._search(USPTO_INDEX, payload) async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{index}/_search", - headers=self._headers(), - json=payload, - ) - response.raise_for_status() - return response.json() \ No newline at end of file + return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE) \ No newline at end of file diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 698e9d84..803201aa 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -172,7 +172,7 @@ class PatentSearchClient: return await self._search(ESIndex.USPTO_INDEX, payload) async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: - response = elasticsearch.search(index=index,body=payload,cluster=ESCluster.INSE) + response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE) return response async def get_by_id_or_title( diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 93188678..d4f0aa40 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -141,62 +141,49 @@ class OpenAlexWorksSearchClient: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json=self.author_works_query( - author_id, - page, - size, - publication_year=publication_year, - work_type=work_type, - language=language, - institution_id=institution_id, - topic_id=topic_id, - ), - ) - # logging.debug(f"Response: {response.text}") - response.raise_for_status() - return response.json() - + body = self.author_works_query( + author_id, + page, + size, + publication_year=publication_year, + work_type=work_type, + language=language, + institution_id=institution_id, + topic_id=topic_id, + ) + return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,) async def search_work(self, identifier: str) -> dict[str, Any]: - if not self.api_key: - raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - decoded_id = urllib.parse.unquote(identifier) - body = { - "query": { - "bool": { + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + decoded_id = urllib.parse.unquote(identifier) + body = { + "query": { + "bool": { "should": [ { - "term": { - "_id": { - "value": decoded_id, - "boost": 5 + "term": { + "_id": { + "value": decoded_id, + "boost": 5 + } } - } }, { - "term": { - "doi": { - "value": "https://doi.org/" + decoded_id.lower(), - "boost": 3 + "term": { + "doi": { + "value": "https://doi.org/" + decoded_id.lower(), + "boost": 3 + } } } - } ], "minimum_should_match": 1 - } } - } - print(body) - response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) - return response + } + } + response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1) + return response async def search_for_work_by_title( self, @@ -220,6 +207,6 @@ class OpenAlexWorksSearchClient: {"cited_by_count": {"order": "desc", "missing": "_last"}}, ], } - response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) + response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) return response \ No newline at end of file From da3541777858c550f6d4b8f473b8c2099af1da17 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 12:10:28 +0200 Subject: [PATCH 72/81] adjusted old fragile logic for topic cache. Adjusted more async await and new global exceptions --- service/src/main/inse/logic.py | 57 +++++------- service/src/main/inse/persons/logic.py | 106 ++++++++++------------- service/src/main/inse/persons/service.py | 44 +++++----- 3 files changed, 93 insertions(+), 114 deletions(-) diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 19e9dda3..bc3edcf6 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -18,6 +18,7 @@ import json from . import schema from . import model from . import config +from inse.integrations import elasticsearch from inse.models.openalex.topic import Topic @@ -103,56 +104,42 @@ def _load_topic_cache() -> dict: return {} -def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict: +async def build_topic_cache(save_json: bool = True) -> dict: """ Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task). Arguments: - page_size (int): Number of topics to fetch per request (default: 200) save_json (bool): Whether to save the cache as a JSON file (default: True) Returns: taxonomy_cache (dict): The topic hierarchy dictionary. """ output_filename: str = "topic_hierarchy_cache.json" - headers = { - "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", - "Content-Type": "application/json", - } taxonomy_cache = {} - offset = 0 - with httpx.Client(timeout=30.0) as client: - while True: - payload = {"query": {"match_all": {}}, "from": offset, "size": page_size} - response = client.post( - config.settings.elasticsearch_url + "/openalex-topics/_search", - json=payload, - headers=headers, - ) - response.raise_for_status() - data = response.json() + try: + async for hit in elasticsearch.scan( + index="openalex-topics", + query={"match_all": {}}, + source=["display_name", "name", "id", "subfield", "field", "domain"], + cluster="nes", + ): + source = hit.get("_source", {}) + topic_name = source.get("display_name") or source.get("name") + if not topic_name: + continue - hits = data.get("hits", {}).get("hits", []) - if not hits: - break + taxonomy_cache[topic_name] = { + "topic_id": source.get("id") or hit.get("_id", ""), + "subfield": source.get("subfield", {}).get("display_name", ""), + "field": source.get("field", {}).get("display_name", ""), + "domain": source.get("domain", {}).get("display_name", ""), + } + except Exception as exc: + logger.error("Failed to scan topics from Elasticsearch: %s", exc) - for hit in hits: - source = hit.get("_source", {}) - topic_name = source.get("display_name") or source.get("name") - if not topic_name: - continue - - taxonomy_cache[topic_name] = { - "topic_id": source.get("id") or hit.get("_id", ""), - "subfield": source.get("subfield", {}).get("display_name", ""), - "field": source.get("field", {}).get("display_name", ""), - "domain": source.get("domain", {}).get("display_name", ""), - } - - offset += len(hits) - logger.info("Processed %s topics total", len(taxonomy_cache)) + logger.info("Processed %s topics total", len(taxonomy_cache)) if save_json: data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 8c5238f9..6c82c35e 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -9,11 +9,17 @@ import logging import time from datetime import datetime from typing import Optional, Callable, Any, List -from elasticsearch import ApiError, NotFoundError import hashlib import httpx from fastapi import HTTPException +from inse.exceptions import ( + NotFoundException, + ElasticsearchException, + ElasticsearchNotFoundException, + ElasticsearchConnectionException, +) + from inse.model import ESIndex from .. import config from .. import util @@ -35,7 +41,7 @@ logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen -def find_ude_author_by_name(display_name: str) -> Optional[dict]: +async def find_ude_author_by_name(display_name: str) -> Optional[dict]: query = { "_source": ["display_name"], "query": { @@ -63,7 +69,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]: } try: - data = elasticsearch.search(index=INDEX_NAME, body=query) + data = await elasticsearch.search(index=INDEX_NAME, body=query) except Exception: logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.") return None @@ -89,7 +95,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]: } -def get_author_name_by_id(author_id: str) -> Optional[str]: +async def get_author_name_by_id(author_id: str) -> Optional[str]: try: query = { "_source": ["id", "display_name"], @@ -99,7 +105,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]: "size": 1, } - data = elasticsearch.search(index=INDEX_NAME, body=query) + data = await elasticsearch.search(index=INDEX_NAME, body=query) hits = data.get("hits", {}).get("hits", []) if not hits: return None @@ -109,7 +115,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]: return None -def search_persons( +async def search_persons( author_id: Optional[str] = None, query: Optional[str] = None, ) -> AuthorsListResponse: @@ -131,7 +137,7 @@ def search_persons( else: return AuthorsListResponse(results=[], meta=Meta(count=0)) - data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_) + data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_) authors = [] for hit in data.get("hits", {}).get("hits", []): @@ -155,7 +161,7 @@ def search_persons( return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) -def _fetch_author_display_name(author_id: str) -> Optional[str]: +async def _fetch_author_display_name(author_id: str) -> Optional[str]: query = { "query_string": { @@ -164,7 +170,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]: } } - response = elasticsearch.search( + response = await elasticsearch.search( index=INDEX_NAME, query=query, source=["display_name"], @@ -178,7 +184,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]: return hits[0].get("_source", {}).get("display_name") -def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: +async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: WORK_SOURCE_FIELDS = [ "title", @@ -221,7 +227,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: }, } - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) @@ -251,7 +257,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics -def _get_publication_years_for_author(author_id: str) -> list[int]: +async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" body = { @@ -278,7 +284,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: }, } - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) @@ -359,8 +365,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: ) -def get_career_metrics_for_author(author_id: str) -> CareerMetrics: - publication_years = _get_publication_years_for_author(author_id) +async def get_career_metrics_for_author(author_id: str) -> CareerMetrics: + publication_years = await _get_publication_years_for_author(author_id) return _compute_career_metrics(publication_years) @@ -382,13 +388,13 @@ def _build_papers(works: list) -> list: return papers -def get_data_for_bio(author_id: str) -> Optional[dict]: +async def get_data_for_bio(author_id: str) -> Optional[dict]: - display_name = _fetch_author_display_name(author_id) + display_name = await _fetch_author_display_name(author_id) if display_name is None: return None - works, top_topics = _fetch_works_and_topics(author_id) + works, top_topics = await _fetch_works_and_topics(author_id) papers = _build_papers(works) author_data = { @@ -399,9 +405,9 @@ def get_data_for_bio(author_id: str) -> Optional[dict]: return author_data -def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: +async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: start_time = time.time() - author_data = get_data_for_bio(author_id) + author_data = await get_data_for_bio(author_id) if author_data is None: return "No person found." @@ -430,27 +436,23 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s return bio -def get_person_by_id( +async def get_person_by_id( author_id: str, include: Optional[str] = None ) -> CustomAuthorsListResponse: source = include.split(",") if include else None try: - hit = elasticsearch.get( + hit = await elasticsearch.get( index="openalex-authors", doc_id=author_id, source=source, ) - except NotFoundError: - raise HTTPException( - status_code=404, detail=f"Person with id {author_id} not found" - ) - except ApiError as e: - raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") + except NotFoundException as e: + raise NotFoundException(f"Person with id {author_id} not found") from e author = util.get_persons_data(hit) start_time = time.time() - career_metrics = get_career_metrics_for_author(author_id) + career_metrics = await get_career_metrics_for_author(author_id) elapsed_time = time.time() - start_time logger.info( @@ -465,7 +467,7 @@ def get_person_by_id( return CustomAuthorsListResponse(results=[custom_author]) -def search_persons_by_name( +async def search_persons_by_name( author_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, @@ -495,7 +497,7 @@ def search_persons_by_name( } } try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-authors", query=search_query, offset=page_offset, @@ -518,7 +520,7 @@ def search_persons_by_name( ) -def search_persons_autocomplete( +async def search_persons_autocomplete( author_name: str, limit: Optional[int] = 5, include: Optional[str] = None ) -> AuthorsListResponse: if not author_name: @@ -555,7 +557,7 @@ def search_persons_autocomplete( "collapse": collapse, } try: - response = elasticsearch.search(index="openalex-authors", body=body) + response = await elasticsearch.search(index="openalex-authors", body=body) except Exception as e: raise HTTPException( status_code=500, detail=f"Elasticsearch search failed: {str(e)}" @@ -587,7 +589,7 @@ def search_persons_autocomplete( return AuthorsListResponse(results=persons) -def search_persons_by_institution( +async def search_persons_by_institution( institution_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, @@ -614,7 +616,7 @@ def search_persons_by_institution( } } try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-authors", query=search_query, source=include.split(",") if include else True, @@ -679,7 +681,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]: return author -def advanced_search_persons( +async def advanced_search_persons( query: Optional[str] = None, institution_name: Optional[str] = None, sort_by: Optional[str] = None, @@ -707,30 +709,19 @@ def advanced_search_persons( filter_mode=filter_mode, filter_year=filter_year, ) - response_dict = elasticsearch.search( + response_dict = await elasticsearch.search( index=INDEX_NAME, body=query_body, ) - except httpx.HTTPStatusError as e: - if e.response.status_code == 404: - logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") - return CustomAuthorsListResponse( - results=[], meta=Meta(count=0, page=page, per_page=page_size) - ) - elif e.response.status_code == 400: - logger.error(f"Elasticsearch request error: {str(e)}") - raise HTTPException( - status_code=400, detail=f"Elasticsearch request error: {str(e)}" - ) - else: - logger.error(f"Elasticsearch API error: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch API error: {str(e)}" - ) - except httpx.RequestError as e: - logger.error(f"Elasticsearch connection/request error: {str(e)}") + except ElasticsearchNotFoundException: + logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") + return CustomAuthorsListResponse( + results=[], meta=Meta(count=0, page=page, per_page=page_size) + ) + except ElasticsearchException as e: + logger.error(f"Elasticsearch search failed: {str(e)}") raise HTTPException( - status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}" + status_code=502, detail="Search service temporarily unavailable" ) except Exception as e: logger.error(f"Elasticsearch search failed: {str(e)}") @@ -739,7 +730,6 @@ def advanced_search_persons( ) total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) hits = response_dict.get("hits", {}).get("hits", []) - total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) include_career_metrics = include is None or "career_metrics" in include results = [] @@ -749,7 +739,7 @@ def advanced_search_persons( if custom_author: if include_career_metrics: start_time = time.time() - custom_author.career_metrics = get_career_metrics_for_author( + custom_author.career_metrics = await get_career_metrics_for_author( custom_author.id ) elapsed_time = time.time() - start_time diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index a1e08f62..dfdf7fd7 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -29,7 +29,7 @@ router = APIRouter( summary="Searches for persons by ID or name.", response_model_exclude_none=True, ) -def search_persons( +async def search_persons( author_id: Annotated[ str, Query(description="OpenAlex author ID (e.g., A5093075883)") ] = None, @@ -53,7 +53,7 @@ def search_persons( if include else None ) - return logic.search_persons(author_id, query) + return await logic.search_persons(author_id, query) @router.get( @@ -62,7 +62,7 @@ def search_persons( response_model=model.PersonBio, summary="Generates a bio for a person by author ID.", ) -def generate_person_bio( +async def generate_person_bio( author_id: Annotated[ str, Query(description="OpenAlex author ID (e.g., A5093075883)") ], @@ -79,7 +79,7 @@ def generate_person_bio( if include else None ) - bio = logic.generate_person_bio(author_id, include_set) + bio = await logic.generate_person_bio(author_id, include_set) return model.PersonBio(bio=bio) @router.get( @@ -89,7 +89,7 @@ def generate_person_bio( summary="Searches for person by ID.", tags=["Persons"], ) -def get_person_by_id( +async def get_person_by_id( id: Annotated[ str, Path(description="OpenAlex author ID", examples=["A5093075883"]) ], @@ -104,7 +104,7 @@ def get_person_by_id( ), ] = None, ): - return logic.get_person_by_id(author_id=id, include=include) + return await logic.get_person_by_id(author_id=id, include=include) @router.get( @@ -114,7 +114,7 @@ def get_person_by_id( summary="Searches for person by name.", tags=["Persons"], ) -def search_persons_by_name( +async def search_persons_by_name( author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], include: Annotated[ Optional[str], @@ -129,24 +129,25 @@ def search_persons_by_name( limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, ): - return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit) + return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit) + @router.get( '/persons/autocomplete', operation_id='searchPersonsAutocomplete', response_model=AuthorsListResponse, summary='Searches for person by name.', - tags=[ 'Persons' ]) -def search_persons_autocomplete( + tags=['Persons']) +async def search_persons_autocomplete( author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], include : Annotated[Optional[str], Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share" - )]): - return logic.search_persons_autocomplete(author_name=author_name,include=include) + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share" + )]): + return await logic.search_persons_autocomplete(author_name=author_name, include=include) @router.get( @@ -156,7 +157,7 @@ def search_persons_autocomplete( summary="Searches for persons by institution name.", tags=["Persons"], ) -def search_persons_by_institution( +async def search_persons_by_institution( institution_name: Annotated[ str, Query(description="Institution name (e.g., MIT, Oxford University)") ], @@ -173,7 +174,8 @@ def search_persons_by_institution( limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, ): - return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit) + return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit) + @router.get( "/persons/search-list", @@ -183,7 +185,7 @@ def search_persons_by_institution( response_model_exclude_none=True, tags=["Persons"], ) -def search_persons_list( +async def search_persons_list( query: Annotated[ Optional[str], Query(description="Search query (e.g., Arman AND Arzani)") ] = None, @@ -227,7 +229,7 @@ def search_persons_list( if include else None ) - return logic.advanced_search_persons( + return await logic.advanced_search_persons( query=query, institution_name=institution_name, sort_by=sort_by, From 5cd53834768fa1fa7912646edb605e78bb8f7fae Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 12:15:09 +0200 Subject: [PATCH 73/81] Replaced httpx in ipc_search_client, adjusted synchronous calls to use async await in logic --- service/src/main/inse/funders/logic.py | 6 +- service/src/main/inse/institutions/logic.py | 4 +- service/src/main/inse/institutions/router.py | 2 +- service/src/main/inse/news/logic.py | 117 +++++++++--------- service/src/main/inse/news/service.py | 16 +-- .../main/inse/patents/ipc_search_client.py | 16 +-- service/src/main/inse/patents/logic.py | 6 +- service/src/main/inse/topics/logic.py | 2 +- .../src/main/inse/university_ranking/logic.py | 2 +- service/src/main/inse/works/logic.py | 54 ++++---- 10 files changed, 109 insertions(+), 116 deletions(-) diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index 1976a9c8..653d1bd9 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -62,7 +62,7 @@ async def get_funders_by_author_id( funder_counts: dict[str, dict[str, Any]] = {} normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id) - author_name = _get_author_name(author_id) + author_name = await _get_author_name(author_id) try: _, all_hits = await _fetch_all_author_work_hits( @@ -180,9 +180,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: return total, results -def _get_author_name(author_id: str) -> str | None: +async def _get_author_name(author_id: str) -> str | None: short_author_id = author_id.replace("https://openalex.org/", "") - search_result = person_logic.search_persons(author_id=short_author_id) + search_result = await person_logic.search_persons(author_id=short_author_id) if not search_result.results: return None diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index 10f53cc6..64ae77d0 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -41,7 +41,7 @@ _VALID_INSTITUTION_TYPES = { async def get_institution_by_id( raw_institution_id: str, client: InstitutionsSearchClient ) -> Institution: - return client.get_institution_by_id(raw_institution_id) + return await client.get_institution_by_id(raw_institution_id) async def list_institutions( @@ -120,7 +120,7 @@ async def autocomplete_institutions( Returns institution options for autocomplete inputs using the local Elasticsearch cluster via the provided client. """ - institutions = client.search_institutions( + institutions = await client.search_institutions( query_text=query, country_code=country_code, institution_type=institution_type, diff --git a/service/src/main/inse/institutions/router.py b/service/src/main/inse/institutions/router.py index 423281c0..2709e4d9 100644 --- a/service/src/main/inse/institutions/router.py +++ b/service/src/main/inse/institutions/router.py @@ -72,7 +72,7 @@ async def search_institutions_by_name( ), ] = "asc", ) -> InstitutionPage: - return client.get_institutions_by_name( + return await client.get_institutions_by_name( name=name, page=page, size=size, diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index b6b9d5fe..15532432 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -36,7 +36,7 @@ RELATED_TOPIC_K = 1 EXACT_ID_CAP = 1000 -def get_news_page( +async def get_news_page( page: int, page_size: int, sort_order: str = "desc", @@ -46,10 +46,10 @@ def get_news_page( ) -> NewsPage: offset = (page - 1) * page_size - clauses = _filter_clauses(year_from, year_to, relevance_values) + clauses = await _filter_clauses(year_from, year_to, relevance_values) query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}} - response = _run_search( + response = await _run_search( query=query, source=["date", "maintitle", "author", "url", "intro_content", "full_content"], size=page_size, @@ -57,10 +57,10 @@ def get_news_page( sort=[{"date_full": sort_order}], ) - return _build_page(response, page, page_size) + return await _build_page(response, page, page_size) -def search_news( +async def search_news( query_text: str, page: int, page_size: int, @@ -78,14 +78,14 @@ def search_news( } # Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage). - clauses = _filter_clauses(year_from, year_to, relevance_values) + clauses = await _filter_clauses(year_from, year_to, relevance_values) exact_query = { "bool": { "must": [{"match": {"full_content": query_text}}], "filter": clauses, } } - response = _run_search( + response = await _run_search( query=exact_query, source=["date", "maintitle", "author", "url"], size=page_size, @@ -94,19 +94,20 @@ def search_news( highlight=highlight, ) - news_page = _build_page(response, page, page_size) + news_page = await _build_page(response, page, page_size) if _is_last_page(page, page_size, news_page.total): - exclude_ids = _exact_match_ids(exact_query) + exclude_ids = await _exact_match_ids(exact_query) news_page.results.extend( - _related_articles( + await _related_articles( query_text, exclude_ids=exclude_ids, extra_filters=clauses ) ) return news_page -def get_news_by_author( + +async def get_news_by_author( author_id: str, page: int = 1, page_size: int = 10, @@ -114,11 +115,11 @@ def get_news_by_author( query_text: str | None = None, ) -> NewsPage: - author_name = get_author_name_by_id(author_id) + author_name = await get_author_name_by_id(author_id) if not author_name: return _empty_page(page, page_size) - news_ids = _find_news_ids_for_author(author_name) + news_ids = await _find_news_ids_for_author(author_name) if not news_ids: return _empty_page(page, page_size) @@ -129,7 +130,7 @@ def get_news_by_author( ] offset = (page - 1) * page_size - response = _run_search( + response = await _run_search( query=es_query, source=["date", "maintitle", "author", "url"], size=page_size, @@ -137,12 +138,12 @@ def get_news_by_author( sort=[{"date_full": sort_order}], ) - news_page = _build_page(response, page, page_size) + news_page = await _build_page(response, page, page_size) if query_text and _is_last_page(page, page_size, news_page.total): - exclude_ids = _exact_match_ids(es_query) + exclude_ids = await _exact_match_ids(es_query) news_page.results.extend( - _related_articles( + await _related_articles( query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids ) ) @@ -150,7 +151,7 @@ def get_news_by_author( return news_page -def _filter_clauses( +async def _filter_clauses( year_from: int | None, year_to: int | None, relevance_values: list | None, @@ -165,14 +166,14 @@ def _filter_clauses( date_range["lte"] = year_to clauses.append({"range": {"date_year": date_range}}) - relevant_ids = _relevance_news_ids(relevance_values) + relevant_ids = await _relevance_news_ids(relevance_values) if relevant_ids is not None: clauses.append({"ids": {"values": relevant_ids}}) return clauses -def _relevance_news_ids(relevance_values: list | None) -> list | None: +async def _relevance_news_ids(relevance_values: list | None) -> list | None: selected = set(relevance_values or []) if not selected or {"relevant", "not_relevant"} <= selected: @@ -182,7 +183,7 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None: news_ids = [] try: - for hit in elasticsearch.scan( + async for hit in elasticsearch.scan( index="aktuell_postproc", query={"term": {"relevant": relevant_value}}, source=["news_id"], @@ -198,10 +199,10 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None: return news_ids -def _find_news_ids_for_author(author_name: str) -> list: +async def _find_news_ids_for_author(author_name: str) -> list: try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell_postproc", query={"term": {"authors.keyword": author_name}}, source=["news_id"], @@ -225,9 +226,9 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage: return NewsPage(total=0, page=page, page_size=page_size, results=[]) -def get_news_by_id(news_id: str) -> NewsArticleDetail: +async def get_news_by_id(news_id: str) -> NewsArticleDetail: try: - response = elasticsearch.get( + response = await elasticsearch.get( index="aktuell", doc_id=news_id, source=["date", "maintitle", "author", "url", "full_content"], @@ -242,9 +243,9 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) - relevant, authors, cached_keywords, postproc_id = _get_postproc_labels(news_id) - topics = _get_article_topics(source.get("maintitle"), source.get("full_content")) - keywords = _get_article_keywords( + relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id) + topics = await _get_article_topics(source.get("maintitle"), source.get("full_content")) + keywords = await _get_article_keywords( news_id, postproc_id, cached_keywords, @@ -260,24 +261,24 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: url=source.get("url"), full_content=source.get("full_content"), relevant=relevant, - authors=_build_mentioned_persons(authors), + authors=await _build_mentioned_persons(authors), topics=topics, keywords=keywords, ) -def _get_article_topics(maintitle: str | None, full_content: str | None) -> list: +async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list: query = " ".join( part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part ).strip() if not query: return [] - topics = _topic_vector_search(query, TOPIC_LIMIT, ["display_name"]) + topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"]) return [topic["display_name"] for topic in topics if topic.get("display_name")] -def _get_article_keywords( +async def _get_article_keywords( news_id: str, postproc_id: str | None, cached_keywords: list, @@ -301,7 +302,7 @@ def _get_article_keywords( keywords = _parse_keywords(raw) if keywords: - _store_keywords(news_id, postproc_id, keywords) + await _store_keywords(news_id, postproc_id, keywords) return keywords @@ -326,17 +327,17 @@ def _parse_keywords(raw: str) -> list: return keywords[:KEYWORD_LIMIT] -def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: +async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: try: if postproc_id: - elasticsearch.update( + await elasticsearch.update( index="aktuell_postproc", doc_id=postproc_id, doc={"keywords": keywords}, cluster="inse", ) else: - elasticsearch.index_doc( + await elasticsearch.index_doc( index="aktuell_postproc", doc_id=news_id, document={"news_id": news_id, "keywords": keywords}, @@ -346,7 +347,7 @@ def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> No logger.exception(f"Failed to cache keywords for {news_id}.") -def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: +async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: try: from ..util import get_model @@ -356,7 +357,7 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: return [] try: - response = elasticsearch.search( + response = await elasticsearch.search( index="topicvectors", body={ "knn": { @@ -378,13 +379,13 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])] -def _build_mentioned_persons(author_names: list) -> list: +async def _build_mentioned_persons(author_names: list) -> list: ude_persons = [] other_persons = [] for name in author_names: - match = find_ude_author_by_name(name) + match = await find_ude_author_by_name(name) if match: ude_persons.append( MentionedPerson(name=name, is_ude=True, person_id=match["id"]) @@ -395,9 +396,9 @@ def _build_mentioned_persons(author_names: list) -> list: return ude_persons + other_persons -def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: +async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell_postproc", query={"term": {"news_id.keyword": news_id}}, source=["relevant", "authors", "keywords"], @@ -421,9 +422,9 @@ def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | N return relevant, authors, keywords, hit.get("_id") -def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: +async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: try: - return elasticsearch.search( + return await elasticsearch.search( index="aktuell", query=query, source=source, @@ -442,7 +443,7 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig ) from exc -def _build_page(response: dict, page: int, page_size: int) -> NewsPage: +async def _build_page(response: dict, page: int, page_size: int) -> NewsPage: hits_section = response.get("hits", {}) total = hits_section.get("total", {}).get("value", 0) hits = hits_section.get("hits", []) @@ -453,7 +454,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage: if news_id: news_ids.append(news_id) - relevance_map = _get_relevance_map(news_ids) + relevance_map = await _get_relevance_map(news_ids) articles = [] for hit in hits: @@ -469,12 +470,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage: ) -def _get_relevance_map(news_ids: list) -> dict: +async def _get_relevance_map(news_ids: list) -> dict: if not news_ids: return {} try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell_postproc", query={"terms": {"news_id.keyword": news_ids}}, source=["news_id", "relevant"], @@ -499,7 +500,7 @@ def _parse_hit(hit: dict) -> NewsArticle: source = hit.get("_source", {}) fragments = hit.get("highlight", {}).get("full_content") - + if fragments: snippet = fragments[0] else: @@ -517,7 +518,7 @@ def _parse_hit(hit: dict) -> NewsArticle: def _make_preview(source: dict) -> str | None: text = source.get("intro_content") or source.get("full_content") - + if not text: return None @@ -534,9 +535,9 @@ def _is_last_page(page: int, page_size: int, total: int) -> bool: return page * page_size >= total -def _exact_match_ids(query: dict) -> list: +async def _exact_match_ids(query: dict) -> list: try: - response = _run_search( + response = await _run_search( query=query, source=[], size=EXACT_ID_CAP, @@ -554,14 +555,14 @@ def _exact_match_ids(query: dict) -> list: ] -def _related_articles( +async def _related_articles( query_text: str, exclude_ids: list | None = None, filter_news_ids: list | None = None, extra_filters: list | None = None, k: int = RELATED_BLOCK_SIZE, ) -> list: - related_terms = _related_search_terms(query_text) + related_terms = await _related_search_terms(query_text) if not related_terms: return [] @@ -577,7 +578,7 @@ def _related_articles( bool_query.setdefault("filter", []).extend(extra_filters) try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell", query={"bool": bool_query}, source=["date", "maintitle", "author", "url", "intro_content", "full_content"], @@ -595,15 +596,15 @@ def _related_articles( article.related = True articles.append(article) - relevance_map = _get_relevance_map([article.id for article in articles]) + relevance_map = await _get_relevance_map([article.id for article in articles]) for article in articles: article.relevant = relevance_map.get(article.id) return articles -def _related_search_terms(query_text: str) -> list: - topics = _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"]) +async def _related_search_terms(query_text: str) -> list: + topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"]) seen = {query_text.lower()} terms = [] diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index dcbf1b2d..b183d6fa 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -34,7 +34,7 @@ def _parse_relevance(relevance: str | None) -> list: summary="Returns a page of news articles, newest first.", tags=[Tags.NEWS], ) -def list_news( +async def list_news( page: Annotated[ int, Query(description="Page number (1-based).", ge=1) ] = 1, @@ -54,7 +54,7 @@ def list_news( int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0) ] = None, ): - return logic.get_news_page( + return await logic.get_news_page( page, page_size, sort_order, @@ -72,7 +72,7 @@ def list_news( summary="Searches news articles by full text (full_content).", tags=[Tags.NEWS], ) -def search_news( +async def search_news( query: Annotated[ str, Query(description="Search term, matched against the full text (full_content).", min_length=1) ], @@ -92,7 +92,7 @@ def search_news( int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0) ] = None, ): - return logic.search_news( + return await logic.search_news( query, page, page_size, @@ -110,7 +110,7 @@ def search_news( summary="Returns news articles in which the given person is mentioned.", tags=[Tags.NEWS], ) -def get_news_by_author( +async def get_news_by_author( author_id: Annotated[ str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.") ], @@ -127,7 +127,7 @@ def get_news_by_author( str | None, Query(description="Optional search term, matched against title/author.") ] = None, ): - return logic.get_news_by_author(author_id, page, page_size, sort_order, query) + return await logic.get_news_by_author(author_id, page, page_size, sort_order, query) @router.get( @@ -138,9 +138,9 @@ def get_news_by_author( summary="Returns a single news article including its full content.", tags=[Tags.NEWS], ) -def get_news_by_id( +async def get_news_by_id( news_id: Annotated[ str, Path(description="The unique id of the news article (Elasticsearch _id).") ], ): - return logic.get_news_by_id(news_id) + return await logic.get_news_by_id(news_id) diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py index 6ab6afa4..6e952e19 100644 --- a/service/src/main/inse/patents/ipc_search_client.py +++ b/service/src/main/inse/patents/ipc_search_client.py @@ -16,6 +16,9 @@ from .ipc_lookup import IpcHierarchyKeys from .ipc_lookup import build_ipc_classification from .ipc_lookup import parse_ipc_symbol +from inse.integrations import elasticsearch +from inse.model import ESCluster + IPC_INDEX = "ipc" _LEVELS: tuple[tuple[str, str, str], ...] = ( @@ -136,15 +139,4 @@ class IpcSearchClient: return found async def _search(self, payload: dict[str, Any]) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{IPC_INDEX}/_search", - headers=self._headers(), - json=payload, - ) - response.raise_for_status() - return response.json() + return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE) diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index d6fe29d5..3142ac3c 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -55,7 +55,7 @@ async def get_patents_by_author_id( search_client = client or PatentSearchClient() ipc_search_client = ipc_client or IpcSearchClient() - author = _get_author(author_id) + author = await _get_author(author_id) if not author: return model.PatentsByAuthorResponse( author_id=author_id, @@ -250,9 +250,9 @@ def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]: ) -def _get_author(author_id: str) -> Author | None: +async def _get_author(author_id: str) -> Author | None: short_id = author_id.replace("https://openalex.org/", "") - result = person_logic.search_persons(author_id=short_id) + result = await person_logic.search_persons(author_id=short_id) return result.results[0] if result.results else None diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index 244f70c8..90540649 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -357,7 +357,7 @@ async def vector_search_topics( } try: - raw_results = elasticsearch.search( + raw_results = await elasticsearch.search( index="topicvectors", body=body, cluster="nes" diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py index bd1e58f9..10d926ff 100644 --- a/service/src/main/inse/university_ranking/logic.py +++ b/service/src/main/inse/university_ranking/logic.py @@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran # Fetch top institutions for the topic by works_count - res = elasticsearch.search( + res = await elasticsearch.search( index="openalex-institutions", query=query, size=10, diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 7b3ed7a0..0d561b37 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -148,7 +148,7 @@ async def get_primary_topic_counts( return result -def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: +async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: indexed_author_id = f"https://openalex.org/{author_id.strip()}" @@ -174,11 +174,11 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) - except httpx.HTTPError as exc: + except Exception as exc: logger.exception("OpenAlex primary topic aggregation request failed.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, @@ -212,18 +212,18 @@ async def get_work( return elements[0] -def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: +async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: if not topic_ids: return {} try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-topics", query={"terms": {"id": topic_ids}}, source=TOPIC_DETAIL_SOURCE_FIELDS, size=len(topic_ids), ) - except httpx.HTTPError: + except Exception: logger.exception("Could not load topic details from Elasticsearch.") return {} @@ -242,7 +242,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: "domain": _extract_topic_hierarchy_item(source, "domain"), } - _enrich_topic_hierarchy_descriptions(details) + await _enrich_topic_hierarchy_descriptions(details) return details @@ -260,7 +260,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non } -def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: +async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items(): hierarchy_ids = { item.get(hierarchy_key, {}).get("id") @@ -268,7 +268,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: if item.get(hierarchy_key, {}).get("id") } - descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids)) + descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids)) for item in details.values(): hierarchy_item = item.get(hierarchy_key) or {} @@ -278,7 +278,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: hierarchy_item["description"] = descriptions[hierarchy_id] -def _get_topic_hierarchy_descriptions( +async def _get_topic_hierarchy_descriptions( index: str, hierarchy_ids: list[str], ) -> dict[str, str | None]: @@ -286,13 +286,13 @@ def _get_topic_hierarchy_descriptions( return {} try: - response = elasticsearch.search( + response = await elasticsearch.search( index=index, query={"terms": {"id": hierarchy_ids}}, source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS, size=len(hierarchy_ids), ) - except httpx.HTTPError: + except Exception: logger.exception("Could not load topic hierarchy details from %s.", index) return {} @@ -433,7 +433,7 @@ async def get_topics_by_time_by_author( client=client, ) - return _get_topics_by_time_by_author_from_es( + return await _get_topics_by_time_by_author_from_es( author_id, max_topics_per_year=max_topics_per_year, target_publications=target_publications, @@ -521,7 +521,7 @@ async def _get_topics_by_time_by_author_from_work_pages( if topic["id"]: topic_ids.add(topic["id"]) - topic_details = _get_topic_details(list(topic_ids)) + topic_details = await _get_topic_details(list(topic_ids)) elements = [] @@ -580,13 +580,13 @@ async def _get_topics_by_time_by_author_from_work_pages( ) -def _get_topics_by_time_by_author_from_es( +async def _get_topics_by_time_by_author_from_es( author_id: str, max_topics_per_year: int = 3, target_publications: int = 300, include_all: bool = False, ) -> TopicsByTime: - year_buckets, total_publications = _get_publication_year_counts_from_es(author_id) + year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id) selected_years, is_limited = _select_complete_timeline_years( year_buckets, target_publications=target_publications, @@ -602,13 +602,13 @@ def _get_topics_by_time_by_author_from_es( total_publications=total_publications, ) - year_topic_buckets = _get_timeline_topic_counts_from_es( + year_topic_buckets = await _get_timeline_topic_counts_from_es( author_id, years=selected_years, max_topics_per_year=max_topics_per_year, ) topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets) - topic_details = _get_topic_details(list(topic_ids)) + topic_details = await _get_topic_details(list(topic_ids)) elements = _build_timeline_elements_from_aggregations( year_topic_buckets, @@ -625,7 +625,7 @@ def _get_topics_by_time_by_author_from_es( ) -def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]: +async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]: body = { "size": 0, "track_total_hits": True, @@ -642,11 +642,11 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) - except httpx.HTTPError as exc: + except Exception as exc: logger.exception("OpenAlex publication year aggregation request failed.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, @@ -656,7 +656,7 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in return _parse_year_count_buckets(response), _parse_total_hits(response) -def _get_timeline_topic_counts_from_es( +async def _get_timeline_topic_counts_from_es( author_id: str, years: list[int], max_topics_per_year: int, @@ -713,11 +713,11 @@ def _get_timeline_topic_counts_from_es( } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) - except httpx.HTTPError as exc: + except Exception as exc: logger.exception("OpenAlex timeline topic aggregation request failed.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, @@ -954,7 +954,7 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: return elements, total -def get_publication_dois_of_author( +async def get_publication_dois_of_author( raw_oa_author_id: str, ) -> List[str]: query = { @@ -976,14 +976,14 @@ def get_publication_dois_of_author( } try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-works", source=["doi"], size=10000, query=query, cluster="nes", ) - except httpx.HTTPError as exc: + except Exception as exc: logger.exception("Request for publication DOIs of author failed.") raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, From aca6ae20b2ae94ad7f673a3934c8a8a295303525 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 12:22:13 +0200 Subject: [PATCH 74/81] replaced tests to mock async behavior --- service/src/main/inse/funders/test_logic.py | 492 ++++++++---------- .../inse/patents/test_ipc_search_client.py | 88 ++-- .../src/main/inse/works/test_search_client.py | 132 ++--- 3 files changed, 329 insertions(+), 383 deletions(-) diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py index 234ffdcf..9c95dbd4 100644 --- a/service/src/main/inse/funders/test_logic.py +++ b/service/src/main/inse/funders/test_logic.py @@ -1,7 +1,5 @@ -import json - -import httpx import pytest +from unittest.mock import AsyncMock, patch from fastapi import HTTPException from inse.funders import logic @@ -68,201 +66,177 @@ def _funded_publication_hit( @pytest.mark.anyio -async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - payload = json.loads(request.content.decode("utf-8")) - assert payload["from"] == 0 - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 2}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W1", - funder_id="https://openalex.org/F123", - funder_name="Funder A", - author_position="first", - pdf_url="https://example.org/w1.pdf", - abstract_inverted_index={ - "This": [0], - "is": [1], - "an": [2], - "abstract.": [3], +async def test_get_funders_by_author_id_aggregates_funders_and_awards(): + mock_es_response = { + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + author_position="first", + pdf_url="https://example.org/w1.pdf", + abstract_inverted_index={ + "This": [0], + "is": [1], + "an": [2], + "abstract.": [3], + }, + extra_source={ + "title": "Example publication: full detail", + "funders": [ + { + "id": "https://openalex.org/F456", + "display_name": "Funder B", + } + ], + "publication_year": 2020, + "publication_date": "2020-05-10", + "type": "article", + "language": "en", + "cited_by_count": 12, + "is_retracted": False, + "primary_location": { + "pdf_url": "https://example.org/w1.pdf", + "is_oa": True, + "license": "cc-by", + "source": { + "display_name": "Example Journal", + "type": "journal", }, - extra_source={ - "title": "Example publication: full detail", - "funders": [ - { - "id": "https://openalex.org/F456", - "display_name": "Funder B", - } - ], - "publication_year": 2020, - "publication_date": "2020-05-10", - "type": "article", - "language": "en", - "cited_by_count": 12, - "is_retracted": False, - "primary_location": { - "pdf_url": "https://example.org/w1.pdf", - "is_oa": True, - "license": "cc-by", - "source": { - "display_name": "Example Journal", - "type": "journal", - }, - }, - "open_access": { - "is_oa": True, - "oa_status": "gold", - "any_repository_has_fulltext": True, - }, - "primary_topic": { - "display_name": "Clinical Trials", - "subfield": {"display_name": "Medicine"}, - "field": {"display_name": "Health Sciences"}, - "domain": {"display_name": "Life Sciences"}, - }, - "topics": [ - {"display_name": "Trials", "score": 0.8}, - {"display_name": "Guidelines", "score": 0.6}, - ], - "keywords": [ - {"display_name": "randomised trials", "score": 0.9}, - {"display_name": "reporting guideline", "score": 0.7}, - ], - "counts_by_year": [ - {"year": 2024, "cited_by_count": 3}, - {"year": 2023, "cited_by_count": 2}, - ], - }, - ), - _funded_publication_hit( - "https://openalex.org/W2", - funder_id=None, - funder_name=None, - award_funder_id="https://openalex.org/F123", - award_funder_name="Funder A", - award_display_name="Project Grant", - award_number="PG-42", - author_position="last", - ), - ], - }, - }, - ) + }, + "open_access": { + "is_oa": True, + "oa_status": "gold", + "any_repository_has_fulltext": True, + }, + "primary_topic": { + "display_name": "Clinical Trials", + "subfield": {"display_name": "Medicine"}, + "field": {"display_name": "Health Sciences"}, + "domain": {"display_name": "Life Sciences"}, + }, + "topics": [ + {"display_name": "Trials", "score": 0.8}, + {"display_name": "Guidelines", "score": 0.6}, + ], + "keywords": [ + {"display_name": "randomised trials", "score": 0.9}, + {"display_name": "reporting guideline", "score": 0.7}, + ], + "counts_by_year": [ + {"year": 2024, "cited_by_count": 3}, + {"year": 2023, "cited_by_count": 2}, + ], + }, + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + award_display_name="Project Grant", + award_number="PG-42", + author_position="last", + ), + ], + }, + } - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type( - "Result", - (), - {"results": [type("Author", (), {"display_name": "Example Author"})()]}, - )(), - ) + mock_author_result = type( + "Result", + (), + {"results": [type("Author", (), {"display_name": "Example Author"})()]} + )() - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - response = await logic.get_funders_by_author_id("A5023888391", client=client) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - assert response.author_id == "https://openalex.org/A5023888391" - assert response.author_name == "Example Author" - assert response.funder_count == 2 - assert response.funders[0].funder_id == "https://openalex.org/F123" - assert response.funders[0].funder_name == "Funder A" - assert response.funders[0].publication_count == 2 - assert response.funders[0].author_position_count.first == 1 - assert response.funders[0].author_position_count.last == 1 - assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"] - assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"] - assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" - assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" - publication_detail = response.funders[0].publication_details["https://openalex.org/W1"] - assert publication_detail.title == "Example publication: full detail" - assert publication_detail.funder_names == ["Funder A", "Funder B"] - assert publication_detail.abstract == "This is an abstract." - assert publication_detail.publication_date == "2020-05-10" - assert publication_detail.publication_type == "article" - assert publication_detail.source_name == "Example Journal" - assert publication_detail.source_type == "journal" - assert publication_detail.is_open_access is True - assert publication_detail.open_access_status == "gold" - assert publication_detail.has_fulltext is True - assert publication_detail.license == "cc-by" - assert publication_detail.cited_by_count == 12 - assert publication_detail.primary_topic == "Clinical Trials" - assert publication_detail.topic_field == "Health Sciences" - assert publication_detail.topic_subfield == "Medicine" - assert publication_detail.topic_domain == "Life Sciences" - assert publication_detail.topics == ["Trials", "Guidelines"] - assert publication_detail.keywords == ["randomised trials", "reporting guideline"] - assert publication_detail.counts_by_year == [ - {"year": 2024, "cited_by_count": 3}, - {"year": 2023, "cited_by_count": 2}, - ] - assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [ - "Project Grant" - ] + assert response.author_id == "https://openalex.org/A5023888391" + assert response.author_name == "Example Author" + assert response.funder_count == 2 + + funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123") + assert funder_a.funder_name == "Funder A" + assert funder_a.publication_count == 2 + assert funder_a.author_position_count.first == 1 + assert funder_a.author_position_count.last == 1 + assert funder_a.publication_ids.first == ["https://openalex.org/W1"] + assert funder_a.publication_ids.last == ["https://openalex.org/W2"] + assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" + assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" + + pub1_detail = funder_a.publication_details["https://openalex.org/W1"] + assert pub1_detail.title == "Example publication: full detail" + assert pub1_detail.funder_names == ["Funder A", "Funder B"] + assert pub1_detail.abstract == "This is an abstract." + assert pub1_detail.publication_date == "2020-05-10" + assert pub1_detail.publication_type == "article" + assert pub1_detail.source_name == "Example Journal" + assert pub1_detail.source_type == "journal" + assert pub1_detail.is_open_access is True + assert pub1_detail.open_access_status == "gold" + assert pub1_detail.has_fulltext is True + assert pub1_detail.license == "cc-by" + assert pub1_detail.cited_by_count == 12 + assert pub1_detail.primary_topic == "Clinical Trials" + assert pub1_detail.topic_field == "Health Sciences" + assert pub1_detail.topic_subfield == "Medicine" + assert pub1_detail.topic_domain == "Life Sciences" + assert pub1_detail.topics == ["Trials", "Guidelines"] + assert pub1_detail.keywords == ["randomised trials", "reporting guideline"] + assert pub1_detail.counts_by_year == [ + {"year": 2024, "cited_by_count": 3}, + {"year": 2023, "cited_by_count": 2}, + ] + assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"] @pytest.mark.anyio -async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 1}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W3", - funder_id="https://openalex.org/F123", - funder_name="Funder A", - award_funder_id="https://openalex.org/F123", - award_funder_name="Funder A", - award_display_name=None, - award_number="ANR-12-1234", - ), - ], - }, - }, - ) +async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(): + mock_es_response = { + "hits": { + "total": {"value": 1}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W3", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + award_display_name=None, + award_number="ANR-12-1234", + ), + ], + }, + } + mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type( - "Result", - (), - {"results": [type("Author", (), {"display_name": "Example Author"})()]}, - )(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - response = await logic.get_funders_by_author_id("A5023888391", client=client) - - assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == [] + assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == [] @pytest.mark.anyio -async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch): +async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(): requested_pages: list[int] = [] - def handler(request: httpx.Request) -> httpx.Response: - payload = json.loads(request.content.decode("utf-8")) - size = payload["size"] - offset = payload["from"] + async def mock_search_func(index, body, cluster=None): + size = body["size"] + offset = body["from"] page = offset // size + 1 requested_pages.append(page) total = size + 1 @@ -284,115 +258,89 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m ) ] - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": total}, - "hits": hits, - }, + return { + "hits": { + "total": {"value": total}, + "hits": hits, }, - ) + } - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + mock_author_result = type("Result", (), {"results": []})() - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search_persons.return_value = mock_author_result - response = await logic.get_funders_by_author_id("A5023888391", client=client) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - assert requested_pages == [1, 2] - assert response.funder_count > 1 - funder_names = {funder.funder_name for funder in response.funders} - assert "Funder 1" in funder_names + assert requested_pages == [1, 2] + assert response.funder_count > 1 + funder_names = {funder.funder_name for funder in response.funders} + assert "Funder 1" in funder_names @pytest.mark.anyio -async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 2}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W1", - funder_id="https://openalex.org/F123", - funder_name="Bundesministerium", - ), - _funded_publication_hit( - "https://openalex.org/W2", - funder_id=None, - funder_name=None, - ), - ], - }, - }, - ) +async def test_get_funders_by_author_id_ignores_publications_without_funders(): + mock_es_response = { + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Bundesministerium", + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + ), + ], + }, + } + mock_author_result = type("Result", (), {"results": []})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5093075883", client=client) - response = await logic.get_funders_by_author_id("A5093075883", client=client) - - assert response.funder_count == 1 - assert response.funders[0].funder_name == "Bundesministerium" - assert response.funders[0].publication_count == 1 + assert response.funder_count == 1 + assert response.funders[0].funder_name == "Bundesministerium" + assert response.funders[0].publication_count == 1 @pytest.mark.anyio -async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={"hits": {"total": {"value": 0}, "hits": []}}, - ) +async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(): + mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}} + mock_author_result = type("Result", (), {"results": []})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5093075883", client=client) - response = await logic.get_funders_by_author_id("A5093075883", client=client) - - assert response.funder_count == 0 - assert response.funders == [] + assert response.funder_count == 0 + assert response.funders == [] @pytest.mark.anyio -async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch): - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) - client = FundedPublicationsSearchClient(api_key="") +async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(): + mock_author_result = type("Result", (), {"results": []})() - with pytest.raises(HTTPException) as exc: - await logic.get_funders_by_author_id("A5023888391", client=client) + with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search_persons.return_value = mock_author_result - assert exc.value.status_code == 503 + client = FundedPublicationsSearchClient(api_key="") + + with pytest.raises(HTTPException) as exc: + await logic.get_funders_by_author_id("A5023888391", client=client) + + assert exc.value.status_code == 503 diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py index 4bf064bd..78df758e 100644 --- a/service/src/main/inse/patents/test_ipc_search_client.py +++ b/service/src/main/inse/patents/test_ipc_search_client.py @@ -1,4 +1,4 @@ -import httpx +from unittest.mock import AsyncMock, patch import pytest from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient @@ -11,57 +11,51 @@ def anyio_backend(): @pytest.mark.anyio async def test_resolve_symbols_posts_to_ipc_index(): - requests: list[str] = [] + mock_response = { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + }, + { + "_source": { + "cpc_class_number": "H01L", + "cpc_class_name": "SEMICONDUCTOR DEVICES", + } + }, + { + "_source": { + "cpc_group_number": "H01L21/02", + "cpc_group_name": "Manufacture or treatment of semiconductor devices", + } + }, + ] + } + } - def handler(request: httpx.Request) -> httpx.Response: - requests.append(request.url.path) - return httpx.Response( - 200, - json={ - "hits": { - "hits": [ - { - "_source": { - "cpc_section_number": "H", - "cpc_section_name": "ELECTRICITY", - } - }, - { - "_source": { - "cpc_class_number": "H01L", - "cpc_class_name": "SEMICONDUCTOR DEVICES", - } - }, - { - "_source": { - "cpc_group_number": "H01L21/02", - "cpc_group_name": "Manufacture or treatment of semiconductor devices", - } - }, - ] - } - }, - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = mock_response + client = IpcSearchClient() - transport = httpx.MockTransport(handler) - client = IpcSearchClient(api_key="test-key", transport=transport) + result = await client.resolve_symbols(["H01L 21/02"]) - result = await client.resolve_symbols(["H01L 21/02"]) - - assert len(requests) >= 1 - assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests) - assert "H01L 21/02" in result - assert result["H01L 21/02"].section == "H - ELECTRICITY" - assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" + assert mock_search.call_count >= 1 + _, kwargs = mock_search.call_args + assert kwargs.get("index") == IPC_INDEX + assert "H01L 21/02" in result + assert result["H01L 21/02"].section == "H - ELECTRICITY" + assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" @pytest.mark.anyio async def test_resolve_symbols_does_not_crash_for_subclass_codes(): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(200, json={"hits": {"hits": []}}) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"hits": []}} + client = IpcSearchClient() + result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) - client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler)) - result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) - - assert "A61J 1/14" in result - assert "C07D 319/06" in result + assert "A61J 1/14" in result + assert "C07D 319/06" in result diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 0bfe1a44..1297d848 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -152,37 +152,47 @@ def test_author_works_query_adds_topic_filter(): ] +from unittest.mock import AsyncMock, patch + + @pytest.mark.anyio async def test_search_author_works_passes_institution_filter_to_query(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) - assert body["query"]["bool"]["must"][1]["nested"]["path"] == ( - "authorships.institutions" + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], ) + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") + assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions" assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == { "authorships.institutions.id": ["https://openalex.org/I205640436"], } - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_author_works( - "A5023888391", - page=1, - size=20, - institution_id=["https://openalex.org/I205640436"], - ) @pytest.mark.anyio async def test_search_author_works_passes_topic_filter_to_query(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") assert body["query"]["bool"]["filter"] == [ { "bool": { @@ -207,61 +217,55 @@ async def test_search_author_works_passes_topic_filter_to_query(): }, }, ] - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_author_works( - "A5023888391", - page=1, - size=20, - topic_id=["https://openalex.org/T12419"], - ) @pytest.mark.anyio async def test_search_author_works_calls_elasticsearch_index_with_api_key(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.method == "POST" - assert request.url.path == "/elastic/openalex-works/_search" - assert request.headers["Authorization"] == "ApiKey test-key" - return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}}) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + result = await client.search_author_works("A5023888391", page=1, size=20) - result = await client.search_author_works("A5023888391", page=1, size=20) - - assert result == {"hits": {"total": {"value": 0}, "hits": []}} + assert result == {"hits": {"total": {"value": 0}, "hits": []}} @pytest.mark.anyio async def test_search_work_filters_by_work_id(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_work("W2741809807") + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") assert body == { - "size": 1, - "query": {"term": {"id": "https://openalex.org/W2741809807"}}, + "query": { + "bool": { + "should": [ + { + "term": { + "_id": { + "value": "W2741809807", + "boost": 5 + } + } + }, + { + "term": { + "doi": { + "value": "https://doi.org/w2741809807", + "boost": 3 + } + } + } + ], + "minimum_should_match": 1 + } + } } - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_work("W2741809807") @pytest.mark.anyio From 65bb29ecd828ceae319bac919c6e9df3858b30e4 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 13:08:36 +0200 Subject: [PATCH 75/81] Added new exception and adjusted all relevant exceptions to use the new global exception instead of own httpx --- service/src/main/inse/company_connections/logic.py | 7 ++++--- service/src/main/inse/company_connections/search_client.py | 3 +-- service/src/main/inse/exceptions.py | 5 +++++ service/src/main/inse/funders/elastic_search_client.py | 3 +-- service/src/main/inse/funders/logic.py | 2 +- service/src/main/inse/integrations/elasticsearch.py | 5 +++-- .../main/inse/patents/elastic_search_all_patents_client.py | 2 +- service/src/main/inse/patents/elastic_search_client.py | 3 +-- service/src/main/inse/patents/ipc_search_client.py | 2 +- service/src/main/inse/patents/logic.py | 2 +- service/src/main/inse/works/logic.py | 6 +++--- service/src/main/inse/works/search_client.py | 3 +-- service/src/main/inse/works/test_search_client.py | 2 +- 13 files changed, 24 insertions(+), 21 deletions(-) diff --git a/service/src/main/inse/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py index 1ffea295..ad71847e 100644 --- a/service/src/main/inse/company_connections/logic.py +++ b/service/src/main/inse/company_connections/logic.py @@ -6,7 +6,8 @@ from fastapi import HTTPException from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE from . import model -from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException +from .search_client import CompanyConnectionsSearchClient logger = logging.getLogger(__name__) @@ -30,7 +31,7 @@ async def get_company_connections_by_author_id( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail="Elasticsearch is not configured.", ) from exc - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex author lookup failed for %s.", author_id) raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, @@ -68,7 +69,7 @@ async def get_company_connections_by_author_id( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail="Elasticsearch is not configured.", ) from exc - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.exception("Handelsregister lookup failed for %s.", display_name) raise HTTPException( status_code=HTTP_502_BAD_GATEWAY, diff --git a/service/src/main/inse/company_connections/search_client.py b/service/src/main/inse/company_connections/search_client.py index ddc775c7..6f041c50 100644 --- a/service/src/main/inse/company_connections/search_client.py +++ b/service/src/main/inse/company_connections/search_client.py @@ -10,8 +10,7 @@ from inse.model import ESCluster from inse.exceptions import ElasticsearchNotFoundException -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError class CompanyConnectionsSearchClient: diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py index ed59f58b..f7331b83 100644 --- a/service/src/main/inse/exceptions.py +++ b/service/src/main/inse/exceptions.py @@ -16,3 +16,8 @@ class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException): class ElasticsearchConnectionException(ElasticsearchException): """Raised when connecting to Elasticsearch fails.""" pass + + +class MissingApiKeyError(Exception): + """Raised when a required API key is missing.""" + pass diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py index 22029054..08dc6bde 100644 --- a/service/src/main/inse/funders/elastic_search_client.py +++ b/service/src/main/inse/funders/elastic_search_client.py @@ -12,8 +12,7 @@ from inse.integrations import elasticsearch from inse.model import ESCluster -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError class FundedPublicationsSearchClient: diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index 653d1bd9..098116e9 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -15,7 +15,7 @@ from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from ..persons import logic as person_logic from . import model from .elastic_search_client import FundedPublicationsSearchClient -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError logger = logging.getLogger(__name__) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 1cb37add..803aa212 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -8,6 +8,7 @@ from inse.exceptions import ( ElasticsearchException, ElasticsearchNotFoundException, ElasticsearchConnectionException, + MissingApiKeyError, ) from inse.model import ESCluster, ESIndex from .. import config @@ -50,7 +51,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: not config.settings.elasticsearch_url or not config.settings.elasticsearch_api_key ): - raise ValueError( + raise MissingApiKeyError( "Elasticsearch URL and API key must be set in the configuration for cluster 'nes'" ) @@ -60,7 +61,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: not config.settings.elasticsearch_inse_url or not config.settings.elasticsearch_inse_api_key ): - raise ValueError( + raise MissingApiKeyError( "Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'" ) diff --git a/service/src/main/inse/patents/elastic_search_all_patents_client.py b/service/src/main/inse/patents/elastic_search_all_patents_client.py index da4c959c..bdca70f5 100644 --- a/service/src/main/inse/patents/elastic_search_all_patents_client.py +++ b/service/src/main/inse/patents/elastic_search_all_patents_client.py @@ -8,7 +8,7 @@ from typing import Any import httpx from .. import config -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from inse.integrations import elasticsearch from inse.model import ESCluster diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 803201aa..a7860f4d 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -27,8 +27,7 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]: } -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError class PatentSearchClient: diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py index 6e952e19..834b82af 100644 --- a/service/src/main/inse/patents/ipc_search_client.py +++ b/service/src/main/inse/patents/ipc_search_client.py @@ -11,7 +11,7 @@ import httpx from .. import config from . import model -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from .ipc_lookup import IpcHierarchyKeys from .ipc_lookup import build_ipc_classification from .ipc_lookup import parse_ipc_symbol diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 3142ac3c..fcf2e446 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -15,7 +15,7 @@ from starlette.status import HTTP_404_NOT_FOUND from ..persons import logic as person_logic from ..models.openalex.author import Author from . import model -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from .elastic_search_client import PatentSearchClient from .elastic_search_all_patents_client import AllPatentsSearchClient from .ipc_search_client import IpcSearchClient diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 0d561b37..81d5dbd5 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -24,7 +24,7 @@ from inse.models.openalex.meta import Meta from inse.models.openalex.topic_count import TopicCount from inse.models.openalex.topics_by_year import TopicsByYear from inse.models.openalex.topics_by_time import TopicsByTime -from .search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from .search_client import OpenAlexWorksSearchClient logger = logging.getLogger(__name__) @@ -122,10 +122,10 @@ async def get_primary_topic_counts( author_id: str, client: OpenAlexWorksSearchClient | None = None, ) -> List[TopicCount]: - topic_counts = _get_primary_topic_counts_from_es(author_id) + topic_counts = await _get_primary_topic_counts_from_es(author_id) topic_ids = [item["id"] for item in topic_counts if item["id"]] - details = _get_topic_details(topic_ids) + details = await _get_topic_details(topic_ids) result = [] diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index d4f0aa40..41e6cb1e 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -11,8 +11,7 @@ import urllib from .. import config from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError logger = logging.getLogger(__name__) diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 1297d848..39dbf091 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -3,7 +3,7 @@ import json import httpx import pytest -from inse.works.search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from inse.works.search_client import OpenAlexWorksSearchClient From 4d855620888f1a9abbd9ab97a2e2a0ff318371c3 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 13:58:29 +0200 Subject: [PATCH 76/81] Implement new global exceptions and replace old exception handlers in each logic file --- .../main/inse/company_connections/logic.py | 40 +++-------------- service/src/main/inse/exceptions.py | 13 ++++++ service/src/main/inse/funders/logic.py | 41 +++++------------ service/src/main/inse/institutions/logic.py | 23 ++++------ .../src/main/inse/institutions/test_logic.py | 6 +-- service/src/main/inse/main.py | 28 +++++++++++- service/src/main/inse/news/logic.py | 17 +++---- service/src/main/inse/patents/logic.py | 27 +++-------- service/src/main/inse/persons/logic.py | 36 +++++---------- service/src/main/inse/topics/logic.py | 45 ++++++------------- service/src/main/inse/topics/test_logic.py | 6 +-- service/src/main/inse/util.py | 5 +-- 12 files changed, 107 insertions(+), 180 deletions(-) diff --git a/service/src/main/inse/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py index ad71847e..fa96a1f4 100644 --- a/service/src/main/inse/company_connections/logic.py +++ b/service/src/main/inse/company_connections/logic.py @@ -1,12 +1,8 @@ import logging from typing import Any -import httpx -from fastapi import HTTPException -from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE - from . import model -from inse.exceptions import MissingApiKeyError, ElasticsearchException +from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException from .search_client import CompanyConnectionsSearchClient logger = logging.getLogger(__name__) @@ -24,22 +20,10 @@ async def get_company_connections_by_author_id( ) -> model.CompanyConnectionsResponse: search_client = client or CompanyConnectionsSearchClient() - try: - author_hit = await search_client.get_openalex_author(author_id) - except MissingApiKeyError as exc: - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Elasticsearch is not configured.", - ) from exc - except ElasticsearchException as exc: - logger.exception("OpenAlex author lookup failed for %s.", author_id) - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex author lookup failed.", - ) from exc + author_hit = await search_client.get_openalex_author(author_id) if author_hit is None: - raise HTTPException(status_code=404, detail=f"Author {author_id} not found.") + raise NotFoundException(f"Author {author_id} not found.") source = author_hit.get("_source", {}) display_name = _clean(source.get("display_name")) @@ -60,21 +44,9 @@ async def get_company_connections_by_author_id( connections=[], ) - try: - hr_response = await search_client.search_handelsregister_by_officer_name( - display_name - ) - except MissingApiKeyError as exc: - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Elasticsearch is not configured.", - ) from exc - except ElasticsearchException as exc: - logger.exception("Handelsregister lookup failed for %s.", display_name) - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Handelsregister lookup failed.", - ) from exc + hr_response = await search_client.search_handelsregister_by_officer_name( + display_name + ) company_count, company_count_relation = _parse_total(hr_response) connections = _parse_company_connections( diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py index f7331b83..c642bca5 100644 --- a/service/src/main/inse/exceptions.py +++ b/service/src/main/inse/exceptions.py @@ -21,3 +21,16 @@ class ElasticsearchConnectionException(ElasticsearchException): class MissingApiKeyError(Exception): """Raised when a required API key is missing.""" pass + + +class UpstreamAPIException(Exception): + """Raised when an upstream third-party service (e.g. REST API) fails.""" + def __init__(self, message: str, status_code: int = 502): + self.message = message + self.status_code = status_code + super().__init__(message) + + +class BadRequestException(Exception): + """Raised when request parameters are invalid or validation fails.""" + pass diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index 098116e9..0551b85f 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -6,16 +6,10 @@ import logging from typing import Any -import httpx -from fastapi import HTTPException -from pydantic import ValidationError -from starlette.status import HTTP_502_BAD_GATEWAY -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE - from ..persons import logic as person_logic from . import model from .elastic_search_client import FundedPublicationsSearchClient -from inse.exceptions import MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException logger = logging.getLogger(__name__) @@ -92,9 +86,9 @@ async def get_funders_by_author_id( ) except ValidationError as exc: logger.exception("Funders response could not be validated for author %s.", author_id) - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Funders response could not be parsed.", + raise UpstreamAPIException( + message="Funders response could not be parsed.", + status_code=502, ) from exc @@ -144,26 +138,13 @@ async def _search_funded_publications( *, funded_only: bool = False, ) -> dict: - try: - payload = search_client.publications_by_author_query( - author_id, - page, - page_size, - funded_only=funded_only, - ) - return await search_client.search(payload) - except MissingApiKeyError as exc: - logger.error("OpenAlex works Elasticsearch API key is not configured.") - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="OpenAlex works search is not configured.", - ) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex works search request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + payload = search_client.publications_by_author_query( + author_id, + page, + page_size, + funded_only=funded_only, + ) + return await search_client.search(payload) def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index 64ae77d0..d001c646 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -9,10 +9,8 @@ from copy import deepcopy from typing import Any, Optional import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_400_BAD_REQUEST -from starlette.status import HTTP_502_BAD_GATEWAY +from inse.exceptions import UpstreamAPIException, BadRequestException from inse.models.openalex.autocomplete_response import AutocompleteResponse from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta @@ -58,10 +56,7 @@ async def list_institutions( client: OpenAlexInstitutionsClient | None = None, ) -> InstitutionsListResponse: if sample is not None and (sort or page not in (None, 1)): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail="sample cannot be combined with sort or page.", - ) + raise BadRequestException("sample cannot be combined with sort or page.") openalex_client = client or OpenAlexInstitutionsClient() @@ -86,12 +81,12 @@ async def list_institutions( except ValueError: if exc.response.text: detail = exc.response.text - raise HTTPException(status_code=status_code, detail=detail) from exc + raise UpstreamAPIException(message=detail, status_code=status_code) from exc except httpx.HTTPError as exc: logger.exception("OpenAlex institutions request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex institutions request failed.", + raise UpstreamAPIException( + message="OpenAlex institutions request failed.", + status_code=502, ) from exc try: @@ -102,9 +97,9 @@ async def list_institutions( ) except ValidationError as exc: logger.exception("OpenAlex institutions response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex institutions response could not be parsed.", + raise UpstreamAPIException( + message="OpenAlex institutions response could not be parsed.", + status_code=502, ) from exc diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index bebf52c0..11544b19 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -1,6 +1,6 @@ import httpx import pytest -from fastapi import HTTPException +from inse.exceptions import BadRequestException from inse.institutions import logic from inse.institutions.search_client import OpenAlexInstitutionsClient @@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model(): @pytest.mark.anyio async def test_list_institutions_rejects_sample_with_sort(): - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(BadRequestException) as exc_info: await logic.list_institutions(sample=10, sort="works_count:desc") - assert exc_info.value.status_code == 400 - @pytest.mark.anyio async def test_list_institutions_accepts_practical_openalex_type_variants(): diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 6c339764..3af016e5 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -14,7 +14,13 @@ from fastapi.responses import JSONResponse, RedirectResponse from inse.collaboration_network.router import router as collaboration_network_router from inse.company_connections.service import router as company_connections_router -from inse.exceptions import NotFoundException, ElasticsearchException +from inse.exceptions import ( + NotFoundException, + ElasticsearchException, + MissingApiKeyError, + UpstreamAPIException, + BadRequestException, +) from inse.funders.service import router as funders_service_router from inse.projects.router import router as projects_router from inse.university_ranking.router import router as university_ranking_router @@ -78,6 +84,8 @@ app.add_middleware( ) +# exception handlers + @app.exception_handler(NotFoundException) async def handle_not_found(request: Request, exc: NotFoundException): return JSONResponse(status_code=404, content={"message": str(exc)}) @@ -89,6 +97,24 @@ async def handle_elasticsearch_error(request: Request, exc: ElasticsearchExcepti return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"}) +@app.exception_handler(MissingApiKeyError) +async def handle_missing_api_key(request: Request, exc: MissingApiKeyError): + logger.error("Configuration error: %s", str(exc)) + return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"}) + + +@app.exception_handler(UpstreamAPIException) +async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException): + logger.error("Upstream API error: %s", str(exc)) + return JSONResponse(status_code=exc.status_code, content={"message": exc.message}) + + +@app.exception_handler(BadRequestException) +async def handle_bad_request(request: Request, exc: BadRequestException): + logger.error("Bad Request: %s", str(exc)) + return JSONResponse(status_code=400, content={"message": str(exc)}) + + @app.exception_handler(404) async def redirect(_, __): return RedirectResponse(url="/inse-webapp/") diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 15532432..77cf31a0 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -8,8 +8,7 @@ import json import logging import re -from fastapi import HTTPException -from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR +from inse.exceptions import ElasticsearchException from ..integrations import elasticsearch, llm from ..persons.logic import find_ude_author_by_name, get_author_name_by_id @@ -234,12 +233,9 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail: source=["date", "maintitle", "author", "url", "full_content"], cluster="inse", ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("Abruf des News-Artikels fehlgeschlagen.") - raise HTTPException( - status_code=HTTP_500_INTERNAL_SERVER_ERROR, - detail="Etwas ist schiefgelaufen.", - ) from exc + raise source = response.get("_source", {}) @@ -435,12 +431,9 @@ async def _run_search(query: dict, source: list, size: int, offset: int, sort, h highlight=highlight, cluster="inse", ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.") - raise HTTPException( - status_code=HTTP_500_INTERNAL_SERVER_ERROR, - detail="Etwas ist schiefgelaufen.", - ) from exc + raise async def _build_page(response: dict, page: int, page_size: int) -> NewsPage: diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index fcf2e446..29679f9e 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -7,15 +7,11 @@ import logging import asyncio import httpx -from fastapi import HTTPException -from starlette.status import HTTP_502_BAD_GATEWAY -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE -from starlette.status import HTTP_404_NOT_FOUND from ..persons import logic as person_logic from ..models.openalex.author import Author from . import model -from inse.exceptions import MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException from .elastic_search_client import PatentSearchClient from .elastic_search_all_patents_client import AllPatentsSearchClient from .ipc_search_client import IpcSearchClient @@ -76,16 +72,9 @@ async def get_patents_by_author_id( patents=[], ) - try: - epo_data, uspto_data = await _search_both_indices( - search_client, last_name, first_name - ) - except MissingApiKeyError as exc: - raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Patent search is not configured.") from exc - except httpx.HTTPError as exc: - raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, - detail="Patent search request failed.") from exc + epo_data, uspto_data = await _search_both_indices( + search_client, last_name, first_name + ) all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) @@ -203,7 +192,7 @@ async def _enrich_patents_classifications( except MissingApiKeyError: logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.") return - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.warning("Classification enrichment failed: %s", exc) return except Exception as exc: @@ -314,12 +303,6 @@ async def get_all_patents( uspto_data.get("hits", {}).get("total", {}).get("value", 0) ) - except MissingApiKeyError as exc: - raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Patent search is not configured.") from exc - except httpx.HTTPError as exc: - raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, - detail="Patent search request failed.") from exc await _enrich_patents_classifications(patents, ipc_search_client) diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 6c82c35e..a7d74fde 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -11,13 +11,12 @@ from datetime import datetime from typing import Optional, Callable, Any, List import hashlib import httpx -from fastapi import HTTPException - from inse.exceptions import ( NotFoundException, ElasticsearchException, ElasticsearchNotFoundException, ElasticsearchConnectionException, + BadRequestException, ) from inse.model import ESIndex @@ -474,7 +473,7 @@ async def search_persons_by_name( include: Optional[str] = None, ) -> AuthorsListResponse: if not author_name: - raise HTTPException(status_code=400, detail="name must be provided") + raise BadRequestException("name must be provided") search_query = { "bool": { "should": [ @@ -506,10 +505,8 @@ async def search_persons_by_name( track_total_hits=True, ) - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + except ElasticsearchException as e: + raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e total_count = response.get("hits", {}).get("total", {}).get("value", 0) hits = response.get("hits", {}).get("hits", []) @@ -524,7 +521,7 @@ async def search_persons_autocomplete( author_name: str, limit: Optional[int] = 5, include: Optional[str] = None ) -> AuthorsListResponse: if not author_name: - raise HTTPException(status_code=400, detail="name must be provided") + raise BadRequestException("name must be provided") search_query = { "function_score": { "query": { @@ -558,10 +555,8 @@ async def search_persons_autocomplete( } try: response = await elasticsearch.search(index="openalex-authors", body=body) - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + except ElasticsearchException as e: + raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e hits = response.get("hits", {}).get("hits", []) @@ -597,7 +592,7 @@ async def search_persons_by_institution( ) -> AuthorsListResponse: if not institution_name: - raise HTTPException(status_code=400, detail="institution_name must be provided") + raise BadRequestException("institution_name must be provided") search_query = { "nested": { @@ -626,10 +621,8 @@ async def search_persons_by_institution( track_total_hits=True, ) - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + except ElasticsearchException as e: + raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e total_count = response.get("hits", {}).get("total", {}).get("value", 0) hits = response.get("hits", {}).get("hits", []) persons = [util.get_persons_data(hit) for hit in hits] @@ -720,14 +713,7 @@ async def advanced_search_persons( ) except ElasticsearchException as e: logger.error(f"Elasticsearch search failed: {str(e)}") - raise HTTPException( - status_code=502, detail="Search service temporarily unavailable" - ) - except Exception as e: - logger.error(f"Elasticsearch search failed: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + raise total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) hits = response_dict.get("hits", {}).get("hits", []) diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index 90540649..1d718ecf 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -8,10 +8,8 @@ from copy import deepcopy from typing import Any import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_400_BAD_REQUEST -from starlette.status import HTTP_502_BAD_GATEWAY +from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException from inse.models.openalex.autocomplete_response import AutocompleteResponse from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta @@ -38,10 +36,7 @@ async def list_topics( client: OpenAlexTopicsClient | None = None, ) -> TopicsListResponse: if sample is not None and (sort or page not in (None, 1)): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail="sample cannot be combined with sort or page.", - ) + raise BadRequestException("sample cannot be combined with sort or page.") openalex_client = client or OpenAlexTopicsClient() @@ -66,12 +61,12 @@ async def list_topics( except ValueError: if exc.response.text: detail = exc.response.text - raise HTTPException(status_code=status_code, detail=detail) from exc + raise UpstreamAPIException(message=detail, status_code=status_code) from exc except httpx.HTTPError as exc: logger.exception("OpenAlex topics request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex topics request failed.", + raise UpstreamAPIException( + message="OpenAlex topics request failed.", + status_code=502, ) from exc try: @@ -79,9 +74,9 @@ async def list_topics( return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() except ValidationError as exc: logger.exception("OpenAlex topics response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex topics response could not be parsed.", + raise UpstreamAPIException( + message="OpenAlex topics response could not be parsed.", + status_code=502, ) from exc @@ -282,10 +277,7 @@ async def vector_search_topics( except Exception as exc: logger.exception("Failed to load elasticsearch integration.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail=f"Failed to load elasticsearch integration: {exc}" - ) + raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc # 1. Vectorize query try: @@ -293,10 +285,7 @@ async def vector_search_topics( query_vector = model.encode(query).tolist() except Exception as exc: logger.exception("Failed to encode query text.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail=f"Failed to encode query text: {exc}" - ) + raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc # 2. Query Elasticsearch using standard Bool Should hybrid search should_clauses = [] @@ -363,11 +352,8 @@ async def vector_search_topics( cluster="nes" ) except Exception as exc: - logger.exception("Elasticsearch vector search failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail=f"Elasticsearch vector search failed: {exc}" - ) + logger.exception("Elasticsearch vector search failed with unexpected error.") + raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc # 3. Format result hits = raw_results.get("hits", {}).get("hits", []) @@ -389,8 +375,5 @@ async def vector_search_topics( return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() except ValidationError as exc: logger.exception("Vector search response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Vector search response could not be parsed.", - ) from exc + raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py index e6f9a3a4..5e88a461 100644 --- a/service/src/main/inse/topics/test_logic.py +++ b/service/src/main/inse/topics/test_logic.py @@ -1,6 +1,6 @@ import httpx import pytest -from fastapi import HTTPException +from inse.exceptions import BadRequestException from inse.topics import logic from inse.topics.search_client import OpenAlexTopicsClient @@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model(): @pytest.mark.anyio async def test_list_topics_rejects_sample_with_sort(): - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(BadRequestException) as exc_info: await logic.list_topics(sample=10, sort="works_count:desc") - assert exc_info.value.status_code == 400 - @pytest.mark.anyio async def test_list_topics_accepts_practical_openalex_type_variants(): diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index dc47d976..5848c92e 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -8,15 +8,14 @@ from typing import Optional from typing import TypeVar from inse.models.openalex import Author from . import model -from fastapi import HTTPException -from starlette.status import HTTP_404_NOT_FOUND +from inse.exceptions import NotFoundException T = TypeVar('T') def raise_not_found_if_none(value: Optional[T]) -> T: ''' Returns the value, if it is set, or raises a 404, if the value is None.''' if value == None: - raise HTTPException(HTTP_404_NOT_FOUND) + raise NotFoundException("Not found.") else: return value From 98777eb620bd778c7dae135aa577016a274d04bf Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 13:59:36 +0200 Subject: [PATCH 77/81] remove elasticsearch package dependencies from uv.lock --- service/uv.lock | 62 ------------------------------------------------- 1 file changed, 62 deletions(-) diff --git a/service/uv.lock b/service/uv.lock index d4016c83..4a7e9873 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -178,36 +178,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" }, ] -[[package]] -name = "elastic-transport" -version = "9.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "sniffio" }, - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" }, -] - -[[package]] -name = "elasticsearch" -version = "9.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "elastic-transport" }, - { name = "python-dateutil" }, - { name = "sniffio" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" }, -] - [[package]] name = "fastapi" version = "0.115.14" @@ -799,18 +769,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" }, ] -[[package]] -name = "python-dateutil" -version = "2.9.0.post0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, -] - [[package]] name = "python-dotenv" version = "1.2.2" @@ -1127,7 +1085,6 @@ source = { virtual = "." } dependencies = [ { name = "cryptography" }, { name = "dotenv" }, - { name = "elasticsearch" }, { name = "fastapi" }, { name = "httpx" }, { name = "openai" }, @@ -1148,7 +1105,6 @@ dependencies = [ requires-dist = [ { name = "cryptography", specifier = "~=42.0.0" }, { name = "dotenv", specifier = ">=0.9.9" }, - { name = "elasticsearch", specifier = "~=9.4.0" }, { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, { name = "openai", specifier = "~=2.41.0" }, @@ -1182,15 +1138,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] -[[package]] -name = "six" -version = "1.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, -] - [[package]] name = "sniffio" version = "1.3.1" @@ -1421,15 +1368,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] -[[package]] -name = "urllib3" -version = "2.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, -] - [[package]] name = "uvicorn" version = "0.29.0" From 84b3ec41487b7ece8f410cc0f9334a00043604a3 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 14:01:30 +0200 Subject: [PATCH 78/81] more async and await additions to elastic wrapper calls --- .../inse/projects/projects_search_client.py | 52 +++++++------- service/src/main/inse/projects/router.py | 31 ++++---- service/src/main/inse/projects/service.py | 52 +++++++------- service/src/main/inse/works/logic.py | 72 ++++++------------- 4 files changed, 90 insertions(+), 117 deletions(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 4cd2812a..bbb09625 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -101,7 +101,7 @@ DFG_PERSON_FIELDS: List[str] = [ # BUND -def search_bund_projects( +async def search_bund_projects( filter_properties: ProjectsFilteringProperties, institution_names: List[str] = [], ) -> BundProjectPage: @@ -160,7 +160,7 @@ def search_bund_projects( } ] - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, query=query, sort=sort, @@ -194,7 +194,7 @@ def _complete_response_to_bund_project_page( return BundProjectPage(elements=elements, total=total_hits, page=page, size=size) -def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: +async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: """Decodes project_id and fetches the details of a single Bund project based on its project ID. Args: @@ -207,7 +207,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: decoded_id = urllib.parse.unquote(project_id) query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}} - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, query=query, size=1, @@ -224,7 +224,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: # EU -def get_eu_organization_project_contributions( +async def get_eu_organization_project_contributions( organization_names: List[str], projects_filtering_properties: ProjectsFilteringProperties, ) -> EuOrganizationProjectSummaryPage: @@ -241,11 +241,11 @@ def get_eu_organization_project_contributions( # For FUNDING_AMOUNT before on the organization project contributions # For the rest after the contributions are known on the real projects - organization_project_contributions = get_eu_organization_contributions( + organization_project_contributions = await get_eu_organization_contributions( organization_names=organization_names, ) - total_projects, projects = get_eu_organization_projects( + total_projects, projects = await get_eu_organization_projects( project_contributions=list(organization_project_contributions.values()), projects_filtering_properties=projects_filtering_properties, ) @@ -271,7 +271,7 @@ def get_eu_organization_project_contributions( ) -def get_eu_organization_contributions( +async def get_eu_organization_contributions( organization_names: List[str], ) -> Dict[str, EuOrganizationShort]: """Fetches the contributions of EU organizations to projects based on the provided organization names. @@ -293,7 +293,7 @@ def get_eu_organization_contributions( } } - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, cluster=ESCluster.INSE, source=source, @@ -343,7 +343,7 @@ def _process_organization_project_contributions( return project_contributions -def get_eu_organization_projects( +async def get_eu_organization_projects( project_contributions: List[EuOrganizationShort], projects_filtering_properties: ProjectsFilteringProperties, ) -> Tuple[int, Dict[str, EuProjectShort]]: @@ -388,7 +388,7 @@ def get_eu_organization_projects( # Project contributions have been filtered before based on ecContribution if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, source=source, @@ -396,7 +396,7 @@ def get_eu_organization_projects( size=10000, ) else: - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, source=source, @@ -496,7 +496,7 @@ def _get_raw_doi(doi: str) -> str: return doi -def get_cordis_eu_publications_by_dois(dois: List[str]): +async def get_cordis_eu_publications_by_dois(dois: List[str]): """Retrieves Cordis EU publications associated with the given list of DOIs. Args: @@ -508,7 +508,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]): raw_dois = [_get_raw_doi(doi) for doi in dois] query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, cluster=ESCluster.INSE, @@ -519,7 +519,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]): return response -def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: +async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. Args: @@ -528,7 +528,7 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: Returns: List[str]: The list of project IDs. """ - response = get_cordis_eu_publications_by_dois(dois=dois) + response = await get_cordis_eu_publications_by_dois(dois=dois) hits_block = response.get("hits", {}) project_ids = set() for hit in hits_block.get("hits", []): @@ -539,12 +539,12 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: return list(project_ids) -def get_cordis_eu_projects_by_project_ids( +async def get_cordis_eu_projects_by_project_ids( project_ids: List[str], ) -> CordisEuProjectPage: query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, @@ -561,7 +561,7 @@ def get_cordis_eu_projects_by_project_ids( ) -def get_eu_cordis_projects_by_id( +async def get_eu_cordis_projects_by_id( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: """ @@ -573,14 +573,14 @@ def get_eu_cordis_projects_by_id( Returns: The enriched project details, or None if not found """ - enriched_project = get_enriched_cordis_project_by_id( + enriched_project = await get_enriched_cordis_project_by_id( project_id=project_id ) return enriched_project # DFG -def search_dfg_projects( +async def search_dfg_projects( page: int, size: int, names: Optional[List[str]] = None, @@ -750,7 +750,7 @@ def search_dfg_projects( body["sort"] = [sort_config] - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_DFG_ALL, body=body, ) @@ -776,7 +776,7 @@ def _complete_response_to_dfg_project_page( return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) -def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: +async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: """Fetches the details of a single DFG project based on its project ID. Args: @@ -787,7 +787,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: """ query = {"ids": {"values": [project_id]}} - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_DFG_ALL, query=query, size=1, @@ -804,7 +804,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: # All -def search_all_projects( +async def search_all_projects( projects_filtering_properties: ProjectsFilteringProperties, selected_project_types: Optional[Set[ProjectType]] = None, ) -> FundingProjectPage: @@ -882,7 +882,7 @@ def search_all_projects( size = projects_filtering_properties.size page = projects_filtering_properties.page offset = page * size - response = elasticsearch.search( + response = await elasticsearch.search( index=index, size=size, offset=offset, diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 32f206e4..fcd91844 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -51,13 +51,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS]) }, response_model_by_alias=False, ) -def get_eu_projects_for_author( +async def get_eu_projects_for_author( raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")], ) -> CordisEuProjectPage: logger.debug( f"Received request to get EU projects for author_id={raw_oa_author_id}" ) - return projects_service.search_cordis_eu_projects_for_author_id( + return await projects_service.search_cordis_eu_projects_for_author_id( raw_oa_author_id=raw_oa_author_id, ) @@ -85,7 +85,7 @@ async def search_bund_projects( Body(description="The filtering properties for the projects search."), ], ) -> BundProjectPage: - return projects_service.search_bund_projects( + return await projects_service.search_bund_projects( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) @@ -105,11 +105,11 @@ async def search_bund_projects( }, response_model_by_alias=False, ) -def get_single_dfg_project( +async def get_single_dfg_project( id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")], ) -> DfgProjectDetails: logger.debug(f"Received request to get single DFG project for id={id}") - return projects_service.get_single_dfg_project( + return await projects_service.get_single_dfg_project( project_id=id, ) @@ -128,11 +128,11 @@ def get_single_dfg_project( }, response_model_by_alias=False, ) -def get_single_bund_project( +async def get_single_bund_project( id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")], ) -> BundProjectDetails: logger.debug(f"Received request to get single BUND project for id={id}") - return projects_service.get_single_bund_project( + return await projects_service.get_single_bund_project( project_id=id, ) @@ -157,9 +157,7 @@ def get_single_bund_project( } }, ) - - -def get_single_eu_cordis_project( +async def get_single_eu_cordis_project( id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")], ) -> EuCordisProjectResponse: """ @@ -170,7 +168,7 @@ def get_single_eu_cordis_project( try: # Get the project from the service - project = projects_service.get_single_eu_cordis_project(project_id=id) + project = await projects_service.get_single_eu_cordis_project(project_id=id) # Check if project exists if project is None: @@ -216,6 +214,7 @@ def get_single_eu_cordis_project( error=f"Internal server error: {str(e)}" ) + @router.get( "/institution/bund/funding-over-time", summary="Get funding over time for bund projects.", @@ -230,7 +229,7 @@ def get_single_eu_cordis_project( }, response_model_by_alias=False, ) -def get_institution_bund_projects_funding_over_time( +async def get_institution_bund_projects_funding_over_time( institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -238,7 +237,7 @@ def get_institution_bund_projects_funding_over_time( str, Query(description="The institution ID to filter by.") ], ) -> InstitutionFunderSummary: - return projects_service.get_institution_bund_projects_funding_over_time( + return await projects_service.get_institution_bund_projects_funding_over_time( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, ) @@ -267,7 +266,7 @@ async def search_cordis_eu_projects( Body(description="The filtering properties for the projects search."), ], ) -> EuOrganizationProjectSummaryPage: - return projects_service.search_cordis_eu_projects( + return await projects_service.search_cordis_eu_projects( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) @@ -359,7 +358,7 @@ async def get_dfg_projects( }, response_model_by_alias=False, ) -def search_projects( +async def search_projects( page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 10, selected_project_types: Annotated[ @@ -378,7 +377,7 @@ def search_projects( SortDirection, Query(description="The sort direction (asc or desc).") ] = SortDirection.ASC, ) -> FundingProjectPage: - return projects_service.search_all_projects( + return await projects_service.search_all_projects( page=page, size=size, selected_project_types=selected_project_types, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 955d8289..e8d83281 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -35,7 +35,7 @@ from typing import Union logger = logging.getLogger(__name__) -def search_all_projects( +async def search_all_projects( page: int, size: int, sort_by: ProjectsSortBy, @@ -43,7 +43,7 @@ def search_all_projects( selected_project_types: Optional[Set[ProjectType]] = None, title: Optional[str] = None, ) -> FundingProjectPage: - return projects_search_client.search_all_projects( + return await projects_search_client.search_all_projects( projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects page=page, @@ -56,7 +56,7 @@ def search_all_projects( ) -def search_bund_projects( +async def search_bund_projects( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -69,13 +69,13 @@ def search_bund_projects( f"search_bund_projects called with filtering_properties: {filtering_properties}" ) - return get_bund_projects_by_institution_id( + return await get_bund_projects_by_institution_id( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) -def get_bund_projects_by_institution_id( +async def get_bund_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -93,7 +93,7 @@ def get_bund_projects_by_institution_id( logger.debug( f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - response = projects_search_client.search_bund_projects( + response = await projects_search_client.search_bund_projects( institution_names=institution_aliases, filter_properties=filtering_properties, ) @@ -101,7 +101,7 @@ def get_bund_projects_by_institution_id( return response -def search_cordis_eu_projects( +async def search_cordis_eu_projects( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, ) -> EuOrganizationProjectSummaryPage: @@ -110,13 +110,13 @@ def search_cordis_eu_projects( f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'." ) - return get_cordis_eu_projects_by_institution_id( + return await get_cordis_eu_projects_by_institution_id( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) -def get_cordis_eu_projects_by_institution_id( +async def get_cordis_eu_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, ) -> EuOrganizationProjectSummaryPage: @@ -137,7 +137,7 @@ def get_cordis_eu_projects_by_institution_id( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - page = get_eu_organization_project_contributions( + page = await get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=projects_filtering_properties, ) @@ -158,7 +158,7 @@ async def get_dfg_projects_by_author_id( logger.debug( f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}" ) - name = get_author_name_by_id(author_id) + name = await get_author_name_by_id(author_id) if not name: logger.debug(f"No author name found for author_id={author_id}") raise NotFoundException( @@ -166,7 +166,7 @@ async def get_dfg_projects_by_author_id( ) logger.debug(f"Found author name for author_id={author_id}: {name}") - response = projects_search_client.search_dfg_projects( + response = await projects_search_client.search_dfg_projects( page=page, size=size, names=[name], @@ -186,7 +186,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id ) ) - page = get_eu_organization_project_contributions( + page = await get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, @@ -204,7 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -def get_institution_bund_projects_funding_over_time( +async def get_institution_bund_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, ) -> InstitutionFunderSummary: @@ -219,7 +219,7 @@ def get_institution_bund_projects_funding_over_time( logger.debug( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) - response = projects_search_client.search_bund_projects( + response = await projects_search_client.search_bund_projects( filter_properties=ProjectsFilteringProperties( project_type=ProjectType.BUND, page=0, @@ -305,38 +305,40 @@ def _calculate_funding_over_time( ) -def get_single_dfg_project( +async def get_single_dfg_project( project_id: str, ) -> DfgProjectDetails: logger.debug(f"Fetching single DFG project for id={project_id}") - project = projects_search_client.get_dfg_project_by_id(project_id) + project = await projects_search_client.get_dfg_project_by_id(project_id) if not project: raise NotFoundException(f"DFG project with id {project_id} not found") return project -def get_single_bund_project( +async def get_single_bund_project( project_id: str, ) -> BundProjectDetails: logger.debug(f"Fetching single BUND project for id={project_id}") - project = projects_search_client.get_bund_project_by_id(project_id) + project = await projects_search_client.get_bund_project_by_id(project_id) if not project: raise NotFoundException(f"BUND project with id {project_id} not found") return project -def get_single_eu_cordis_project( + +async def get_single_eu_cordis_project( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: logger.debug(f"Fetching single EU Cordis project for id={project_id}") - project = projects_search_client.get_eu_cordis_projects_by_id(project_id) + project = await projects_search_client.get_eu_cordis_projects_by_id(project_id) if not project: raise NotFoundException(f"EU project with id {project_id} not found") return project -def search_cordis_eu_projects_for_author_id( + +async def search_cordis_eu_projects_for_author_id( raw_oa_author_id: str, ) -> CordisEuProjectPage: @@ -345,17 +347,17 @@ def search_cordis_eu_projects_for_author_id( # 2. CORDIS EU projects have associated publications with DOIs # 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author - dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id) + dois = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id) logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}") - project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) + project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) logger.debug( f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}" ) - funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids( + funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids( project_ids=project_ids ) diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 81d5dbd5..2ffb73e4 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -9,11 +9,8 @@ from time import time from typing import Any, List import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_404_NOT_FOUND -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse import config from inse.integrations import elasticsearch @@ -24,7 +21,7 @@ from inse.models.openalex.meta import Meta from inse.models.openalex.topic_count import TopicCount from inse.models.openalex.topics_by_year import TopicsByYear from inse.models.openalex.topics_by_time import TopicsByTime -from inse.exceptions import MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException from .search_client import OpenAlexWorksSearchClient logger = logging.getLogger(__name__) @@ -178,12 +175,9 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: index=config.settings.openalex_works_search_index, body=body, ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex primary topic aggregation request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + raise aggregations = response.get("aggregations", {}) buckets = aggregations.get("primary_topics", {}).get("buckets", []) @@ -646,12 +640,9 @@ async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dic index=config.settings.openalex_works_search_index, body=body, ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex publication year aggregation request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + raise return _parse_year_count_buckets(response), _parse_total_hits(response) @@ -717,12 +708,9 @@ async def _get_timeline_topic_counts_from_es( index=config.settings.openalex_works_search_index, body=body, ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex timeline topic aggregation request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + raise return response.get("aggregations", {}).get("by_year", {}).get("buckets", []) @@ -883,29 +871,16 @@ async def _search_author_works_data( institution_id: list[str] | None = None, topic_id: list[str] | None = None, ) -> dict: - try: - return await search_client.search_author_works( - author_id, - page, - size, - publication_year=publication_year, - work_type=work_type, - language=language, - institution_id=institution_id, - topic_id=topic_id, - ) - except MissingApiKeyError as exc: - logger.error("OpenAlex works Elasticsearch API key is not configured.") - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="OpenAlex works search is not configured.", - ) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex works search request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + return await search_client.search_author_works( + author_id, + page, + size, + publication_year=publication_year, + work_type=work_type, + language=language, + institution_id=institution_id, + topic_id=topic_id, + ) def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: @@ -946,9 +921,9 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: elements.append(work) except ValidationError as exc: logger.exception("OpenAlex works search response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search response could not be parsed.", + raise UpstreamAPIException( + message="OpenAlex works search response could not be parsed.", + status_code=502, ) from exc return elements, total @@ -983,12 +958,9 @@ async def get_publication_dois_of_author( query=query, cluster="nes", ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("Request for publication DOIs of author failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Request for publication DOIs of author failed.", - ) from exc + raise dois = [] for hit in response.get("hits", {}).get("hits", []): From e206f408227a2e5fb6a8171235f21a4e9751c819 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 14:13:58 +0200 Subject: [PATCH 79/81] small changes to test and Artifact removal --- service/src/main/inse/funders/logic.py | 1 + service/src/main/inse/funders/test_logic.py | 6 +-- service/src/main/inse/patents/logic.py | 55 ++++++++++----------- 3 files changed, 30 insertions(+), 32 deletions(-) diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index 0551b85f..bad9e46e 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -6,6 +6,7 @@ import logging from typing import Any +from pydantic import ValidationError from ..persons import logic as person_logic from . import model from .elastic_search_client import FundedPublicationsSearchClient diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py index 9c95dbd4..52ff0fdb 100644 --- a/service/src/main/inse/funders/test_logic.py +++ b/service/src/main/inse/funders/test_logic.py @@ -1,6 +1,6 @@ import pytest from unittest.mock import AsyncMock, patch -from fastapi import HTTPException +from inse.exceptions import MissingApiKeyError from inse.funders import logic from inse.funders.elastic_search_client import FundedPublicationsSearchClient @@ -340,7 +340,5 @@ async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavaila client = FundedPublicationsSearchClient(api_key="") - with pytest.raises(HTTPException) as exc: + with pytest.raises(MissingApiKeyError): await logic.get_funders_by_author_id("A5023888391", client=client) - - assert exc.value.status_code == 503 diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index 29679f9e..9ff5b490 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -272,36 +272,35 @@ async def get_all_patents( all_patents_client = AllPatentsSearchClient() ipc_search_client = ipc_client or IpcSearchClient() - try: - if source == "EPO": - epo_data = await all_patents_client.search_epo( - all_patents_client.epo_query(page, size, search, sort_direction) - ) - patents = _parse_epo_hits(epo_data) - total = epo_data.get("hits", {}).get("total", {}).get("value", 0) + if source == "EPO": + epo_data = await all_patents_client.search_epo( + all_patents_client.epo_query(page, size, search, sort_direction) + ) + patents = _parse_epo_hits(epo_data) + total = epo_data.get("hits", {}).get("total", {}).get("value", 0) - elif source == "USPTO": - uspto_data = await all_patents_client.search_uspto( - all_patents_client.uspto_query(page, size, search, sort_direction) - ) - patents = _parse_uspto_hits(uspto_data) - total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) + elif source == "USPTO": + uspto_data = await all_patents_client.search_uspto( + all_patents_client.uspto_query(page, size, search, sort_direction) + ) + patents = _parse_uspto_hits(uspto_data) + total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) - else: - half = size // 2 - epo_data, uspto_data = await asyncio.gather( - all_patents_client.search_epo( - all_patents_client.epo_query(page, half, search, sort_direction) - ), - all_patents_client.search_uspto( - all_patents_client.uspto_query(page, half, search, sort_direction) - ), - ) - patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) - total = ( - epo_data.get("hits", {}).get("total", {}).get("value", 0) + - uspto_data.get("hits", {}).get("total", {}).get("value", 0) - ) + else: + half = size // 2 + epo_data, uspto_data = await asyncio.gather( + all_patents_client.search_epo( + all_patents_client.epo_query(page, half, search, sort_direction) + ), + all_patents_client.search_uspto( + all_patents_client.uspto_query(page, half, search, sort_direction) + ), + ) + patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) + total = ( + epo_data.get("hits", {}).get("total", {}).get("value", 0) + + uspto_data.get("hits", {}).get("total", {}).get("value", 0) + ) await _enrich_patents_classifications(patents, ipc_search_client) From 415ee391982c29b59a147f68524f0a0a8f19ed3b Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 14:35:57 +0200 Subject: [PATCH 80/81] Added resolver for EU projects. Changed thread pooling to async calls --- .../eu_cordis_projects_enrichment_client.py | 53 +++++++++---------- webapp/src/app/app.routes.ts | 5 +- 2 files changed, 30 insertions(+), 28 deletions(-) diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py index 5caff70e..cb120418 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py @@ -1,5 +1,5 @@ import logging -from concurrent.futures import ThreadPoolExecutor, as_completed +import asyncio from typing import Any, Dict, List, Optional, Union from inse.config import get_settings @@ -85,7 +85,7 @@ _HEU_ENTITY_CONFIGS = [ {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, ] -def get_enriched_cordis_project_by_id( +async def get_enriched_cordis_project_by_id( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: """ @@ -102,7 +102,7 @@ def get_enriched_cordis_project_by_id( query = {"bool": {"filter": [{"term": {"id": project_id}}]}} - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, @@ -131,7 +131,7 @@ def get_enriched_cordis_project_by_id( logger.warning(f"Unknown programme type for index: {index}") return CordisEuProject.model_validate(source) - return enricher(project_id, source) + return await enricher(project_id, source) # helpers def _determine_program_type_from_index(index: str) -> str: @@ -146,10 +146,9 @@ def _determine_program_type_from_index(index: str) -> str: return "unknown" -def _fetch_related_entities_parallel( +async def _fetch_related_entities_parallel( project_id: str, entity_configs: List[Dict[str, Any]], - max_workers: int = 8, ) -> Dict[str, List[Any]]: """ Fetches all related entity types for a project in parallel. @@ -157,35 +156,35 @@ def _fetch_related_entities_parallel( Args: project_id: The project ID to fetch entities for. entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. - max_workers: Maximum number of concurrent Elasticsearch requests. Returns: Dictionary mapping each config 'key' to a list of validated entities. """ - def _fetch_one(config: Dict[str, Any]): - entities = _fetch_related_entities( + async def _fetch_one(config: Dict[str, Any]): + entities = await _fetch_related_entities( project_ids=[project_id], index_pattern=config["index_pattern"], model_class=config["model_class"], ) return config["key"], entities.get(project_id, []) + tasks = [_fetch_one(cfg) for cfg in entity_configs] + completed = await asyncio.gather(*tasks, return_exceptions=True) + results: Dict[str, List[Any]] = {} - with ThreadPoolExecutor(max_workers=max_workers) as executor: - futures = {executor.submit(_fetch_one, cfg): cfg["key"] for cfg in entity_configs} - for future in as_completed(futures): - try: - key, data = future.result() - results[key] = data - except Exception as e: - key = futures[future] - logger.error(f"Parallel fetch failed for '{key}': {e}") - results[key] = [] + for cfg, res in zip(entity_configs, completed): + key = cfg["key"] + if isinstance(res, Exception): + logger.error(f"Parallel fetch failed for '{key}': {res}") + results[key] = [] + else: + key_name, data = res + results[key_name] = data return results -def _fetch_related_entities( +async def _fetch_related_entities( project_ids: List[str], index_pattern: str, model_class: Any, @@ -204,7 +203,7 @@ def _fetch_related_entities( query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} try: - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=index_pattern, cluster=ESCluster.INSE, @@ -234,7 +233,7 @@ def _fetch_related_entities( return grouped -def _enrich_fp7_project( +async def _enrich_fp7_project( project_id: str, project_source: Dict[str, Any], ) -> Optional[Fp7ProjectDetails]: @@ -245,12 +244,12 @@ def _enrich_fp7_project( logger.error(f"Failed to validate FP7 project {project_id}: {e}") return None - related = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) + related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) return Fp7ProjectDetails.from_project_with_relations(project=project, **related) -def _enrich_h2020_project( +async def _enrich_h2020_project( project_id: str, project_source: Dict[str, Any], ) -> Optional[H2020ProjectDetails]: @@ -261,12 +260,12 @@ def _enrich_h2020_project( logger.error(f"Failed to validate H2020 project {project_id}: {e}") return None - related = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) + related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) return H2020ProjectDetails.from_project_with_relations(project=project, **related) -def _enrich_heu_project( +async def _enrich_heu_project( project_id: str, project_source: Dict[str, Any], ) -> Optional[HEUProjectDetails]: @@ -277,6 +276,6 @@ def _enrich_heu_project( logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") return None - related = _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) + related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) return HEUProjectDetails.from_project_with_relations(project=project, **related) \ No newline at end of file diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 27cbb63a..db7e24ac 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -163,7 +163,10 @@ export const routes: Routes = [ import('./modules/person-projects/person-projects.component').then( (mod) => mod.PersonProjectsComponent, ), - resolve: { dfgProjectPage: dfgProjectsResolver }, + resolve: { + dfgProjectPage: dfgProjectsResolver, + personCordisEuProjectPage: personCordisEuProjectPageResolver, + }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; return keys.some( From 7b2834a177eb5d56cc05c1cb3ca58ee99f576603 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 29 Jun 2026 17:23:49 +0200 Subject: [PATCH 81/81] fixed wrong cluster call --- service/src/main/inse/company_connections/search_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/company_connections/search_client.py b/service/src/main/inse/company_connections/search_client.py index 6f041c50..b4fe2d1e 100644 --- a/service/src/main/inse/company_connections/search_client.py +++ b/service/src/main/inse/company_connections/search_client.py @@ -67,7 +67,7 @@ class CompanyConnectionsSearchClient: return await elasticsearch.search( index=self.handelsregister_index, body=payload, - cluster=ESCluster.INSE, + cluster=ESCluster.NES, ) @staticmethod