fix(patents): restore patent detail API and align frontend service types
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good

Re-add getPatentByIdOrTitle endpoint and OrgPatentMatchTypeFilter export
lost during dev merge; update institution-patents to use options-based API.
This commit is contained in:
2026-07-06 13:57:47 +02:00
parent eb89076070
commit de4ba0591e
6 changed files with 152 additions and 10 deletions
+105
View File
@@ -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]
@@ -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,
)
+17 -2
View File
@@ -368,12 +368,26 @@ export class PatentsService extends BaseService {
}
public getPatentById(patentId: string): Observable<PatentEntry> {
return this.getPatentByIdOrTitle(patentId);
}
public getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
fillingDate?: string,
): Observable<PatentEntry> {
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<PatentEntry>(`${basePath}${localVarPath}`, {
params,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
});
@@ -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;
@@ -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 ?? [];
@@ -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: () => {