diff --git a/service/src/main/inse/patents/all/logic.py b/service/src/main/inse/patents/all/logic.py index f18b6a8d..4c308c95 100644 --- a/service/src/main/inse/patents/all/logic.py +++ b/service/src/main/inse/patents/all/logic.py @@ -1,6 +1,7 @@ """Business logic for global patent listing.""" import asyncio from datetime import datetime + import httpx from fastapi import HTTPException from starlette.status import HTTP_404_NOT_FOUND @@ -83,3 +84,107 @@ async def get_all_patents( size=size, patents=patents, ) + + +def _normalize_patent_date(date_str: str) -> str: + return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d") + + +def _parse_patent_id(patent_id: str) -> tuple[str, str]: + normalized = patent_id.strip().upper() + if normalized.startswith("EP"): + return "EPO", normalized.removeprefix("EP") + if normalized.startswith("US"): + return "USPTO", normalized.removeprefix("US") + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Patent not found.", + ) + + +async def _search_by_id( + client: AllPatentsSearchClient, + patent_id: str, + filling_date: str | None = None, +) -> list[model.PatentEntry]: + try: + source, number = _parse_patent_id(patent_id) + except HTTPException: + return [] + + if source == "EPO": + data = await client.search_epo(client.epo_detail_query(number, filling_date)) + return parse_epo_hits(data) + data = await client.search_uspto(client.uspto_detail_query(number, filling_date)) + return parse_uspto_hits(data) + + +async def _search_by_title( + client: AllPatentsSearchClient, + title: str, + filling_date: str | None = None, + prefix: str | None = None, +) -> list[model.PatentEntry]: + if prefix and prefix.upper() == "US": + data = await client.search_uspto(client.uspto_title_query(title, filling_date)) + return parse_uspto_hits(data) + if prefix and prefix.upper() == "EP": + data = await client.search_epo(client.epo_title_query(title, filling_date)) + return parse_epo_hits(data) + + epo_data, uspto_data = await asyncio.gather( + client.search_epo(client.epo_title_query(title, filling_date)), + client.search_uspto(client.uspto_title_query(title, filling_date)), + ) + return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + + +async def get_patent_by_id( + patent_id: str, + prefix: str | None = None, + title: str | None = None, + filling_date: str | None = None, + ipc_client: IpcSearchClient | None = None, +) -> model.PatentEntry: + all_patents_client = AllPatentsSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() + normalized_filling_date = ( + _normalize_patent_date(filling_date) if filling_date else None + ) + + lookup_id = patent_id + if prefix and not patent_id.upper().startswith(prefix.upper()): + lookup_id = f"{prefix.upper()}{patent_id}" + + try: + patents = await _search_by_id( + all_patents_client, lookup_id, normalized_filling_date + ) + + if not patents and title: + patents = await _search_by_title( + all_patents_client, + title, + normalized_filling_date, + prefix, + ) + + if not patents: + raise HTTPException( + status_code=HTTP_404_NOT_FOUND, + detail="Patent not found.", + ) + + 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[:1], ipc_search_client) + return patents[0] diff --git a/service/src/main/inse/patents/all/service.py b/service/src/main/inse/patents/all/service.py index a620c93c..2126fc29 100644 --- a/service/src/main/inse/patents/all/service.py +++ b/service/src/main/inse/patents/all/service.py @@ -33,3 +33,23 @@ async def get_all_patents( year_from=year_from, year_to=year_to, ) + + +@router.get( + "/patents/{identifier}", + operation_id="getPatentByIdOrTitle", + response_model=model.PatentEntry, + summary="Get a single patent by identifier with optional title fallback.", +) +async def get_patent_by_identifier( + identifier: str, + prefix: str | None = None, + title: str | None = None, + filling_date: str | None = None, +): + return await logic.get_patent_by_id( + patent_id=identifier, + prefix=prefix, + title=title, + filling_date=filling_date, + ) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 3ad51a73..14d602a1 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -368,12 +368,26 @@ export class PatentsService extends BaseService { } public getPatentById(patentId: string): Observable { + return this.getPatentByIdOrTitle(patentId); + } + + public getPatentByIdOrTitle( + identifier: string, + prefix?: string, + title?: string, + fillingDate?: string, + ): Observable { + let params = new HttpParams(); + if (prefix) params = params.set('prefix', prefix); + if (title) params = params.set('title', title); + if (fillingDate) params = params.set('filling_date', fillingDate); + const localVarHeaders = this.defaultHeaders; const { basePath, withCredentials } = this.configuration; const localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam( { - name: 'patentId', - value: patentId, + name: 'identifier', + value: identifier, in: 'path', style: 'simple', explode: false, @@ -383,6 +397,7 @@ export class PatentsService extends BaseService { )}`; return this.httpClient.get(`${basePath}${localVarPath}`, { + params, ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, }); diff --git a/webapp/src/app/api/model/orgPatentsResponse.ts b/webapp/src/app/api/model/orgPatentsResponse.ts index 68b2be7a..1d085b3e 100644 --- a/webapp/src/app/api/model/orgPatentsResponse.ts +++ b/webapp/src/app/api/model/orgPatentsResponse.ts @@ -9,6 +9,8 @@ */ import { OrgPatentEntry } from './orgPatentEntry'; +export type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; + export interface OrgPatentsResponse { institution_id: string; institution_name?: string | null; diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 2c807d97..2ff0c77c 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -130,13 +130,13 @@ export class InstitutionPatentsComponent implements OnInit { this.error = false; this.patentsApi - .getOrgPatentsByInstitution( - institutionId, - this.activeMatchType, - this.selectedPage - 1, - this.pageSize, - this.activeFilter !== 'all' ? this.activeFilter : undefined, - ) + .getOrgPatentsByInstitution(institutionId, 'body', false, { + matchType: + this.activeMatchType !== 'all' ? this.activeMatchType : undefined, + page: this.selectedPage - 1, + size: this.pageSize, + source: this.activeFilter !== 'all' ? this.activeFilter : undefined, + }) .subscribe({ next: (result) => { this.patents = result.patents ?? []; diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.ts b/webapp/src/app/modules/patent-detail/patent-detail.component.ts index 5052d8db..0394cc26 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.component.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.ts @@ -128,7 +128,7 @@ export class PatentDetailComponent implements OnInit { .getPatentByIdOrTitle(patentId, prefix, title, fillingDate) .pipe(finalize(() => (this.loading = false))) .subscribe({ - next: (patent) => { + next: (patent: PatentEntry) => { this.patent = patent; }, error: () => {