ts-136-patent-to-researchers-v2 #167

Merged
khalti merged 14 commits from ts-136-patent-to-researchers-v2 into dev 2026-06-25 21:16:48 +02:00
22 changed files with 3548 additions and 1139 deletions
+2
View File
@@ -34,6 +34,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__)
@@ -61,6 +62,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,
@@ -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()
@@ -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()
+221
View File
@@ -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<section>[A-HY])"
r"(?P<class_num>\d{2})"
r"(?P<subclass_letter>[A-Z])"
r"\s*"
r"(?:(?P<main_group>\d+))?"
r"(?:/(?P<subgroup>\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<section>[A-HY])\s+"
r"(?P<class_num>\d{2})\s*"
r"(?P<subclass_letter>[A-Z])\s+"
r"(?P<main_group>\d+)"
r"(?:/(?P<subgroup>\d+))?"
r"(?:\s+(?P<classification_value>[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,
)
@@ -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()
+308 -156
View File
@@ -1,156 +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 .name_matching import name_matches
logger = logging.getLogger(__name__)
async def get_patents_by_author_id(
author_id: str,
client: PatentSearchClient | None = None,
) -> model.PatentsByAuthorResponse:
search_client = client or PatentSearchClient()
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)
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 []
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,
inventors=inventors if isinstance(inventors, list) else [inventors],
assignees=applicants if isinstance(applicants, list) else [applicants],
ipc=ipc if isinstance(ipc, list) else [ipc],
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 []
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,
inventors=inventors if isinstance(inventors, list) else [inventors],
assignees=assignees if isinstance(assignees, list) else [assignees],
ipc=ipc if isinstance(ipc, list) else [ipc],
country=src.get("country", "US"),
))
return patents
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 _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
#!/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,
)
+28 -1
View File
@@ -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):
@@ -8,13 +19,29 @@ 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)
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
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]
+27 -4
View File
@@ -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,
)
@@ -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")
@@ -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"
@@ -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
@@ -0,0 +1,91 @@
from inse.patents import logic, model
def _uspto_patent(
patent_id: str = "US12508845",
publication_date: str = "20251230",
application_type: str | None = None,
) -> model.PatentEntry:
return model.PatentEntry(
patent_id=patent_id,
source="USPTO",
title="Vehicle pneumatic tyre and rubber mixture for a tread",
publication_date=publication_date,
publication_year="2025",
application_type=application_type,
)
def _epo_patent(
patent_id: str = "EP2867692",
publication_date: str = "20180411",
kind: str | None = None,
) -> model.PatentEntry:
return model.PatentEntry(
patent_id=patent_id,
source="EPO",
title="METHOD FOR GENERATING AND USING A MAP",
publication_date=publication_date,
publication_year="2018",
kind=kind,
)
def test_deduplicate_patents_removes_exact_duplicates() -> None:
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
result = logic._deduplicate_patents(patents)
assert len(result) == 1
assert result[0].patent_id == "US12508845"
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
result = logic._deduplicate_patents(patents)
assert len(result) == 2
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None:
first = _uspto_patent()
first.abstract = "First abstract"
duplicate = _uspto_patent()
duplicate.abstract = "Second abstract"
result = logic._deduplicate_patents([first, duplicate])
assert len(result) == 1
assert result[0].abstract == "First abstract"
def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
application = _epo_patent(publication_date="20161005", kind="A1")
grant = _epo_patent(publication_date="20180411", kind="B1")
result = logic._deduplicate_patents([application, grant])
assert len(result) == 2
assert [patent.kind for patent in result] == ["A1", "B1"]
def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() -> None:
earlier = _uspto_patent(publication_date="20241230")
later = _uspto_patent(publication_date="20251230")
result = logic._deduplicate_patents([earlier, later])
assert len(result) == 2
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types() -> None:
utility = _uspto_patent(application_type="utility")
reissue = _uspto_patent(application_type="reissue")
result = logic._deduplicate_patents([utility, reissue])
assert len(result) == 2
assert [patent.application_type for patent in result] == ["utility", "reissue"]
+166 -148
View File
@@ -1,148 +1,166 @@
/**
* 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 { 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);
}
/**
* 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<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
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<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
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',
})
export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
public getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetPatentsByAuthorOptions,
): Observable<any> {
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<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
public getAllPatents(
page: number = 0,
size: number = 10,
search?: string,
source?: string,
sortBy: string = 'date',
sortDirection: string = 'desc',
): Observable<AllPatentsResponse> {
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<AllPatentsResponse>(
`${basePath}/api/inse-service/patents`,
{
params,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
},
);
}
}
+25 -17
View File
@@ -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<string>;
assignees?: Array<string>;
ipc?: Array<string>;
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;
}
+30 -150
View File
@@ -7,7 +7,6 @@ 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';
@@ -15,7 +14,6 @@ import { bundSingleProjectResolver } from './resolvers/bund-single-project-resol
import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver';
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';
export const routes: Routes = [
{
@@ -57,47 +55,20 @@ 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;
},
},
{
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],
@@ -114,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',
@@ -126,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',
@@ -143,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: () =>
@@ -161,13 +124,9 @@ export const routes: Routes = [
import('./modules/person-projects/person-projects.component').then(
(mod) => mod.PersonProjectsComponent,
),
resolve: {
dfgProjectPage: dfgProjectsResolver,
personCordisEuProjectPage: personCordisEuProjectPageResolver,
},
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),
);
@@ -186,68 +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) => {
const network = from.data['collaborationNetwork'] as
| {
filter_information?: {
min_possible_year?: number;
max_possible_year?: number;
};
}
| undefined;
const filterInformation = network?.filter_information;
const defaultQueryParams: Record<string, string> = {
filter_by: 'works',
start_year: filterInformation?.min_possible_year
? String(filterInformation.min_possible_year)
: '',
end_year: filterInformation?.max_possible_year
? String(filterInformation.max_possible_year)
: '',
min_contributors: '2',
max_contributors: '10',
min_collaborations: '1',
max_collaborations: '100',
institutions: '',
topics: '',
};
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) => {
const fromRawValue = from.queryParamMap.get(key);
const toRawValue = to.queryParamMap.get(key);
const fromValue =
fromRawValue === null || fromRawValue === ''
? defaultQueryParams[key]
: fromRawValue;
const toValue =
toRawValue === null || toRawValue === ''
? defaultQueryParams[key]
: toRawValue;
return fromValue !== toValue;
});
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'funding',
loadComponent: () =>
@@ -255,23 +164,6 @@ export const routes: Routes = [
(mod) => mod.PersonFundingComponent,
),
},
{
path: 'news',
loadComponent: () =>
import('./modules/person-news/person-news.component').then(
(mod) => mod.PersonNewsComponent,
),
resolve: {
newsPage: personNewsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'pageSize', 'sortOrder', 'query'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'patents',
loadComponent: () =>
@@ -295,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),
);
@@ -313,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: () =>
@@ -338,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,
@@ -351,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),
);
@@ -366,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: () =>
@@ -400,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],
},
@@ -0,0 +1,248 @@
<div class="content">
<h1>Patente</h1>
<mat-divider />
<div class="search-and-filter">
<mat-form-field style="width: 100%">
<mat-label>Suche nach Titel oder Patent-Nr.</mat-label>
<input
matInput
type="search"
[value]="searchTerm"
(input)="onSearchInput($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearch()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<div class="filter-row">
<mat-chip-listbox
[value]="activeFilter"
(change)="setFilterFromChip($event)">
<mat-chip-option value="all">Alle</mat-chip-option>
<mat-chip-option value="EPO">EPO</mat-chip-option>
<mat-chip-option value="USPTO">USPTO</mat-chip-option>
</mat-chip-listbox>
<div class="sorting">
<select
(change)="setSortDirection($any($event.target).value)"
[value]="sortDirection">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
</select>
</div>
</div>
</div>
<mat-divider />
@if (loading) {
<div class="state-message">
<mat-progress-spinner diameter="36" mode="indeterminate" />
<span>Lade Patente...</span>
</div>
} @else if (error) {
<p class="state-message error">Fehler beim Laden der Patente.</p>
} @else if (showDetail && selectedPatent) {
<div class="detail-view">
<button type="button" class="back-btn" (click)="closeDetail()">
← Zurück zu den Patenten
</button>
<h2>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h2>
<div class="patent-meta__list">
@for (row of getPatentMetadataRows(selectedPatent); track row.label) {
<div class="patent-meta__row">
<dt>{{ row.label }}</dt>
<dd>
@if (row.variant === 'source') {
<span class="source-badge source-badge--{{ row.value.toLowerCase() }}">{{ row.value }}</span>
} @else {
{{ row.value }}
}
</dd>
</div>
}
</div>
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inv of selectedPatent.inventors; track inv) {
<li class="tag">{{ inv }}</li>
}
</ul>
</div>
@if (selectedPatent.assignees.length > 0) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (a of selectedPatent.assignees; track a) {
<li class="tag">{{ a }}</li>
}
</ul>
</div>
}
@if (selectedPatent.ipc_descriptions.length > 0) {
<div class="detail-section classification-section classification-section--ipc">
<h4>Klassifikation (IPC)</h4>
<div class="classification-cards">
@for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">{{ card.system }}</span>
<span class="classification-badge classification-badge--level">{{ card.levelLabel }}</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button type="button" class="classification-toggle" (click)="toggleClassificationExpanded(card.key)">
{{ isClassificationExpanded(card.key) ? 'Weniger anzeigen' : 'Mehr anzeigen' }}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.ipc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
@if (selectedPatent.cpc_descriptions.length > 0) {
<div class="detail-section classification-section classification-section--cpc">
<h4>Klassifikation (CPC)</h4>
<div class="classification-cards">
@for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">{{ card.system }}</span>
<span class="classification-badge classification-badge--level">{{ card.levelLabel }}</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button type="button" class="classification-toggle" (click)="toggleClassificationExpanded(card.key)">
{{ isClassificationExpanded(card.key) ? 'Weniger anzeigen' : 'Mehr anzeigen' }}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.cpc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (CPC)</h4>
<ul class="tag-list tag-list--compact">
@for (cpc of selectedPatent.cpc; track cpc) {
<li class="tag">{{ cpc }}</li>
}
</ul>
</div>
}
</div>
} @else if (patents.length === 0) {
<div class="no-results">
<p>Keine Patente gefunden.</p>
</div>
} @else {
<div class="cards">
@for (patent of patents; track patent.patent_id + (patent.publication_date ?? '')) {
<mat-card class="card" appearance="outlined" (click)="selectPatent(patent)">
<mat-card-header>
<mat-card-title>{{ patent.title ?? patent.patent_id }}</mat-card-title>
<mat-card-subtitle>
<span class="source-badge source-badge--{{ patent.source.toLowerCase() }}">{{ patent.source }}</span>
</mat-card-subtitle>
</mat-card-header>
<mat-card-content class="card-content">
<mat-divider />
<div class="card-metadata">
<span>{{ patent.patent_id }}</span>
<span>{{ formatDate(patent.publication_date) }}</span>
</div>
<mat-divider />
</mat-card-content>
<mat-card-footer>
<mat-card-actions>
<button mat-button (click)="selectPatent(patent); $event.stopPropagation()">
<mat-icon>info</mat-icon>
Übersicht
</button>
</mat-card-actions>
</mat-card-footer>
</mat-card>
}
</div>
}
<mat-divider />
@if (!showDetail) {
<mat-paginator
[length]="total"
[pageSize]="pageSize"
[pageIndex]="page"
[pageSizeOptions]="[10, 25, 50]"
(page)="handlePageChange($event)" />
}
</div>
@@ -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; }
}
@@ -0,0 +1,307 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
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<string>();
private searchSubject = new Subject<string>();
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<string, ClassificationCard>();
for (const entry of entries) {
const card = this.buildClassificationCard(entry, system);
const mergeKey = card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const s of card.symbols) {
if (!existing.symbols.includes(s)) existing.symbols.push(s);
}
continue;
}
merged.set(mergeKey, card);
}
return [...merged.values()];
}
toggleClassificationExpanded(key: string): void {
this.expandedClassificationKeys.has(key)
? this.expandedClassificationKeys.delete(key)
: this.expandedClassificationKeys.add(key);
}
isClassificationExpanded(key: string): boolean {
return this.expandedClassificationKeys.has(key);
}
isLongDescription(text: string | null): boolean {
return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
}
getDescriptionPreview(text: string | null): string {
if (!text) return '';
return text.length <= DESCRIPTION_PREVIEW_LENGTH
? text
: `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
}
private buildClassificationCard(entry: IpcClassification, system: ClassificationSystem): ClassificationCard {
const level = this.getClassificationLevel(entry);
const primaryDescription = this.extractDescriptionText(entry[level.field]);
return {
key: `${system}-${entry.symbol}`,
symbols: [entry.symbol],
system,
levelLabel: level.label,
primaryDescription,
hierarchy: this.buildHierarchyRows(entry, primaryDescription),
};
}
private getClassificationLevel(entry: IpcClassification): { label: string; field: keyof IpcClassification } {
if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };
if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' };
if (entry.section) return { label: 'Sektion', field: 'section' };
return { label: 'Code', field: 'symbol' };
}
private buildHierarchyRows(entry: IpcClassification, primaryDescription: string | null) {
const rows: { label: string; value: string }[] = [];
const seen = new Set<string>();
const addRow = (label: string, raw: string | null) => {
const value = this.extractDescriptionText(raw);
if (!value) return;
const norm = value.toLocaleLowerCase('en');
if (seen.has(norm) || norm === primaryDescription?.toLocaleLowerCase('en')) return;
seen.add(norm);
rows.push({ label, value });
};
addRow('Sektion', entry.section);
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;
}
}
@@ -1,179 +1,300 @@
@if (loading) {
<p class="message">Lade Patente...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (patents.length === 0) {
<p class="message">Keine Patente gefunden.</p>
} @else {
<div class="patents-container">
<div class="patents-summary">
<p class="summary-line">
<span class="summary-value">{{ filteredPatents.length }}</span>
<span class="summary-label"> Patente</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getEpoCount() }}</span>
<span class="summary-label"> EPO</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getUsptoCount() }}</span>
<span class="summary-label"> USPTO</span>
</p>
</div>
@if (showDetail && selectedPatent) {
<button class="back-btn" (click)="showDetail = false">
← Zurück zu den Patenten
</button>
}
<div class="patents-content">
@if (showDetail && selectedPatent) {
<div class="patent-full-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inventor of selectedPatent.inventors; track inventor) {
<li class="tag">{{ inventor }}</li>
}
</ul>
</div>
@if (hasAsignees(selectedPatent)) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (assignee of selectedPatent.assignees; track assignee) {
<li class="tag">{{ assignee }}</li>
}
</ul>
</div>
}
@if (hasIpcs(selectedPatent)) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
</div>
}
<div class="patents-list" [class.hidden]="showDetail">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select
[value]="activeFilter"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select
[value]="sortMode"
(change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
</div>
<table>
<thead>
<tr>
<th>Patent</th>
<th>Quelle</th>
<th>Jahr</th>
</tr>
</thead>
<tbody>
@for (patent of getPagedPatents(); track patent.patent_id) {
<tr
[class.selected]="selectedPatent === patent"
(click)="selectPatent(patent)">
<td class="patent-title">
{{ patent.title ?? patent.patent_id }}
</td>
<td>
<span
class="source-badge source-badge--{{
patent.source.toLowerCase()
}}">
{{ patent.source }}
</span>
</td>
<td>{{ patent.publication_year ?? '-' }}</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button
[disabled]="selectedPage === 1"
(click)="setPage(selectedPage - 1)">
Zurück
</button>
<span>Seite {{ selectedPage }} von {{ getPageCount() }}</span>
<button
[disabled]="selectedPage === getPageCount()"
(click)="setPage(selectedPage + 1)">
Weiter
</button>
</div>
}
</div>
@if (selectedPatent) {
<div class="patent-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat stat--clickable" (click)="openDetail()">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span
class="source-badge source-badge--{{
selectedPatent.source.toLowerCase()
}}">
{{ selectedPatent.source }}
</span>
</span>
</div>
<div class="stat">
<span class="stat-label">Patent-Nr.</span>
<span class="stat-value">{{ selectedPatent.patent_id }}</span>
</div>
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{
formatDate(selectedPatent.publication_date || '')
}}</span>
</div>
</div>
</div>
} @else {
<div class="patent-detail empty">
<p>Klicke auf ein Patent für Details.</p>
</div>
}
</div>
</div>
}
@if (loading) {
<p class="message">Lade Patente...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (patents.length === 0) {
<p class="message">Keine Patente gefunden.</p>
} @else {
<div class="patents-container">
<div class="patents-content">
@if (showDetail && selectedPatent) {
<div class="patent-full-detail">
<button type="button" class="back-btn" (click)="closeDetail()">
← Zurück zu den Patenten
</button>
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
@if (hasPatentMetadata(selectedPatent)) {
<div class="patent-meta patent-meta--inline">
<dl class="patent-meta__list">
@for (row of getPatentMetadataRows(selectedPatent); track row.label) {
<div class="patent-meta__row">
<dt>{{ row.label }}</dt>
<dd>
@if (row.variant === 'source') {
<span class="source-badge source-badge--{{ row.value.toLowerCase() }}">
{{ row.value }}
</span>
} @else {
{{ row.value }}
}
</dd>
</div>
}
</dl>
</div>
}
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inventor of selectedPatent.inventors; track inventor) {
<li class="tag">{{ inventor }}</li>
}
</ul>
</div>
@if (selectedPatent.assignees.length > 0) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (assignee of selectedPatent.assignees; track assignee) {
<li class="tag">{{ assignee }}</li>
}
</ul>
</div>
}
@if (selectedPatent.ipc_descriptions.length > 0) {
<div class="detail-section classification-section classification-section--ipc">
<h4>Klassifikation (IPC)</h4>
<div class="classification-cards">
@for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">{{ card.system }}</span>
<span class="classification-badge classification-badge--level">{{ card.levelLabel }}</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{ isClassificationExpanded(card.key) ? 'Weniger anzeigen' : 'Mehr anzeigen' }}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.ipc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
@if (selectedPatent.cpc_descriptions.length > 0) {
<div class="detail-section classification-section classification-section--cpc">
<h4>Klassifikation (CPC)</h4>
<div class="classification-cards">
@for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">{{ card.system }}</span>
<span class="classification-badge classification-badge--level">{{ card.levelLabel }}</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{ isClassificationExpanded(card.key) ? 'Weniger anzeigen' : 'Mehr anzeigen' }}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.cpc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (CPC)</h4>
<ul class="tag-list tag-list--compact">
@for (cpc of selectedPatent.cpc; track cpc) {
<li class="tag">{{ cpc }}</li>
}
</ul>
</div>
}
</div>
}
<div class="patents-list" [class.hidden]="showDetail">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select [value]="activeFilter" (change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select [value]="sortMode" (change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
</div>
<table>
<thead>
<tr>
<th>Patent</th>
<th>Quelle</th>
<th>Jahr</th>
</tr>
</thead>
<tbody>
@for (patent of getPagedPatents(); track trackPatent($index, patent)) {
<tr
[class.selected]="selectedPatent === patent"
(click)="selectPatent(patent)">
<td class="patent-title">{{ patent.title ?? patent.patent_id }}</td>
<td>
<span class="source-badge source-badge--{{ patent.source.toLowerCase() }}">
{{ patent.source }}
</span>
</td>
<td>{{ patent.publication_year ?? '-' }}</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button [disabled]="selectedPage === 1" (click)="setPage(selectedPage - 1)">Zurück</button>
<span>Seite {{ selectedPage }} von {{ getPageCount() }}</span>
<button [disabled]="selectedPage === getPageCount()" (click)="setPage(selectedPage + 1)">Weiter</button>
</div>
}
</div>
@if (selectedPatent && !showDetail) {
<div class="patent-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span class="source-badge source-badge--{{ selectedPatent.source.toLowerCase() }}">
{{ selectedPatent.source }}
</span>
</span>
</div>
<div class="stat">
<span class="stat-label">Patent-Nr.</span>
<span class="stat-value">{{ selectedPatent.patent_id }}</span>
</div>
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{ formatDate(selectedPatent.publication_date) }}</span>
</div>
@if (getPublicationStageLabel(selectedPatent); as stageLabel) {
<div class="stat">
<span class="stat-label">Publikationsstufe</span>
<span class="stat-value">{{ stageLabel }}</span>
</div>
}
</div>
@if (getAbstractPreview(selectedPatent.abstract); as abstractPreview) {
<p class="patent-detail-preview">{{ abstractPreview }}</p>
}
<button type="button" class="patent-detail-action" (click)="openDetail()">
<span class="patent-detail-action__label">Patentdetails anzeigen</span>
<span class="material-icons" aria-hidden="true">chevron_right</span>
</button>
<p class="patent-detail-hint">
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
</p>
</div>
} @else {
<div class="patent-detail overview">
<p class="overview-title">Patentübersicht</p>
<p class="overview-subtitle">Alle Patente dieser Person im Überblick.</p>
<div class="overview-stats">
<div class="overview-stat">
<span class="overview-value">{{ patents.length }}</span>
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getEpoCount() }}</span>
<span class="overview-label">EPO</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getUsptoCount() }}</span>
<span class="overview-label">USPTO</span>
</div>
</div>
<p class="overview-hint">Wähle links ein Patent aus, um Kurzinfos und Details zu sehen.</p>
</div>
}
</div>
</div>
}
@@ -1,306 +1,564 @@
.message {
padding: 16px;
color: #666;
}
.patents-container {
padding: 16px;
display: flex;
flex-direction: column;
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;
gap: 6px;
width: fit-content;
padding: 10px 14px;
border-radius: 20px;
background: #f2f2f2;
color: #333;
font-size: 14px;
span {
color: #555;
}
select {
border: 0;
background: transparent;
color: #111827;
font: inherit;
cursor: pointer;
outline: none;
}
}
.patents-content {
display: flex;
gap: 24px;
align-items: flex-start;
}
.patents-list {
flex: 1;
&.hidden {
display: none;
}
.patents-list-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
flex-wrap: wrap;
}
table {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #333;
}
tr {
cursor: pointer;
&:hover {
background: #f5f5f5;
}
&.selected {
background: #f0f0f0;
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
}
.patent-title {
color: #333;
font-weight: 500;
max-width: 400px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.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;
}
}
.patent-detail {
width: 440px;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
&.empty {
display: flex;
align-items: center;
justify-content: center;
color: #999;
min-height: 200px;
}
h3 {
margin: 0 0 16px 0;
font-size: 16px;
color: #333;
line-height: 1.4;
}
}
.detail-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
.stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 10px;
text-align: center;
.stat-label {
display: block;
font-size: 11px;
color: #666;
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.stat-value {
display: block;
font-size: 15px;
font-weight: bold;
color: #333;
}
}
}
.stat--clickable {
cursor: pointer;
transition:
border-color 0.15s,
background 0.15s;
&:hover {
border-color: #0b63ce;
background: #f0f6ff;
}
}
.patent-full-detail {
flex: 1;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
h3 {
margin: 0 0 16px 0;
font-size: 16px;
color: #333;
line-height: 1.4;
}
h4 {
margin: 16px 0 8px 0;
font-size: 14px;
color: #555;
font-weight: 600;
}
p {
font-size: 13px;
color: #444;
line-height: 1.6;
margin: 0;
}
}
.back-btn {
border: none;
background: none;
color: #333;
cursor: pointer;
font-size: 14px;
font-weight: 400;
padding: 0;
align-self: flex-start; // NEU
&:hover {
text-decoration: underline;
}
}
.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;
line-height: 1.3;
}
.pagination {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
button {
padding: 4px 10px;
border: 1px solid #d0d0d0;
border-radius: 6px;
background: white;
cursor: pointer;
font-size: 12px;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
span {
font-size: 12px;
color: #666;
}
}
.message {
padding: 16px;
color: #666;
}
.patents-container {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
.sort-control {
display: inline-flex;
align-items: center;
gap: 6px;
width: fit-content;
padding: 10px 14px;
border-radius: 20px;
background: #f2f2f2;
color: #333;
font-size: 14px;
span {
color: #555;
}
select {
border: 0;
background: transparent;
color: #111827;
font: inherit;
cursor: pointer;
outline: none;
}
}
.patents-content {
display: flex;
gap: 24px;
align-items: flex-start;
}
.patents-list {
flex: 1;
&.hidden {
display: none;
}
.patents-list-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
flex-wrap: wrap;
}
table {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #333;
}
tr {
cursor: pointer;
&:hover {
background: #f5f5f5;
}
&.selected {
background: #f0f0f0;
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
}
.patent-title {
color: #333;
font-weight: 500;
max-width: 400px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.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;
}
}
.patent-detail {
width: 440px;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
&.empty {
display: flex;
align-items: center;
justify-content: center;
color: #999;
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;
color: #333;
line-height: 1.4;
}
}
.detail-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
.stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 10px;
text-align: center;
.stat-label {
display: block;
font-size: 11px;
color: #666;
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.stat-value {
display: block;
font-size: 15px;
font-weight: bold;
color: #333;
}
}
}
.patent-detail-preview {
margin: 14px 0 0;
font-size: 13px;
line-height: 1.55;
color: #555;
}
.patent-detail-action {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
margin-top: 16px;
padding: 12px 14px;
border: 1px solid #bdd4ff;
border-radius: 10px;
background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
color: #0b63ce;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
&:hover {
border-color: #0b63ce;
background: #f0f6ff;
box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
}
.material-icons {
font-size: 20px;
}
}
.patent-detail-hint {
margin: 8px 0 0;
font-size: 12px;
line-height: 1.4;
color: #888;
text-align: center;
}
.patent-full-detail {
flex: 1;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
h3 {
margin: 0 0 4px 0;
font-size: 16px;
color: #333;
line-height: 1.4;
}
h4 {
margin: 16px 0 8px 0;
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;
width: auto;
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;
transition:
background-color 0.15s ease,
border-color 0.15s ease,
color 0.15s ease,
box-shadow 0.15s ease;
&:hover {
background: #eef5ff;
border-color: #bcd3f7;
color: #1d4ed8;
box-shadow: 0 1px 4px rgba(37, 99, 235, 0.12);
}
&:focus-visible {
outline: 2px solid #93c5fd;
outline-offset: 2px;
}
}
.detail-section {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #eee;
}
.patent-meta {
&--inline {
margin: 12px 0 20px;
}
&__list {
margin: 0;
border: 1px solid #e2e8f4;
border-radius: 12px;
background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
overflow: hidden;
}
&__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;
line-height: 1.35;
}
dd {
margin: 0;
font-size: 14px;
font-weight: 600;
color: #1e293b;
line-height: 1.35;
word-break: break-word;
}
}
}
.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;
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;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
button {
padding: 4px 10px;
border: 1px solid #d0d0d0;
border-radius: 6px;
background: white;
cursor: pointer;
font-size: 12px;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
span {
font-size: 12px;
color: #666;
}
}
@@ -1,174 +1,406 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api';
type SortMode = 'date' | 'title';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
@Component({
selector: 'app-person-patents',
imports: [CommonModule],
templateUrl: './person-patents.component.html',
styleUrl: './person-patents.component.scss',
})
export class PersonPatentsComponent implements OnInit {
private route = inject(ActivatedRoute);
private router = inject(Router);
private patentsApi = inject(PatentsService);
patents: PatentEntry[] = [];
filteredPatents: PatentEntry[] = [];
authorName: string | null = null;
selectedPatent: PatentEntry | null = null;
showDetail = false;
loading = true;
error = false;
activeFilter: SourceFilter = 'all';
sortMode: SortMode = 'date';
selectedPage = 1;
readonly pageSize = 10;
hasAsignees(selectedPatent: PatentEntry | null): boolean {
return !!selectedPatent?.assignees && selectedPatent.assignees.length > 0;
}
hasIpcs(selectedPatent: PatentEntry | null): boolean {
return !!selectedPatent?.ipc && selectedPatent.ipc.length > 0;
}
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
const authorId = params.get('id') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
if (authorId) {
this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({
next: (result) => {
this.patents = result.patents ?? [];
this.authorName = result.author_name ?? null;
this.applyFilter();
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
},
});
}
});
}
setFilter(filter: SourceFilter): void {
this.activeFilter = filter;
this.selectedPage = 1;
this.selectedPatent = null;
this.showDetail = false;
this.applyFilter();
this.updateQueryParams();
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.applyFilter();
this.updateQueryParams();
}
selectPatent(patent: PatentEntry): void {
this.selectedPatent = patent;
this.showDetail = false;
this.updateQueryParams();
}
openDetail(): void {
this.showDetail = true;
}
private applyFilter(): void {
let patents = this.patents;
if (this.activeFilter !== 'all') {
patents = patents.filter((p) => p.source === this.activeFilter);
}
this.filteredPatents = this.sortPatents(patents);
}
private sortPatents(patents: PatentEntry[]): PatentEntry[] {
return [...patents].sort((a, b) => {
if (this.sortMode === 'date') {
return (b.publication_date ?? '').localeCompare(
a.publication_date ?? '',
);
}
return (a.title ?? '').localeCompare(b.title ?? '', 'de', {
sensitivity: 'base',
});
});
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
sortBy: this.sortMode,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
private isValidFilter(value: string | null): value is SourceFilter {
return value === 'all' || value === 'EPO' || value === 'USPTO';
}
private isValidSortMode(value: string | null): value is SortMode {
return value === 'date' || value === 'title';
}
getPagedPatents(): PatentEntry[] {
const start = (this.selectedPage - 1) * this.pageSize;
return this.filteredPatents.slice(start, start + this.pageSize);
}
getPageCount(): number {
return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize));
}
hasPagination(): boolean {
return this.getPageCount() > 1;
}
setPage(page: number): void {
this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount());
this.updateQueryParams();
}
formatDate(date: string | null): 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));
}
getEpoCount(): number {
return this.patents.filter((p) => p.source === 'EPO').length;
}
getUsptoCount(): number {
return this.patents.filter((p) => p.source === 'USPTO').length;
}
}
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
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 }[];
}
interface PatentMetadataRow {
label: string;
value: string;
variant?: 'source';
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
@Component({
selector: 'app-person-patents',
imports: [CommonModule],
templateUrl: './person-patents.component.html',
styleUrl: './person-patents.component.scss',
})
export class PersonPatentsComponent implements OnInit {
private route = inject(ActivatedRoute);
private router = inject(Router);
private patentsApi = inject(PatentsService);
patents: PatentEntry[] = [];
filteredPatents: PatentEntry[] = [];
authorName: string | null = null;
selectedPatent: PatentEntry | null = null;
showDetail = false;
loading = true;
error = false;
activeFilter: SourceFilter = 'all';
sortMode: SortMode = 'date';
selectedPage = 1;
readonly pageSize = 10;
private expandedClassificationKeys = new Set<string>();
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
const authorId = params.get('id') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
if (authorId) {
this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({
next: (result) => {
this.patents = result.patents ?? [];
this.authorName = result.author_name ?? null;
this.applyFilter();
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
},
});
}
});
}
setFilter(filter: SourceFilter): void {
this.activeFilter = filter;
this.selectedPage = 1;
this.selectedPatent = null;
this.showDetail = false;
this.applyFilter();
this.updateQueryParams();
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.applyFilter();
this.updateQueryParams();
}
selectPatent(patent: PatentEntry): void {
this.selectedPatent = patent;
this.showDetail = false;
this.expandedClassificationKeys.clear();
this.updateQueryParams();
}
openDetail(): void {
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.showDetail = false;
this.expandedClassificationKeys.clear();
}
private applyFilter(): void {
let patents = this.patents;
if (this.activeFilter !== 'all') {
patents = patents.filter((p) => p.source === this.activeFilter);
}
this.filteredPatents = this.sortPatents(patents);
}
private sortPatents(patents: PatentEntry[]): PatentEntry[] {
return [...patents].sort((a, b) => {
if (this.sortMode === 'date') {
return (b.publication_date ?? '').localeCompare(a.publication_date ?? '');
}
return (a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' });
});
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
sortBy: this.sortMode,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
private isValidFilter(value: string | null): value is SourceFilter {
return value === 'all' || value === 'EPO' || value === 'USPTO';
}
private isValidSortMode(value: string | null): value is SortMode {
return value === 'date' || value === 'title';
}
getPagedPatents(): PatentEntry[] {
const start = (this.selectedPage - 1) * this.pageSize;
return this.filteredPatents.slice(start, start + this.pageSize);
}
getPageCount(): number {
return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize));
}
hasPagination(): boolean {
return this.getPageCount() > 1;
}
setPage(page: number): void {
this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount());
this.updateQueryParams();
}
formatDate(date: string | null): 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));
}
getEpoCount(): number {
return this.patents.filter((p) => p.source === 'EPO').length;
}
getUsptoCount(): number {
return this.patents.filter((p) => p.source === 'USPTO').length;
}
trackPatent(_index: number, patent: PatentEntry): string {
return [
patent.source,
patent.patent_id,
patent.publication_date ?? '',
patent.kind ?? patent.application_type ?? '',
].join('|');
}
getAbstractPreview(abstract: string | null | undefined): string | null {
if (!abstract?.trim()) {
return null;
}
const text = abstract.trim();
if (text.length <= 160) {
return text;
}
return `${text.slice(0, 160).trimEnd()}…`;
}
getPublicationStageLabel(patent: PatentEntry): string | null {
if (patent.kind) {
return patent.kind;
}
if (patent.application_type) {
return patent.application_type;
}
return null;
}
hasPatentMetadata(_patent: PatentEntry): boolean {
return true;
}
getPatentMetadataRows(patent: PatentEntry): PatentMetadataRow[] {
const rows: PatentMetadataRow[] = [];
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 stageLabel = this.getPublicationStageLabel(patent);
if (stageLabel) {
rows.push({
label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp',
value: patent.kind ? stageLabel : this.formatMetadataLabel(stageLabel),
});
}
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, (char) => char.toUpperCase());
}
getClassificationCards(
entries: IpcClassification[] | undefined,
system: ClassificationSystem,
): ClassificationCard[] {
if (!entries?.length) {
return [];
}
const merged = new Map<string, ClassificationCard>();
for (const entry of entries) {
const card = this.buildClassificationCard(entry, system);
const mergeKey =
card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const 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<string>();
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();
}
}
@@ -90,6 +90,12 @@ export class AppMenuComponent {
sorting_order: 'asc',
},
},
{
label: 'Patente',
icon: 'workspace_premium',
route: '/patents',
disabled: false,
},
];
constructor(