diff --git a/service/Dockerfile b/service/Dockerfile index cfbb7094..e32d005c 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -12,8 +12,11 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "uvicorn~=0.29.0" \ "pytest~=8.1.0" \ "httpx~=0.27.0" \ - "python-multipart~=0.0.19"\ + "python-multipart~=0.0.19" \ + "beautifulsoup4==4.12.3" \ "openai~=2.41.0" \ + "websockets==12.0" \ + "partial-json-parser==0.2.1.1.post7" \ "sqlmodel~=0.0.33" \ "argon2-cffi~=25.1.0" diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py new file mode 100644 index 00000000..7eb03cef --- /dev/null +++ b/service/scripts/index_org_patents.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Index org_patents for an institution.""" +from __future__ import annotations + +import argparse +import asyncio +import logging +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from dotenv import load_dotenv + +load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env") + +from inse.patents.org.logic import index_org_patents_for_institution + +logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") +logger = logging.getLogger(__name__) + + +async def main() -> None: + parser = argparse.ArgumentParser(description="Index org_patents for an institution.") + parser.add_argument( + "--institution-id", + required=True, + help="OpenAlex institution ID, e.g. I62318514", + ) + args = parser.parse_args() + + count = await index_org_patents_for_institution(args.institution_id) + logger.info("Finished indexing %d patents for institution %s", count, args.institution_id) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/service/src/main/inse/account_management/model.py b/service/src/main/inse/account_management/model.py index 2bb7613d..8b21edf7 100644 --- a/service/src/main/inse/account_management/model.py +++ b/service/src/main/inse/account_management/model.py @@ -20,6 +20,7 @@ class AccountProfile(BaseModel): organization_id: uuid.UUID organization_name: str deleted: bool + activated: bool is_current: bool = False is_real_account: bool = False is_impersonating: bool = False @@ -49,3 +50,4 @@ class UpdateAccountRequest(BaseModel): password: Optional[str] = Field(default=None, min_length=8) openalex_person_id: Optional[str] = None deleted: Optional[bool] = None + activated: Optional[bool] = None diff --git a/service/src/main/inse/account_management/router.py b/service/src/main/inse/account_management/router.py index 82781fb0..81b22593 100644 --- a/service/src/main/inse/account_management/router.py +++ b/service/src/main/inse/account_management/router.py @@ -1,12 +1,11 @@ import uuid -from typing import Optional +from typing import Annotated, Optional -from fastapi import APIRouter, Depends, Query, Response, status -from sqlmodel import Session +from fastapi import APIRouter, Query, Response, status from inse.auth import service as auth_service -from inse.auth.model import AccessToken -from inse.database import get_session +from inse.auth.model import AccessTokenMetadata +from inse.database import SessionDep from inse.tags import Tags from . import service @@ -24,11 +23,10 @@ router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH]) @router.get( "/me", operation_id="getCurrentAccount", - response_model=AccountProfile, ) async def get_current_account( - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.get_current_account(session=session, access_token=access_token) @@ -36,16 +34,15 @@ async def get_current_account( @router.get( "", operation_id="listAccounts", - response_model=AccountPage, ) async def list_accounts( - page: int = Query(default=0, ge=0), - page_size: int = Query(default=25, ge=1, le=100), - offset: Optional[int] = Query(default=None, ge=0), - search: Optional[str] = Query(default=None), - organization_id: Optional[uuid.UUID] = Query(default=None), - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + page: Annotated[int, Query(ge=0)] = 0, + page_size: Annotated[int, Query(ge=1, le=100)] = 10, + offset: Annotated[int, Query(ge=0)] = 0, + search: Annotated[Optional[str], Query()] = None, + organization_id: Annotated[Optional[uuid.UUID], Query()] = None, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountPage: return service.list_accounts( session=session, @@ -61,13 +58,12 @@ async def list_accounts( @router.post( "", operation_id="createAccount", - response_model=AccountProfile, status_code=status.HTTP_201_CREATED, ) async def create_account( payload: CreateAccountRequest, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.create_account( session=session, @@ -79,11 +75,10 @@ async def create_account( @router.get( "/organizations", operation_id="listAccountOrganizations", - response_model=list[OrganizationProfile], ) async def list_organizations( - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> list[OrganizationProfile]: return service.list_organizations(session=session, access_token=access_token) @@ -91,13 +86,12 @@ async def list_organizations( @router.put( "/{account_id}", operation_id="updateAccount", - response_model=AccountProfile, ) async def update_account( account_id: uuid.UUID, payload: UpdateAccountRequest, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> AccountProfile: return service.update_account( session=session, @@ -114,8 +108,8 @@ async def update_account( ) async def delete_account( account_id: uuid.UUID, - session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + session: SessionDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> Response: service.delete_account( session=session, diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py index 5ef45372..b9d9dfda 100644 --- a/service/src/main/inse/account_management/service.py +++ b/service/src/main/inse/account_management/service.py @@ -5,7 +5,7 @@ from fastapi import HTTPException, status from sqlmodel import Session, func, or_, select from inse.auth import service as auth_service -from inse.auth.model import AccessToken, Account, Organization, UserRole +from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole from .model import ( AccountPage, @@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool: return False -def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: +def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile: organization_name = account.organization.name if account.organization else "" return AccountProfile( id=account.id, @@ -38,6 +38,7 @@ def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile: organization_id=account.organization_id, organization_name=organization_name, deleted=account.deleted, + activated=account.activated, is_current=account.id == token.effective_account_id, is_real_account=account.id == token.real_account_id, is_impersonating=token.is_impersonating(), @@ -54,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account: return account -def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None: +def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata) -> None: if token.effective_role == UserRole.SUPER_ADMIN: return if ( @@ -94,31 +95,35 @@ def _ensure_email_available( ) -def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile: +def get_current_account(session: Session, access_token: AccessTokenMetadata) -> AccountProfile: account = _get_account_or_404(session, access_token.effective_account_id) return _account_to_profile(account, access_token) def list_accounts( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, page: int, page_size: int, offset: Optional[int] = None, search: Optional[str] = None, organization_id: Optional[uuid.UUID] = None, ) -> AccountPage: - if not _is_admin(access_token.effective_role): + if access_token.effective_role not in { + UserRole.SUPER_ADMIN, + UserRole.ADMIN, + UserRole.MANAGER, + }: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, - detail="Only admins can list accounts.", + detail="Only managers and admins can list accounts.", ) statement = select(Account) count_statement = select(func.count()).select_from(Account) filters = [] - if access_token.effective_role == UserRole.ADMIN: + if access_token.effective_role in {UserRole.ADMIN, UserRole.MANAGER}: filters.append(Account.organization_id == access_token.effective_organization_id) elif organization_id is not None: filters.append(Account.organization_id == organization_id) @@ -152,7 +157,7 @@ def list_accounts( def create_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, payload: CreateAccountRequest, ) -> AccountProfile: if not _is_admin(access_token.effective_role): @@ -202,12 +207,12 @@ def create_account( def list_organizations( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, ) -> list[OrganizationProfile]: if access_token.effective_role == UserRole.SUPER_ADMIN: organizations = session.exec( select(Organization) - .where(Organization.deleted == False) # noqa: E712 + .where(Organization.deleted.is_not(True)) .order_by(Organization.name) ).all() elif access_token.effective_role == UserRole.ADMIN: @@ -228,7 +233,7 @@ def list_organizations( def update_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, account_id: uuid.UUID, payload: UpdateAccountRequest, ) -> AccountProfile: @@ -285,6 +290,15 @@ def update_account( account.deleted = payload.deleted account.epoch += 1 + if payload.activated is not None and payload.activated != account.activated: + if access_token.effective_role != UserRole.SUPER_ADMIN or is_self_update: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only super admins can activate or deactivate other accounts.", + ) + account.activated = payload.activated + account.epoch += 1 + session.add(account) session.commit() session.refresh(account) @@ -293,7 +307,7 @@ def update_account( def delete_account( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, account_id: uuid.UUID, ) -> None: account = _get_account_or_404(session, account_id) diff --git a/service/src/main/inse/account_management/test_service.py b/service/src/main/inse/account_management/test_service.py new file mode 100644 index 00000000..b6d43714 --- /dev/null +++ b/service/src/main/inse/account_management/test_service.py @@ -0,0 +1,180 @@ +from types import SimpleNamespace + +import pytest +from fastapi import HTTPException +from sqlmodel import Session, SQLModel, create_engine + +from inse.account_management import service +from inse.account_management.model import UpdateAccountRequest +from inse.auth.model import Account, Organization, UserRole + + +@pytest.fixture() +def session(): + engine = create_engine( + "sqlite:///:memory:", connect_args={"check_same_thread": False} + ) + SQLModel.metadata.create_all(engine) + with Session(engine) as database_session: + yield database_session + + +def access_token(role, account_id, organization_id): + return SimpleNamespace( + effective_role=role, + effective_account_id=account_id, + real_account_id=account_id, + effective_organization_id=organization_id, + is_impersonating=lambda: False, + ) + + +def create_accounts(session): + organization = Organization(name="Test organization") + session.add(organization) + session.flush() + superadmin = Account( + email="superadmin@example.org", + name="Superadmin", + password_hash="hash", + organization_id=organization.id, + role=UserRole.SUPER_ADMIN, + ) + user = Account( + email="user@example.org", + name="User", + password_hash="hash", + organization_id=organization.id, + ) + session.add(superadmin) + session.add(user) + session.commit() + return organization, superadmin, user + + +def test_accounts_are_activated_by_default(session): + _, _, user = create_accounts(session) + assert user.activated is True + + +def test_superadmin_can_deactivate_and_reactivate_account(session): + organization, superadmin, user = create_accounts(session) + token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id) + + profile = service.update_account( + session, token, user.id, UpdateAccountRequest(activated=False) + ) + assert profile.activated is False + assert user.epoch == 1 + + profile = service.update_account( + session, token, user.id, UpdateAccountRequest(activated=True) + ) + assert profile.activated is True + assert user.epoch == 2 + + +def test_non_superadmin_cannot_change_activation(session): + organization, superadmin, user = create_accounts(session) + admin = Account( + email="admin@example.org", + name="Admin", + password_hash="hash", + organization_id=organization.id, + role=UserRole.ADMIN, + ) + session.add(admin) + session.commit() + + with pytest.raises(HTTPException) as error: + service.update_account( + session, + access_token(UserRole.ADMIN, admin.id, organization.id), + user.id, + UpdateAccountRequest(activated=False), + ) + + assert error.value.status_code == 403 + assert user.activated is True + + +def test_superadmin_cannot_deactivate_own_account(session): + organization, superadmin, _ = create_accounts(session) + + with pytest.raises(HTTPException) as error: + service.update_account( + session, + access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id), + superadmin.id, + UpdateAccountRequest(activated=False), + ) + + assert error.value.status_code == 403 + assert superadmin.activated is True + + +def test_manager_only_lists_accounts_from_own_organization(session): + organization, superadmin, user = create_accounts(session) + manager = Account( + email="manager@example.org", + name="Manager", + password_hash="hash", + organization_id=organization.id, + role=UserRole.MANAGER, + ) + other_organization = Organization(name="Other organization") + session.add(other_organization) + session.flush() + other_user = Account( + email="other@example.org", + name="Other User", + password_hash="hash", + organization_id=other_organization.id, + ) + session.add(manager) + session.add(other_user) + session.commit() + + result = service.list_accounts( + session, + access_token(UserRole.MANAGER, manager.id, organization.id), + page=0, + page_size=25, + organization_id=other_organization.id, + ) + + assert {profile.id for profile in result.items} == { + account.id for account in [superadmin, user, manager] + } + assert other_user.id not in {profile.id for profile in result.items} + + +def test_user_cannot_list_accounts(session): + organization, _, user = create_accounts(session) + + with pytest.raises(HTTPException) as error: + service.list_accounts( + session, + access_token(UserRole.USER, user.id, organization.id), + page=0, + page_size=25, + ) + + assert error.value.status_code == 403 + + +def test_superadmin_lists_all_active_organizations_for_selectbox(session): + first = Organization(name="Alpha") + second = Organization(name="Beta") + deleted = Organization(name="Deleted", deleted=True) + session.add(first) + session.add(second) + session.add(deleted) + session.commit() + + organizations = service.list_organizations( + session, + access_token(UserRole.SUPER_ADMIN, first.id, first.id), + ) + + assert [organization.name for organization in organizations] == ["Alpha", "Beta"] diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index a79aa113..fdd687a2 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -15,9 +15,9 @@ class UserRole(StrEnum): class TokenType(StrEnum): - ID_TOKEN = "ID" - REFRESH_TOKEN = "REFRESH" - ACCESS_TOKEN = "ACCESS" + ID_TOKEN = "ID_TOKEN" + REFRESH_TOKEN = "REFRESH_TOKEN" + ACCESS_TOKEN = "ACCESS_TOKEN" class Durable(SQLModel): @@ -77,6 +77,12 @@ class Account(Durable, table=True): nullable=False, description="The epoch value for the account. Used for versioning of tokens.", ) + activated: bool = Field( + default=True, + nullable=False, + index=True, + description="Indicates whether the account is allowed to authenticate.", + ) password_hash: str = Field( index=False, nullable=False, @@ -123,37 +129,20 @@ class Secret(SQLModel, table=True): ) -class Token(BaseModel): - token_type: TokenType = Field( - description="The type of the token (ID, Refresh, or Access).", - ) +class BaseTokenData(BaseModel): real_account_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the real account associated with this token.", ) expires_at: datetime = Field( - index=True, - nullable=False, description="The timestamp indicating when the token will expire.", ) epoch: int = Field( default=0, - nullable=False, description="The epoch value for the token. Used for versioning of tokens.", ) - user_fingerprint_hash: str = Field( - index=True, - nullable=False, - description="A hash of the user's fingerprint to ensure the token is used by the same user.", - ) - raw_token: str = Field( - index=False, - nullable=False, - description="The raw token string.", - ) -class IdToken(Token): +class IdTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.ID_TOKEN, const=True, @@ -161,24 +150,23 @@ class IdToken(Token): ) -class AccessToken(Token): +class AccessTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.ACCESS_TOKEN, const=True, description="The type of the token, which is always ACCESS_TOKEN for this class.", ) + user_fingerprint_hash: str = Field( + description="A unique fingerprint of the user, used for additional security checks.", + ) effective_account_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", ) effective_role: UserRole = Field( default=UserRole.USER, - index=True, - nullable=False, description="The specific role this access token grants within its organization.", ) effective_organization_id: uuid.UUID = Field( - nullable=False, description="The unique identifier of the organization associated with this access token.", ) @@ -191,22 +179,50 @@ class AccessToken(Token): return self.effective_account_id != self.real_account_id -class RefreshToken(AccessToken): +class AccessToken(AccessTokenMetadata): + raw_token: str = Field( + description="The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.", + ) + + +class RefreshTokenMetadata(BaseTokenData): token_type: TokenType = Field( default=TokenType.REFRESH_TOKEN, const=True, description="The type of the token, which is always REFRESH_TOKEN for this class.", ) + effective_account_id: uuid.UUID = Field( + description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", + ) + effective_role: UserRole = Field( + default=UserRole.USER, + description="The specific role this access token grants within its organization.", + ) + effective_organization_id: uuid.UUID = Field( + description="The unique identifier of the organization associated with this access token.", + ) + + +class RefreshToken(RefreshTokenMetadata): + raw_token: str = Field( + description="The raw string representation of the refresh token. This is the actual token that can be used to obtain new access tokens.", + ) class LoginResponse(BaseModel): - id_token: IdToken = Field(description="The ID token issued upon successful login.") + id_token: IdTokenMetadata = Field( + description="The ID token issued upon successful login." + ) class AccessResponse(BaseModel): access_token: AccessToken = Field( description="The access token issued upon successful authentication." ) - refresh_token: RefreshToken = Field( - description="The refresh token issued alongside the access token for obtaining new access tokens." + + +class OtkResponse(BaseModel): + status: str = Field(description="The status of the one-time code (OTC) request.") + account_id: uuid.UUID = Field( + description="The unique identifier of the account for which the OTC was requested." ) diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 2ce4f52a..9c15079f 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -12,9 +12,11 @@ from inse.database import SessionDep, get_session from inse.auth.model import ( AccessResponse, AccessToken, - IdToken, + AccessTokenMetadata, + IdTokenMetadata, LoginResponse, - RefreshToken, + OtkResponse, + RefreshTokenMetadata, ) logger = logging.getLogger(__name__) @@ -40,7 +42,7 @@ async def request_otk( session: SessionDep, email: Annotated[str, Body(description="User's email address")], password: Annotated[str, Body(description="User's password")], -): +) -> OtkResponse: return auth_service.request_otk(session=session, email=email, password=password) @@ -80,7 +82,7 @@ async def get_action_tokens( effective_account_id: Annotated[ uuid.UUID, Body(description="Effective account ID for the access token") ], - id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep], + id_token: Annotated[IdTokenMetadata, auth_service.CurrentUserIdTokenPayloadDep], ) -> AccessResponse: logger.debug( "Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s", @@ -108,11 +110,14 @@ async def get_action_tokens( }, ) async def refresh_access_token( + response: Response, refresh_token: Annotated[ - RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep + RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep ], ) -> AccessToken: - return auth_service.refresh_access_token(refresh_token=refresh_token) + return auth_service.refresh_access_token( + response=response, refresh_token=refresh_token + ) @router.post( @@ -125,7 +130,7 @@ async def refresh_access_token( async def logout( session: Annotated[Session, Depends(get_session)], access_token: Annotated[ - AccessToken, + AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, ], ): @@ -150,7 +155,7 @@ async def change_password( Body(description="New password", min_length=8), ], access_token: Annotated[ - AccessToken, + AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, ], ): diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 3c24086e..604085ab 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -4,21 +4,23 @@ import json import logging import secrets import uuid -from typing import Annotated, Any, Dict, Literal, Optional +from typing import Annotated, Any, Dict, Optional import jwt from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError -from fastapi import Depends, HTTPException, Request, Response, status +from fastapi import Cookie, Depends, HTTPException, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from inse.auth.model import ( AccessResponse, AccessToken, + AccessTokenMetadata, Account, - IdToken, + IdTokenMetadata, LoginResponse, Organization, - RefreshToken, + OtkResponse, + RefreshTokenMetadata, Secret, TokenType, UserRole, @@ -28,9 +30,9 @@ from inse.database import get_session from sqlmodel import Session, select, func from inse.auth.email_service import send_email -ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days -REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes -ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes +ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days +REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day +ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes OTK_EXPIRATION_MINUTES = 15 # 15 minutes @@ -41,8 +43,11 @@ EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id" EPOCH_KEY = "epoch" USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" -ID_FP_COOKIE_KEY = "_Secure-Fgp-ID" -ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act" + +ACCESS_FP_COOKIE_KEY = "_Secure-Fgp-Acc" +ID_TOKEN_COOKIE_KEY = "id_token" +REFRESH_TOKEN_COOKIE_KEY = "refresh_token" + settings = get_settings() @@ -155,7 +160,7 @@ def _verify_password(password: str, password_hash: str) -> bool: return False -def request_otk(session: Session, email: str, password: str): +def request_otk(session: Session, email: str, password: str) -> OtkResponse: """Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid. Args: @@ -196,6 +201,13 @@ def request_otk(session: Session, email: str, password: str): detail="Invalid email or password", ) + if not account.activated: + logger.warning("OTK request rejected for deactivated account %s", account.id) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is deactivated and cannot log in.", + ) + otk_code = f"{secrets.randbelow(1_000_000):06d}" print(otk_code) @@ -236,7 +248,7 @@ def request_otk(session: Session, email: str, password: str): else: logger.info("OTK generated for account %s", account.id) - return {"status": "ok", "account_id": str(account.id)} + return OtkResponse(status="success", account_id=account.id) def login( @@ -300,7 +312,7 @@ def login( ) account = _get_active_account(session, account_id) - if not account or account.deleted or account.id is None: + if not account or account.deleted or not account.activated or account.id is None: logger.warning("Login failed: account is not active %s", account_id) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -320,9 +332,9 @@ def login( def _get_current_user_access_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> AccessToken: + secure_fgp: Annotated[str | None, Cookie(alias=ACCESS_FP_COOKIE_KEY)] = None, +) -> AccessTokenMetadata: """Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -333,18 +345,22 @@ def _get_current_user_access_token_payload( Returns: AccessToken: The verified access token payload. """ + if secure_fgp is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Access fingerprint cookie is missing", + ) token = credentials.credentials - access_token_payload = _verify_fp_token( - request=request, - cookie_key=ACT_FP_COOKIE_KEY, - token=token, + access_token_payload = _verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=token, session=session, ) # If reaches here, the access token is valid and the fingerprint matches - return AccessToken( + return AccessTokenMetadata( real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( @@ -356,15 +372,13 @@ def _get_current_user_access_token_payload( access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] ), user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) def _get_current_user_refresh_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> RefreshToken: + token: Annotated[str | None, Cookie(alias=REFRESH_TOKEN_COOKIE_KEY)] = None, +) -> RefreshTokenMetadata: """Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -373,18 +387,20 @@ def _get_current_user_refresh_token_payload( credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token. Returns: - RefreshToken: The verified refresh token payload. + RefreshTokenData: The verified refresh token payload. """ - token = credentials.credentials + if token is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Refresh token cookie is missing", + ) - refresh_token_payload = _verify_fp_token( - request=request, - cookie_key=ACT_FP_COOKIE_KEY, - token=token, + refresh_token_payload = _verify_refresh_token( + raw_refresh_token=token, session=session, ) # If reaches here, the refresh token is valid and the fingerprint matches - refresh_token = RefreshToken( + refresh_token = RefreshTokenMetadata( real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( @@ -395,8 +411,6 @@ def _get_current_user_refresh_token_payload( effective_organization_id=uuid.UUID( refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY] ), - user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) logger.debug("Extracted refresh token payload: %s", refresh_token) @@ -406,9 +420,8 @@ def _get_current_user_refresh_token_payload( def _get_current_user_id_token_payload( session: Annotated[Session, Depends(get_session)], - request: Request, - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], -) -> IdToken: + token: Annotated[str | None, Cookie(alias=ID_TOKEN_COOKIE_KEY)] = None, +) -> IdTokenMetadata: """Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. Args: @@ -419,30 +432,24 @@ def _get_current_user_id_token_payload( Returns: IdToken: The verified ID token payload. """ - logger.debug( - "Verifying ID token for request %s with credentials %s", - request.url, - credentials, - ) - token = credentials.credentials - logger.debug("Verifying ID token for request %s with token %s", request.url, token) + if token is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="ID token cookie is missing", + ) - id_token_payload = _verify_fp_token( - request=request, - cookie_key=ID_FP_COOKIE_KEY, - token=token, + id_token_payload = _verify_id_token( + raw_id_token=token, session=session, ) # If reaches here, the ID token is valid and the fingerprint matches - return IdToken( + return IdTokenMetadata( real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]), expires_at=datetime.datetime.fromtimestamp( id_token_payload["exp"], tz=datetime.timezone.utc ), epoch=id_token_payload[EPOCH_KEY], - user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY], - raw_token=token, ) @@ -469,7 +476,12 @@ def _get_account_epoch( """ account = session.get(Account, account_id) - if account is None or account.deleted or account.id is None: + if ( + account is None + or account.deleted + or not account.activated + or account.id is None + ): raise AccountNotFoundException return account.epoch @@ -487,7 +499,7 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole: """ account = session.get(Account, account_id) - if not account or account.deleted or account.id is None: + if not account or account.deleted or not account.activated or account.id is None: raise AccountNotFoundException return account.role @@ -505,7 +517,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U """ account = session.get(Account, account_id) - if not account or account.deleted or account.id is None: + if not account or account.deleted or not account.activated or account.id is None: raise AccountNotFoundException return account.organization_id @@ -525,12 +537,18 @@ def _is_valid_impersonation( bool: True if impersonation is allowed, False otherwise. """ real_account = session.get(Account, real_account_id) - if not real_account or real_account.deleted or real_account.id is None: + if ( + not real_account + or real_account.deleted + or not real_account.activated + or real_account.id is None + ): raise AccountNotFoundException effective_account = session.get(Account, effective_account_id) if ( not effective_account or effective_account.deleted + or not effective_account.activated or effective_account.id is None ): raise AccountNotFoundException @@ -560,26 +578,10 @@ def _is_valid_impersonation( def get_access_token( response: Response, session: Session, - id_token: IdToken, + id_token: IdTokenMetadata, real_account_id: uuid.UUID, effective_account_id: Optional[uuid.UUID] = None, ) -> AccessResponse: - """Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies. - - Args: - request (Request): The FastAPI request object containing the cookies. - response (Response): The FastAPI response object to which the cookies will be added. - id_token (str): The ID token to verify. - real_account_id (uuid.UUID): The unique identifier of the real account associated with this token. - effective_account_id (Optional[uuid.UUID], optional): The unique identifier of the effective account associated with this token. If not provided, it defaults to the real account ID. - - Raises: - HTTPException: If the ID token is invalid, expired, or does not match the real account ID. - HTTPException: If impersonation is not allowed. - - Returns: - AccessResponse: An object containing the generated access and refresh tokens. - """ # IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here. if real_account_id != id_token.real_account_id: @@ -594,16 +596,15 @@ def get_access_token( if effective_account_id is None: effective_account_id = real_account_id - elif effective_account_id != real_account_id: - if not _is_valid_impersonation( - session=session, - real_account_id=real_account_id, - effective_account_id=effective_account_id, - ): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Impersonation not allowed", - ) + elif effective_account_id != real_account_id and not _is_valid_impersonation( + session=session, + real_account_id=real_account_id, + effective_account_id=effective_account_id, + ): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Impersonation not allowed", + ) role = _get_account_role(session=session, account_id=effective_account_id) epoch = _get_account_epoch(account_id=effective_account_id, session=session) @@ -611,7 +612,7 @@ def get_access_token( session=session, account_id=effective_account_id ) - user_fingerprint_hash = _set_act_fp_cookie(response=response) + user_fingerprint_hash = _set_access_fp_cookie(response=response) access_token = _build_access_token( real_account_id=real_account_id, @@ -621,77 +622,96 @@ def get_access_token( epoch=epoch, user_fingerprint_hash=user_fingerprint_hash, ) - refresh_token = _build_refresh_token( + _set_refresh_token( + response=response, real_account_id=real_account_id, effective_account_id=effective_account_id, effective_role=role, effective_organization_id=organization_id, epoch=epoch, - user_fingerprint_hash=user_fingerprint_hash, ) return AccessResponse( access_token=access_token, - refresh_token=refresh_token, ) -def _set_id_fp_cookie(response: Response) -> str: - """Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint. +def _set_id_token_cookie(response: Response, raw_id_token: str) -> None: + """Sets a secure cookie for the ID token. Args: response (Response): The FastAPI response object to which the cookie will be added. - - Returns: - str: The hashed value of the fingerprint. + raw_id_token (str): The raw string representation of the ID token. """ - return _set_fingerprint_cookie( - response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 + _set_token_cookie( + response=response, + cookie_name=ID_TOKEN_COOKIE_KEY, + token=raw_id_token, + max_age=ID_TOKEN_EXPIRATION_MINUTES * 60, ) -def _set_act_fp_cookie(response: Response) -> str: +def _set_refresh_token_cookie(response: Response, raw_refresh_token: str) -> None: + """Sets a secure cookie for the refresh token. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + raw_refresh_token (str): The raw string representation of the refresh token. + """ + _set_token_cookie( + response=response, + cookie_name=REFRESH_TOKEN_COOKIE_KEY, + token=raw_refresh_token, + max_age=REFRESH_TOKEN_EXPIRATION_MINUTES * 60, + ) + + +def _set_token_cookie( + response: Response, cookie_name: str, token: str, max_age: int +) -> None: + """Sets a secure cookie for the specified token. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + cookie_name (str): The name of the cookie to set. + token (str): The raw string representation of the token. + max_age (int): The maximum age of the cookie in seconds. + """ + secure = False if settings.environment == "dev" else True + response.set_cookie( + key=cookie_name, + value=token, + httponly=True, + secure=secure, + samesite="strict", + max_age=max_age, + ) + + +def _set_access_fp_cookie(response: Response) -> str: """Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint. Args: response (Response): The FastAPI response object to which the cookie will be added. - Returns: - str: The hashed value of the fingerprint. - """ - return _set_fingerprint_cookie( - response, ACT_FP_COOKIE_KEY - ) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. - - -def _set_fingerprint_cookie( - response: Response, - key: Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"], - max_age: Optional[int] = None, -) -> str: - """Sets a secure fingerprint cookie and returns the hashed value of the fingerprint. - - Args: - response (Response): The FastAPI response object to which the cookie will be added. - key (Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"]): The name of the cookie to set. - max_age (Optional[int], optional): The maximum age of the cookie in seconds. Defaults to None. - Returns: str: The hashed value of the fingerprint. """ user_fingerprint = secrets.token_hex(50) secure = False if settings.environment == "dev" else True response.set_cookie( - key=key, + key=ACCESS_FP_COOKIE_KEY, value=user_fingerprint, httponly=True, secure=secure, samesite="strict", - max_age=max_age, + max_age=None, # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. ) return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() -def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: +def refresh_access_token( + response: Response, refresh_token: RefreshTokenMetadata +) -> AccessToken: """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. Args: @@ -704,25 +724,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> AccessToken: """ # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. - return _refresh_access_token( - refresh_token=refresh_token, - ) - - -def _refresh_access_token( - refresh_token: RefreshToken, -) -> AccessToken: - """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. - - Args: - request (Request): The FastAPI request object containing the cookies. - refresh_token (RefreshToken): The refresh token to verify. - current_user_epoch (int): The epoch value for the tokens. - - Returns: - AccessToken: The refreshed access token. - """ - # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here. + user_fingerprint_hash = _set_access_fp_cookie(response=response) return _build_access_token( real_account_id=refresh_token.real_account_id, @@ -730,7 +732,7 @@ def _refresh_access_token( effective_role=refresh_token.effective_role, effective_organization_id=refresh_token.effective_organization_id, epoch=refresh_token.epoch, - user_fingerprint_hash=refresh_token.user_fingerprint_hash, + user_fingerprint_hash=user_fingerprint_hash, ) @@ -738,7 +740,7 @@ def _build_id_token( response: Response, real_account_id: uuid.UUID, epoch: int, -) -> IdToken: +) -> IdTokenMetadata: """Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie. Args: @@ -753,34 +755,31 @@ def _build_id_token( expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( minutes=ID_TOKEN_EXPIRATION_MINUTES ) - user_fingerprint_hash = _set_id_fp_cookie(response) payload = { REAL_ACCOUNT_ID_KEY: str(real_account_id), EPOCH_KEY: epoch, - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } raw_token = _build_token( payload=payload, expiration_datetime=expires_at, token_type=TokenType.ID_TOKEN, ) - return IdToken( + _set_id_token_cookie(response=response, raw_id_token=raw_token) + return IdTokenMetadata( real_account_id=real_account_id, expires_at=expires_at, epoch=epoch, - user_fingerprint_hash=user_fingerprint_hash, - raw_token=raw_token, ) -def _build_refresh_token( +def _set_refresh_token( + response: Response, real_account_id: uuid.UUID, effective_account_id: uuid.UUID, effective_role: UserRole, effective_organization_id: uuid.UUID, epoch: int, - user_fingerprint_hash: str, -) -> RefreshToken: +) -> RefreshTokenMetadata: """Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. Args: @@ -793,7 +792,7 @@ def _build_refresh_token( user_fingerprint_hash (str): The hashed value of the user's fingerprint. Returns: - RefreshToken: The generated refresh token object. + RefreshTokenMetadata: The generated refresh token object. """ expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( minutes=REFRESH_TOKEN_EXPIRATION_MINUTES @@ -804,7 +803,6 @@ def _build_refresh_token( EFFECTIVE_ROLE_KEY: effective_role.value, EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id), EPOCH_KEY: epoch, - USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, } raw_token = _build_token( @@ -812,16 +810,14 @@ def _build_refresh_token( expiration_datetime=expires_at, token_type=TokenType.REFRESH_TOKEN, ) - - return RefreshToken( + _set_refresh_token_cookie(response=response, raw_refresh_token=raw_token) + return RefreshTokenMetadata( real_account_id=real_account_id, effective_account_id=effective_account_id, expires_at=expires_at, epoch=epoch, effective_role=effective_role, effective_organization_id=effective_organization_id, - user_fingerprint_hash=user_fingerprint_hash, - raw_token=raw_token, ) @@ -908,18 +904,57 @@ def _build_token( return token -def _verify_fp_token( - request: Request, - cookie_key: str, - token: str, - session: Session, -) -> Dict[str, Any]: - """Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid. +def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]: + """Verifies the provided ID token and returns the decoded payload if valid. Args: - request (Request): The FastAPI request object containing the cookies. - cookie_key (str): The name of the cookie that contains the fingerprint. - token (str): The JWT token to verify. + raw_id_token (str): The JWT ID token to verify. + session (Session): The database session. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT ID token if verification is successful. + """ + payload = _extract_valid_token_payload(session, raw_id_token) + return payload + + +def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]: + """Verifies the provided refresh token and returns the decoded payload if valid. + + Args: + raw_refresh_token (str): The JWT refresh token to verify. + session (Session): The database session. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT refresh token if verification is successful. + """ + payload = _extract_valid_token_payload(session, raw_refresh_token) + return payload + + +def _verify_access_token_fp( + secure_fgp: str, + raw_access_token: str, + session: Session, +) -> Dict[str, Any]: + """Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid. + + Args: + secure_fgp (str): The secure fingerprint value. + raw_access_token (str): The JWT token to verify. + session (Session): The database session. Raises: ValueError: If the token HMAC key is not set in the configuration. @@ -931,19 +966,29 @@ def _verify_fp_token( Returns: Dict[str, Any]: The decoded payload of the JWT token if verification is successful. """ - if not settings.token_hmac_key: - raise ValueError("Token HMAC key is not set in the configuration.") - - secure_fgp = request.cookies.get(cookie_key) - if not secure_fgp: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Fingerprint cookie missing", - ) fingerprint_bytes = secure_fgp.encode("utf-8") expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest() + payload = _extract_valid_token_payload(session, raw_access_token) + + token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) + if ( + not token_fingerprint_hash + or token_fingerprint_hash != expected_fingerprint_hash + ): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid context fingerprint", + ) + + return payload + + +def _extract_valid_token_payload(session: Session, token: str): + if not settings.token_hmac_key: + raise ValueError("Token HMAC key is not set in the configuration.") + try: payload = jwt.decode( token, @@ -952,23 +997,12 @@ def _verify_fp_token( issuer=settings.token_issuer_id, ) - token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) - if ( - not token_fingerprint_hash - or token_fingerprint_hash != expected_fingerprint_hash - ): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid context fingerprint", - ) - real_account_id = payload.get(REAL_ACCOUNT_ID_KEY) if not real_account_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing real account ID", ) - epoch_account_id = uuid.UUID(real_account_id) effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY) @@ -980,6 +1014,9 @@ def _verify_fp_token( account_id=epoch_account_id, ) + if uuid.UUID(real_account_id) != epoch_account_id: + _get_active_account(session, uuid.UUID(real_account_id)) + token_epoch = payload.get(EPOCH_KEY) if token_epoch is None or token_epoch != current_account_epoch: raise HTTPException( @@ -988,7 +1025,6 @@ def _verify_fp_token( ) return payload - except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -1016,7 +1052,12 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: """ account = session.get(Account, account_id) - if account is None or account.deleted or account.id is None: + if ( + account is None + or account.deleted + or not account.activated + or account.id is None + ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Account is not active.", @@ -1025,7 +1066,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: return account -def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: +def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]: """Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account. Args: @@ -1049,7 +1090,7 @@ def logout(session: Session, access_token: AccessToken) -> Dict[str, str]: def change_password( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, current_password: str, new_password: str, ) -> Dict[str, str]: @@ -1071,15 +1112,31 @@ def change_password( account = _get_active_account(session, access_token.effective_account_id) if not _verify_password(current_password, account.password_hash): + logger.warning( + "Password change failed: current password is incorrect for account %s", + account.id, + ) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Current password is incorrect.", ) + if current_password == new_password: + logger.warning( + "Password change failed: new password is the same as the current password for account %s", + account.id, + ) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="New password cannot be the same as the current password.", + ) + account.password_hash = _hash_password(new_password) account.epoch += 1 session.add(account) session.commit() + logger.info("Password changed successfully for account %s", account.id) + return {"status": "ok"} diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 7db19bb4..728a61ee 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -14,9 +14,10 @@ from inse.auth.model import ( Account, Organization, Secret, - IdToken, AccessToken, - RefreshToken, + IdTokenMetadata, + AccessTokenMetadata, + RefreshTokenMetadata, UserRole, ) @@ -61,6 +62,19 @@ def create_org_and_account( return org, acc +def _get_cookie_value(response: Response, cookie_name: str) -> str: + for header_name, header_value in getattr(response, "raw_headers", []): + if header_name.lower() == b"set-cookie": + cookie_header = header_value.decode("latin-1") + if cookie_header.startswith(f"{cookie_name}="): + return cookie_header.split(";", 1)[0].split("=", 1)[1] + + header = response.headers.get("set-cookie") + assert header is not None + assert header.startswith(f"{cookie_name}=") + return header.split(";", 1)[0].split("=", 1)[1] + + def test_hash_and_verify_password(): pw = "s3cret-password" h = auth_service._hash_password(pw) @@ -80,8 +94,8 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): assert acc.id is not None resp = auth_service.request_otk(in_memory_session, email, password) - assert resp["status"] == "ok" - assert resp["account_id"] == str(acc.id) + assert resp.status == "success" + assert resp.account_id == acc.id secret = in_memory_session.exec( select(Secret).where(Secret.account_id == acc.id) @@ -93,9 +107,12 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): login_result = auth_service.login( in_memory_session, response, acc.id, secret.secret_value ) - assert isinstance(login_result.id_token, IdToken) + assert isinstance(login_result.id_token, IdTokenMetadata) assert login_result.id_token.real_account_id == acc.id - assert login_result.id_token.user_fingerprint_hash is not None + + raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY) + payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session) + assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): @@ -108,35 +125,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - assert isinstance(id_token, IdToken) + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) + assert isinstance(access_token, AccessToken) - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - assert cookie_header is not None - cookie_value = cookie_header.split("=")[1].split(";")[0] - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - - req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}) - payload = auth_service._verify_fp_token( - request=req, - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + payload = auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=access_token.raw_token, session=in_memory_session, ) assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) with pytest.raises(Exception): - auth_service._verify_fp_token( - request=DummyReq({}), - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="bad-fingerprint", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -158,11 +169,30 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): access_response = auth_service.get_access_token( response, in_memory_session, id_token, acc.id ) - assert isinstance(access_response.access_token, AccessToken) - assert isinstance(access_response.refresh_token, RefreshToken) + assert isinstance(access_response.access_token, AccessTokenMetadata) - refreshed = auth_service.refresh_access_token(access_response.refresh_token) - assert isinstance(refreshed, AccessToken) + raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + refresh_payload = auth_service._verify_refresh_token( + raw_refresh_token=raw_refresh_token, + session=in_memory_session, + ) + refresh_token = RefreshTokenMetadata( + real_account_id=uuid.UUID(refresh_payload[auth_service.REAL_ACCOUNT_ID_KEY]), + effective_account_id=uuid.UUID( + refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY] + ), + expires_at=_dt.datetime.fromtimestamp( + refresh_payload["exp"], tz=_dt.timezone.utc + ), + epoch=refresh_payload[auth_service.EPOCH_KEY], + effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]), + effective_organization_id=uuid.UUID( + refresh_payload[auth_service.EFFECTIVE_ORGANIZATION_ID_KEY] + ), + ) + + refreshed = auth_service.refresh_access_token(Response(), refresh_token) + assert isinstance(refreshed, AccessTokenMetadata) assert refreshed.real_account_id == access_response.access_token.real_account_id @@ -210,6 +240,36 @@ def test_request_otk_invalid_credentials(in_memory_session, settings_backup): auth_service.request_otk(in_memory_session, email, "wrongpw") +def test_deactivated_account_cannot_request_otk(in_memory_session): + email = "inactive@example.com" + password = "rightpw" + _, account = create_org_and_account(in_memory_session, email, password) + account.activated = False + in_memory_session.add(account) + in_memory_session.commit() + + with pytest.raises(HTTPException) as error: + auth_service.request_otk(in_memory_session, email, password) + + assert error.value.status_code == 403 + assert error.value.detail == "Account is deactivated and cannot log in." + + +def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_session): + _, account = create_org_and_account( + in_memory_session, "inactive-lookup@example.com", "password" + ) + account.activated = False + in_memory_session.add(account) + in_memory_session.commit() + + assert account.id is not None + with pytest.raises(HTTPException) as error: + auth_service._get_active_account(in_memory_session, account.id) + + assert error.value.status_code == 403 + + def test_login_with_expired_secret(in_memory_session, settings_backup): config_module.settings.token_hmac_key = "expired-key" config_module.settings.token_issuer_id = "expired-issuer" @@ -239,24 +299,20 @@ def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="badcookie", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -271,28 +327,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) - - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies + secure_fgp_hash = auth_service._set_access_fp_cookie(response) + secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp_hash, + ) acc.epoch += 1 in_memory_session.add(acc) in_memory_session.commit() with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=id_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -307,25 +360,21 @@ def test_invalid_token_signature_raises(in_memory_session, settings_backup): assert acc.id is not None response = Response() - id_token = auth_service._build_id_token(response, acc.id, acc.epoch) + secure_fgp = auth_service._set_access_fp_cookie(response) + access_token = auth_service._build_access_token( + real_account_id=acc.id, + effective_account_id=acc.id, + effective_role=acc.role, + effective_organization_id=acc.organization_id, + epoch=acc.epoch, + user_fingerprint_hash=secure_fgp, + ) - cookie_header = None - for header, value in response.headers.items(): - if header.lower() == "set-cookie": - cookie_header = value - break - cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore - - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - - bad_token = id_token.raw_token + "x" + bad_token = access_token.raw_token + "x" with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=bad_token, + auth_service._verify_access_token_fp( + secure_fgp=secure_fgp, + raw_access_token=bad_token, session=in_memory_session, ) @@ -362,7 +411,7 @@ def test_impersonation_rules(in_memory_session, settings_backup): real_acc.id, effective_account_id=eff_acc.id, ) - assert isinstance(access_resp.access_token, AccessToken) + assert isinstance(access_resp.access_token, AccessTokenMetadata) def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): @@ -396,7 +445,7 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup): login_res = auth_service.login( in_memory_session, Response(), acc.id, secret2.secret_value ) - assert isinstance(login_res.id_token, IdToken) + assert isinstance(login_res.id_token, IdTokenMetadata) def test_otk_deleted_after_login(in_memory_session, settings_backup): @@ -432,7 +481,7 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup): assert acc.id is not None response = Response() - raw = auth_service._set_act_fp_cookie(response) + raw_hash = auth_service._set_access_fp_cookie(response) access_token = auth_service._build_access_token( real_account_id=acc.id, @@ -440,18 +489,13 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup): effective_role=acc.role, effective_organization_id=acc.organization_id, epoch=acc.epoch, - user_fingerprint_hash=raw, + user_fingerprint_hash=raw_hash, ) - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore - cookie_key=auth_service.ACT_FP_COOKIE_KEY, - token=access_token.raw_token, + auth_service._verify_access_token_fp( + secure_fgp="wrongcookie", + raw_access_token=access_token.raw_token, session=in_memory_session, ) @@ -466,34 +510,26 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup): assert acc.id is not None response = Response() - cookie_raw = auth_service._set_id_fp_cookie(response) past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5) + access_fingerprint_hash = auth_service._set_access_fp_cookie(response) payload = { auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EFFECTIVE_ACCOUNT_ID_KEY: str(acc.id), + auth_service.EFFECTIVE_ROLE_KEY: acc.role.value, + auth_service.EFFECTIVE_ORGANIZATION_ID_KEY: str(acc.organization_id), auth_service.EPOCH_KEY: acc.epoch, - auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw, + auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash, } bad_token = auth_service._build_token( payload=payload, expiration_datetime=past, - token_type=auth_service.TokenType.ID_TOKEN, + token_type=auth_service.TokenType.ACCESS_TOKEN, ) - class DummyReq: - def __init__(self, cookies): - self.cookies = cookies - with pytest.raises(HTTPException): - auth_service._verify_fp_token( - request=DummyReq( - { - auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"] - .split("=")[1] - .split(";")[0] - } - ), # type: ignore - cookie_key=auth_service.ID_FP_COOKIE_KEY, - token=bad_token, + auth_service._verify_access_token_fp( + secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY), + raw_access_token=bad_token, session=in_memory_session, ) diff --git a/service/src/main/inse/database.py b/service/src/main/inse/database.py index 728b750f..39a7c24b 100644 --- a/service/src/main/inse/database.py +++ b/service/src/main/inse/database.py @@ -1,6 +1,7 @@ from typing import Annotated from fastapi import Depends +from sqlalchemy import inspect, text from sqlmodel import SQLModel, Session, create_engine from inse import config @@ -18,6 +19,15 @@ engine = create_engine( def create_db_and_tables(): """Creates the database and tables based on the SQLModel metadata.""" SQLModel.metadata.create_all(engine) + columns = {column["name"] for column in inspect(engine).get_columns("account")} + if "activated" not in columns: + with engine.begin() as connection: + connection.execute( + text( + "ALTER TABLE account ADD COLUMN activated " + "BOOLEAN NOT NULL DEFAULT TRUE" + ) + ) def get_session(): diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 6cf4ed22..39924953 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -1,25 +1,31 @@ from openai import OpenAI, APIConnectionError +from openai import AsyncOpenAI from .. import config - +from typing import Optional, Dict, Any def call( system_prompt: str, user_prompt: str, model: str = None, - timeout: int = 30, + json_schema = None, + schema_name = None, + timeout: int = 120, temperature: float = 1.0, top_p: float = 0.95, ) -> str: if model is None: model = config.settings.llm_model - + + response_format = None + if json_schema is not None: + response_format = _get_response_format(schema = json_schema,schema_name=schema_name) + client = OpenAI( base_url=config.settings.llm_api_url, api_key=config.settings.llm_api_key, timeout=timeout, ) - try: response = client.chat.completions.create( model=model, @@ -27,10 +33,10 @@ def call( {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], - temperature=temperature, top_p=top_p, extra_body={"top_k": 64}, + response_format=response_format ) except APIConnectionError: return "Etwas ist schiefgelaufen. Bitte versuche es später erneut." @@ -38,3 +44,73 @@ def call( return response.choices[0].message.content or ( "Etwas ist schiefgelaufen. Bitte versuche es erneut." ) + +def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str, Any]: + response_format = { + "type": "json_schema", + "json_schema": { + "name": schema_name or "response", + "strict": True, + "schema": schema, + }, + } + return response_format + + + + +async def call_stream( + system_prompt: str, + user_prompt: str, + emit, # EventCallback + model: str = None, + json_schema=None, + schema_name=None, + timeout: int = 120, + temperature: float = 1.0, + top_p: float = 0.95, +) -> str: + if model is None: + model = config.settings.llm_model + + response_format = None + if json_schema is not None: + response_format = _get_response_format(schema=json_schema, schema_name=schema_name) + + client = AsyncOpenAI( + base_url=config.settings.llm_api_url, + api_key=config.settings.llm_api_key, + timeout=timeout, + ) + + full_content = "" + try: + stream = await client.chat.completions.create( + model=model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ], + temperature=temperature, + top_p=top_p, + extra_body={"top_k": 64}, + response_format=response_format, + stream=True, + ) + + async for chunk in stream: + delta = chunk.choices[0].delta.content + if delta: + full_content += delta + await emit({"type": "llm_chunk", "content": delta}) + + except APIConnectionError as e: + print(f"Connection error: {e}") + return "" + except Exception as e: + import traceback + print(f"LLM streaming failed: {type(e).__name__}: {e}") + traceback.print_exc() + return "" + + return full_content \ No newline at end of file diff --git a/service/src/main/inse/keywords/__init__.py b/service/src/main/inse/keywords/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py new file mode 100644 index 00000000..d6ae4c97 --- /dev/null +++ b/service/src/main/inse/keywords/logic.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for persons / authors. +""" +import asyncio +from typing import Any, Dict, List + +import partial_json_parser +import json +import logging +import time +import httpx +from bs4 import BeautifulSoup +from pydantic import ValidationError +from typing import Awaitable, Callable +from inse.keywords.prompts import KeywordsPrompt +from inse.integrations import llm +from inse.keywords.model import ( + ExtractedKeywords, + ExtractedKeywordsLLM, + ExtractedKeywordsResponse, + KeywordEntry, + KeywordEntryWithTopic, + KeywordsWsEvent, +) +from inse.topics.logic import vector_search_topics_batch +logger = logging.getLogger(__name__) +EventCallback = Callable[[dict], Awaitable[None]] +LEVELS = ("broad_keywords", "coarse_grained", "fine_grained") + + +def _build_enriched_snapshot( + confirmed: Dict[str, List[KeywordEntryWithTopic]], +) -> ExtractedKeywords: + return ExtractedKeywords.model_validate( + {level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS} + ) + + +async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords: + confirmed: Dict[str, List[KeywordEntryWithTopic]] = { + level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)] + for level in LEVELS + } + + keywords: List[str] = [] + positions: List[tuple[str, int]] = [] + for level in LEVELS: + for idx, entry in enumerate(getattr(results, level)): + keywords.append(entry.keyword) + positions.append((level, idx)) + + if keywords: + matches = await vector_search_topics_batch(keywords=keywords, search_type="hybrid") + for (level, idx), match in zip(positions, matches.results): + confirmed[level][idx].topic_mapping = match + + return _build_enriched_snapshot(confirmed) + +async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywordsResponse: + """ + Extracts keywords from the given text or URL using a language model. + """ + start_time = time.time() + if mode == "url": + text = await _get_text_content(query) + system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT + + else: + system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT + text = query + + + user_prompt = f""" + Now analyze the following text and return ONLY the JSON object.\n""" + + if limit: + user_prompt +=f"Extract exactly {limit} keywords for each level (broad, coarse, fine) from the text below.\n" + + user_prompt += f"""Input:{text}""" + + keywords = llm.call( + system_prompt=system_prompt, + user_prompt=user_prompt, + json_schema = ExtractedKeywordsLLM.model_json_schema(), + schema_name = "extracted_keywords", + temperature=0.8, + top_p=0.95, + ) + keywords_json = json.loads(keywords) + validated = ExtractedKeywordsLLM.model_validate(keywords_json) + enriched = await _enrich_llm_keywords(validated) + + elapsed_time = time.time() - start_time + logger.info(f"Keyword extraction took {elapsed_time:.2f} seconds") + return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time) + + +async def _get_text_content(url: str) -> str: + """ + Fetches the HTML content from the given URL using httpx and extracts visible text. + """ + try: + headers = { + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/91.0.4472.124 Safari/537.36" + ) + } + async with httpx.AsyncClient(timeout=30.0) as client: + response = await client.get(url, headers=headers) + response.raise_for_status() + + soup = BeautifulSoup(response.text, "html.parser") + for element in soup(["script", "style"]): + element.decompose() + text = soup.get_text(separator=" ", strip=True) + text = " ".join(text.split()) + return text + + except httpx.HTTPError as e: + logger.error(f"HTTP error for {url}: {e}") + except Exception as e: + logger.error(f"Error processing {url}: {e}") + + +async def extract_keywords_stream( + query: str, + mode: str, + limit: int, + emit: EventCallback, +) -> ExtractedKeywordsResponse: + start_time = time.time() + timeout_seconds = 60 # configurable + await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump()) + + if mode == "url": + await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump()) + text = await _get_text_content(query) + await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump()) + system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT + else: + text = query + await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump()) + system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT + user_prompt = "\nNow analyze the following text and return ONLY the JSON object.\n" + if limit: + user_prompt += f"\nExtract exactly {limit} keywords for each level (broad, coarse, fine).\n" + user_prompt += f"\nInput:\n{text}" + + await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump()) + + LEVELS = ("broad_keywords", "coarse_grained", "fine_grained") + + # Holds only fully validated KeywordEntry dicts for each level + confirmed: Dict[str, List[Dict[str, Any]]] = {level: [] for level in LEVELS} + + async def emit_full_results() -> None: + """Attempt to build and validate the full ExtractedKeywordsLLM model and emit it.""" + # Build a dict with all three fields, using empty lists for missing ones + data = {level: confirmed.get(level, []) for level in LEVELS} + try: + validated = ExtractedKeywordsLLM.model_validate(data) + except ValidationError: + # Should not happen if all items are valid, but guard against it + return + await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump()) + + # adds completed keyword chunks to the confirmed dict and emits the full results when new valid items are found + async def on_chunk(event: Dict[str, Any]) -> None: + if event["type"] != "llm_chunk": + await emit(event) + return + + try: + partial = partial_json_parser.loads(event.get("_full_content", "")) + except Exception: + return + + if not isinstance(partial, dict): + return + + grew = False + + for level in LEVELS: + current = partial.get(level) or [] + idx = len(confirmed[level]) + + while idx < len(current): + raw_item = current[idx] + try: + validated_item = KeywordEntry.model_validate(raw_item) + except ValidationError: + break # item not complete yet + confirmed[level].append(validated_item.model_dump()) + idx += 1 + grew = True + + if grew: + await emit_full_results() + + # Accumulate full_content for incremental parsing + full_content_holder = {"value": ""} + + async def emit_wrapper(event: Dict[str, Any]) -> None: + if event["type"] == "llm_chunk": + full_content_holder["value"] += event["content"] + event = {**event, "_full_content": full_content_holder["value"]} + await on_chunk(event) + + try: + keywords = await asyncio.wait_for( + llm.call_stream( + system_prompt=system_prompt, + user_prompt=user_prompt, + json_schema=ExtractedKeywordsLLM.model_json_schema(), + schema_name="extracted_keywords", + temperature=0.8, + top_p=0.95, + emit=emit_wrapper, + ), + timeout=timeout_seconds, + ) + except asyncio.TimeoutError: + await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump()) + raise RuntimeError("LLM streaming call timed out") + except asyncio.CancelledError: + await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump()) + raise + + if not keywords: + await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump()) + raise RuntimeError("LLM streaming call returned empty content") + + await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump()) + + try: + keywords_json = json.loads(keywords) + except json.JSONDecodeError as e: + await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump()) + raise RuntimeError("LLM response is not valid JSON") + + # Final emission of the full results (in case the last chunk didn't trigger it) + final_data = {level: confirmed.get(level, []) for level in LEVELS} + try: + final_validated = ExtractedKeywordsLLM.model_validate(keywords_json) + except ValidationError: + # Fallback: use our confirmed data + final_validated = ExtractedKeywordsLLM.model_validate(final_data) + + elapsed_time = time.time() - start_time + result = ExtractedKeywordsResponse( + results=final_validated, + source=mode, + source_url=query if mode == "url" else None, + source_content=text, + duration=elapsed_time, + ) + + return result + + +async def extract_keywords_stream_enriched( + query: str, + mode: str, + limit: int, + emit: EventCallback, +) -> ExtractedKeywordsResponse: + start_time = time.time() + timeout_seconds = 120 + await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump()) + + if mode == "url": + await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump()) + text = await _get_text_content(query) + await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump()) + system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT + else: + text = query + await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump()) + system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT + + user_prompt = "\nNow analyze the following text.\n" + if limit: + user_prompt += f"\nExtract exactly {limit} keywords for each level.\n" + user_prompt += f"\nInput:\n{text}" + + await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump()) + + LEVELS = ("broad_keywords", "coarse_grained", "fine_grained") + + # Holds enriched keyword wrappers for each level + confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS} + + # Track background enrichment tasks + enrichment_tasks: List[asyncio.Task] = [] + + async def emit_full_results() -> None: + """Attempt to build and emit the full enriched keyword model.""" + try: + validated = _build_enriched_snapshot(confirmed) + except ValidationError: + return + await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump()) + + async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None: + """ + Fetch/enrich metadata for a single keyword. + Runs concurrently without blocking the LLM stream. + """ + try: + topic = await vector_search_topics_batch( + keywords=[item.keyword], + search_type="hybrid", + ) + # Update the shared confirmed list in-place (safe in asyncio) + confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None + + # Emit the full updated set after each enrichment so the frontend sees progress. + await emit_full_results() + + except asyncio.CancelledError: + # If the whole request is cancelled, we can just re-raise + raise + except Exception as e: + logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}") + await emit_full_results() + + # ---------- on_chunk: parses LLM stream and appends new keywords ---------- + async def on_chunk(event: Dict[str, Any]) -> None: + if event["type"] != "llm_chunk": + await emit(event) + return + + try: + partial = partial_json_parser.loads(event.get("_full_content", "")) + except Exception: + return + + if not isinstance(partial, dict): + return + + grew = False + + for level in LEVELS: + current = partial.get(level) or [] + start_idx = len(confirmed[level]) # Where we start appending + + while len(confirmed[level]) < len(current): + raw_item = current[len(confirmed[level])] + try: + validated_item = KeywordEntry.model_validate(raw_item) + except ValidationError: + break # item not complete yet + + confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item)) + grew = True + + # Launch openalex topic mapping + for idx in range(start_idx, len(confirmed[level])): + keyword_text = confirmed[level][idx].llm_keyword.keyword + await emit( + KeywordsWsEvent( + type="status", + step="enriching", + message=f"Extracting topic for keyword '{keyword_text}'", + ).model_dump() + ) + task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword)) + enrichment_tasks.append(task) + + if grew: + await emit_full_results() + + # ---------- Accumulate full_content for incremental parsing ---------- + full_content_holder = {"value": ""} + + async def emit_wrapper(event: Dict[str, Any]) -> None: + if event["type"] == "llm_chunk": + full_content_holder["value"] += event["content"] + event = {**event, "_full_content": full_content_holder["value"]} + await on_chunk(event) + + # ---------- Call the LLM ---------- + try: + keywords = await asyncio.wait_for( + llm.call_stream( + system_prompt=system_prompt, + user_prompt=user_prompt, + json_schema=ExtractedKeywordsLLM.model_json_schema(), + schema_name="extracted_keywords", + temperature=0.0, + top_p=0.95, + emit=emit_wrapper, + ), + timeout=timeout_seconds, + ) + except asyncio.TimeoutError: + await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump()) + raise RuntimeError("LLM streaming call timed out") + except asyncio.CancelledError: + # Cancel all pending enrichment tasks to avoid dangling background work + for task in enrichment_tasks: + task.cancel() + if enrichment_tasks: + await asyncio.gather(*enrichment_tasks, return_exceptions=True) + await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump()) + raise + + # ---------- Finalize ---------- + await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump()) + + try: + keywords_json = json.loads(keywords) + except json.JSONDecodeError as e: + await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump()) + raise RuntimeError("LLM response is not valid JSON") + + # ---------- Wait for ALL pending enrichments to complete ---------- + if enrichment_tasks: + await asyncio.gather(*enrichment_tasks, return_exceptions=True) + + await emit_full_results() + + # Build final response + try: + final_validated = _build_enriched_snapshot(confirmed) + except ValidationError: + final_validated = ExtractedKeywords.model_validate( + {level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS} + ) + + elapsed_time = time.time() - start_time + result = ExtractedKeywordsResponse( + results=final_validated, + source=mode, + source_url=query if mode == "url" else None, + source_content=text, + duration=elapsed_time, + ) + + return result \ No newline at end of file diff --git a/service/src/main/inse/keywords/model.py b/service/src/main/inse/keywords/model.py new file mode 100644 index 00000000..d2c9239e --- /dev/null +++ b/service/src/main/inse/keywords/model.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Data models for persons / authors. +""" +from typing import List, Literal + +from pydantic import BaseModel, Field + +from inse.topics.model import KeywordTopicMatch +class KeywordsRequest(BaseModel): + query: str = Field(description="The input text from which to extract keywords.") + mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.") + limit: int = Field(default=None, description="The maximum number of keywords to extract.") + +class KeywordEntry(BaseModel): + keyword: str = Field(description="The extracted keyword.") + relevance_score: float = Field(description="The relevance score of the keyword.") + +class KeywordEntryWithTopic(BaseModel): + llm_keyword: KeywordEntry = Field(description="The keyword extracted by the LLM.") + topic_mapping: KeywordTopicMatch | None = Field( + default=None, + description="The corresponding OpenAlex topic match for the keyword, if any.", + ) + +class ExtractedKeywords(BaseModel): + broad_keywords: List[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.") + coarse_grained: List[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.") + fine_grained: List[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.") + +class ExtractedKeywordsLLM(BaseModel): + broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.") + coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.") + fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.") + +class ExtractedKeywordsResponse(BaseModel): + results_llm: ExtractedKeywordsLLM | None = None + results: ExtractedKeywords | None = None + source: str = Field(description="The source of the input text, e.g., 'url', 'text', or 'keywords'.") + source_url: str | None = Field(default=None, description="The URL from which keywords were extracted, if applicable.") + source_content: str = Field(description="The actual content from which keywords were extracted.") + duration: float | None = Field(default=None, description="The time taken to extract keywords, in seconds.") + +class KeywordsWsEvent(BaseModel): + type: str + step: str | None = None + message: str | None = None + result: ExtractedKeywordsResponse | None = None + keywords: ExtractedKeywords | ExtractedKeywordsLLM | None = None + duration: float | None = None + completed: str | None = None + \ No newline at end of file diff --git a/service/src/main/inse/keywords/prompts.py b/service/src/main/inse/keywords/prompts.py new file mode 100644 index 00000000..f60c8fc3 --- /dev/null +++ b/service/src/main/inse/keywords/prompts.py @@ -0,0 +1,469 @@ +from enum import StrEnum +class KeywordsPrompt(StrEnum): + EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst. + + Your task is to extract keywords from a given text and organize them into three hierarchical levels suitable for technology scouting, innovation discovery, scientific literature search, and OpenAlex-based research retrieval. + + The extracted keywords should prioritize: + + * Scientific domains + * Technologies + * Research fields + * Methods + * Applications + * Materials + * Standards + * Diseases + * Industrial sectors + * Technical concepts + + Avoid generic business terms unless they are core topics of the text. + + Examples of terms to avoid: + + * Solution + * Platform + * Improvement + * Capability + * Innovation + * Process + * Service + * Performance + * Efficiency + + unless they represent an actual searchable concept. + + --- + + # Keyword Hierarchy + + ## 1. broad_keywords + + High-level domains, disciplines, industries, or technology areas. + + Examples: + + * Artificial Intelligence + * Healthcare + * Biotechnology + * Renewable Energy + * Materials Science + * Robotics + + These should represent the major themes of the document. + + --- + + ## 2. coarse_grained + + Mid-level concepts, technologies, research areas, methods, or applications. + + Examples: + + * Machine Learning + * Drug Discovery + * Computer Vision + * Predictive Maintenance + * Smart Manufacturing + * Gene Editing + + These should provide more specific context within the broad domains. + + --- + + ## 3. fine_grained + + Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology. + + Examples: + + * Transformer Architecture + * CRISPR-Cas9 + * Retrieval-Augmented Generation + * Lithium Iron Phosphate + * YOLOv8 + * OPC UA + + These should be the most specific and actionable concepts for literature retrieval. + + --- + + # Relevance Score + + Each keyword must include a relevance score. + + Definition: + + * 1.0 = central concept of the text + * 0.9 = extremely important concept + * 0.8 = highly relevant concept + * 0.7 = important supporting concept + * 0.6 = relevant secondary concept + * below 0.6 = use sparingly + + Guidelines: + + * Scores must be between 0.0 and 1.0. + * Use decimal precision up to 3 digits. + * Rank keywords by importance. + * The most important keywords should appear first. + * Broad keywords generally receive higher scores than secondary topics. + * Only include keywords with meaningful relevance. + + --- + + # Extraction Rules + + * Extract only concepts explicitly mentioned or strongly implied. + * Prefer noun phrases. + * Avoid complete sentences. + * Avoid duplicates across levels whenever possible. + * Do not invent technologies not supported by the text. + * Prefer terminology that can be searched in scientific literature databases such as OpenAlex. + * Return between 5 and 15 keywords per level when sufficient information exists. + + --- + + # Output Schema + + Return ONLY valid JSON. + + + --- + + # Example 1 + + Input: + + Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories. + + Output: + + {"broad_keywords":[{"keyword":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]} + + --- + + # Example 2 + + Input: + + A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making. + + Output: + + {"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]} + Return ONLY valid JSON matching the schema provided by the API. + """ + + + EXTRACT_WEBSITE_KEYWORDS_PROMPT = """ + You are an expert technology scout, scientific analyst, and innovation intelligence specialist. + + The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser. + + The extracted text may contain: + + * Navigation menus + * Headers and footers + * Cookie notices + * Marketing language + * Contact information + * Repeated sections + * Calls to action + * Legal disclaimers + * Product pages + * Blog articles + * News articles + * Landing pages + + Your first task is to identify the actual content and purpose of the webpage. + + Ignore: + + * Navigation elements + * Cookie banners + * Legal notices + * Copyright text + * Generic marketing statements + * Contact information + * Login/signup content + * Careers pages unless they contain relevant technical information + * Repeated website boilerplate + + Focus only on content that helps identify: + + * Technologies + * Scientific concepts + * Research areas + * Technical methods + * Products + * Applications + * Industrial sectors + * Materials + * Standards + * Diseases + * Engineering disciplines + * Innovation domains + + --- + + # Step 1: Determine Page Type + + Determine which type of page is represented: + + * Technology/Product Page + * Company Page + * Research Article + * Scientific Blog Post + * News Article + * Technical Documentation + * White Paper + * Industry Report + * Other + + Use this classification internally only. + + Do not include it in the output. + + --- + + # Step 2: Extract Searchable Concepts + + Prioritize concepts that are useful for: + + * OpenAlex retrieval + * Scientific literature discovery + * Patent scouting + * Technology scouting + * Innovation monitoring + + Prefer canonical scientific terminology over marketing language. + + Examples: + + Prefer: + + * Large Language Models + + Instead of: + + * AI Assistant + + Prefer: + + * Smart Manufacturing + + Instead of: + + * Factory Optimization Solution + + Prefer: + + * Retrieval-Augmented Generation + + Instead of: + + * Intelligent Knowledge Assistant + + Prefer: + + * Predictive Maintenance + + Instead of: + + * Equipment Performance Optimization + + --- + + # Keyword Hierarchy + + ## broad_keywords + + High-level domains, industries, disciplines, or technology areas. + + Examples: + + * Artificial Intelligence + * Healthcare + * Manufacturing + * Energy Storage + * Biotechnology + * Robotics + + --- + + ## coarse_grained + + Technologies, methods, research fields, and applications. + + Examples: + + * Machine Learning + * Predictive Maintenance + * Drug Discovery + * Smart Manufacturing + * Computer Vision + * Clinical Decision Support + + --- + + ## fine_grained + + Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols. + + Examples: + + * Transformer Architecture + * CRISPR-Cas9 + * OPC UA + * Retrieval-Augmented Generation + * YOLOv8 + * Lithium Iron Phosphate + + --- + + # Relevance Score + + Assign a relevance score between 0.0 and 1.0. + + Guidelines: + + * 1.00 = central topic of the webpage + * 0.90 = major topic + * 0.80 = highly relevant + * 0.70 = supporting concept + * 0.60 = secondary concept + + Avoid scores below 0.60 unless necessary. + + --- + + # Additional Rules + + * Extract only concepts supported by the page content. + * Do not hallucinate technologies. + * Avoid generic company descriptions. + * Avoid generic business terminology. + * Prefer terminology suitable for scientific literature search. + * Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications. + * Remove duplicates across hierarchy levels whenever possible. + * Rank keywords by importance. + + --- + # Example 3 — News Article + + ## Input + + Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications. + + ## Output + + ```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}``` + + --- + + # Example 4 — Product Page + + ## Input + + The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support. + + ## Output + + ```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}``` + + --- + + # Example 5 — Technical Documentation + + ## Input + + FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models. + + ## Output + + ```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}``` + + --- + + # Example 6 — Company Website + + ## Input + + Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations. + + ## Output + + ```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}``` + + --- + + Return ONLY valid JSON matching the schema provided by the API. + """ + + SIMPLE_TEXT_PROMPT = """ +You are a scientific and technology intelligence expert. Extract keywords from the given text into three hierarchical levels. Each keyword must include a relevance_score (0.0–1.0) indicating centrality. + +**Levels:** +- **broad_keywords** – high‑level domains/industries (e.g., Artificial Intelligence, Healthcare, Renewable Energy). +- **coarse_grained** – mid‑level technologies/methods/applications (e.g., Machine Learning, Drug Discovery, Smart Manufacturing). +- **fine_grained** – specific technical concepts, algorithms, materials, protocols (e.g., Transformer Architecture, CRISPR‑Cas9, Retrieval‑Augmented Generation). + +**Guidelines:** +- Prioritize scientific, technical, and research‑oriented terminology. +- Avoid generic business fluff: "solution", "platform", "improvement", "service", "performance" – unless they are explicit searchable concepts. +- Prefer noun phrases; avoid complete sentences. +- Extract 5–15 keywords per level when possible. +- Rank by importance (higher scores first). + +**Relevance scores:** +- 1.0 = central topic +- 0.9 = extremely important +- 0.8 = highly relevant +- 0.7 = supporting concept +- 0.6 = secondary +- Below 0.6 – use sparingly. + +**Output schema (JSON only):** +{ + "broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...], + "coarse_grained": [...], + "fine_grained": [...] +} + +**Example:** +Input: Researchers developed a transformer-based ML framework for predictive maintenance in smart factories using sensor fusion and anomaly detection. +Output: +{ + "broad_keywords": [{"keyword": "Artificial Intelligence", "relevance_score": 0.98}, {"keyword": "Manufacturing", "relevance_score": 0.94}], + "coarse_grained": [{"keyword": "Predictive Maintenance", "relevance_score": 0.95}, {"keyword": "Anomaly Detection", "relevance_score": 0.85}], + "fine_grained": [{"keyword": "Transformer Architecture", "relevance_score": 0.95}, {"keyword": "Sensor Fusion", "relevance_score": 0.82}] +} + +Return ONLY the JSON object, nothing else. +""" + SIMPLE_WEBSITE_PROMPT = """ +You are a technology scout and scientific analyst. The input is text scraped from a webpage (using BeautifulSoup or similar). Your goal: extract keywords into three hierarchical levels, just like the text prompt, but with extra care to ignore website boilerplate. + +**Ignore:** +- Navigation menus, headers/footers, cookie banners, legal disclaimers, copyright notices. +- Generic marketing language, calls-to-action, contact details, login/signup content. +- Repeated site templates or boilerplate. + +**Focus only on:** +- Technologies, research areas, scientific methods, products, applications, industrial sectors, materials, standards, diseases, engineering disciplines, innovation domains. +- Prefer canonical scientific terms over marketing buzzwords (e.g., "Large Language Models" instead of "AI Assistant"). + +**Hierarchy and relevance scores** are the same as in the text prompt (broad → coarse → fine, scores 0.0–1.0). + +**Output schema (JSON only):** +'''{"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],"coarse_grained": [...],"fine_grained": [...]}''' + +**Example (company website):** +Input: Stripe provides payment infrastructure for businesses, supporting processing, billing, fraud prevention, and global commerce. +Output: +{"broad_keywords": [{"keyword": "Financial Technology", "relevance_score": 0.98}, {"keyword": "Business Services", "relevance_score": 0.91}],"coarse_grained": [{"keyword": "Payment Processing", "relevance_score": 0.97}, {"keyword": "Digital Payments", "relevance_score": 0.95}],"fine_grained": [{"keyword": "Stripe Platform", "relevance_score": 0.99}, {"keyword": "Fraud Prevention", "relevance_score": 0.91}]} + +**Return ONLY the JSON object, nothing else.** +- Nno leading/trailing spaces, newlines, or any text before or after. NO IDENTATION, justa stringified JSON +""" \ No newline at end of file diff --git a/service/src/main/inse/keywords/service.py b/service/src/main/inse/keywords/service.py new file mode 100644 index 00000000..ae207f1c --- /dev/null +++ b/service/src/main/inse/keywords/service.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for persons / authors. +""" + +import asyncio +from typing import Annotated + +from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect + +from . import logic +from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest + + +router = APIRouter( + prefix="/api/inse-service", + tags=["Keywords"], + responses={404: {"description": "Not found"}}, +) + +@router.websocket("/keywords/extract/ws") +async def extract_keywords_ws(websocket: WebSocket): + print("WebSocket connection established for keyword extraction.") + await websocket.accept() + try: + raw = await websocket.receive_json() + request = KeywordsRequest(**raw) + disconnected = asyncio.Event() + + async def emit(event: dict): + if disconnected.is_set(): + return + await websocket.send_json(event) + + async def watch_disconnect() -> None: + while True: + message = await websocket.receive() + if message["type"] == "websocket.disconnect": + disconnected.set() + return + + extraction_task = asyncio.create_task( + logic.extract_keywords_stream_enriched( + query=request.query, + mode=request.mode, + limit=request.limit, + emit=emit, + ) + ) + disconnect_task = asyncio.create_task(watch_disconnect()) + + done, pending = await asyncio.wait( + {extraction_task, disconnect_task}, + return_when=asyncio.FIRST_COMPLETED, + ) + + if disconnect_task in done: + disconnected.set() + extraction_task.cancel() + try: + await extraction_task + except asyncio.CancelledError: + pass + return + + disconnect_task.cancel() + try: + await disconnect_task + except asyncio.CancelledError: + pass + result = extraction_task.result() + + await websocket.send_json({"type": "completed", "result": result.model_dump()}) + + except WebSocketDisconnect: + print("WebSocket disconnected.") + pass + except Exception as e: + await websocket.send_json({"type": "error", "message": str(e)}) + finally: + if websocket.application_state.name != "DISCONNECTED": + await websocket.close() + +# @router.post( +# "/keywords/extract", +# operation_id="extractKeywords", +# response_model=ExtractedKeywordsResponse, +# ) +# async def extract_keywords( +# request: Annotated[ +# KeywordsRequest, +# Body(description="Input text for keyword extraction"), +# ], +# ): +# async def noop(_: dict): +# pass + +# return await logic.extract_keywords_stream( +# query=request.query, +# mode=request.mode, +# limit=request.limit, +# emit=noop, +# ) + +@router.post( + "/keywords/extract", + operation_id="extractKeywords", + response_model=ExtractedKeywordsResponse, + summary="Extracts keywords from text.", + response_model_exclude_none=True, +) +async def extract_keywords( + request: Annotated[ + KeywordsRequest, + Body(description="Input text for keyword extraction") + ], + +): + return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index d6e5a905..54a43096 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -33,6 +33,7 @@ from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router from inse.news.service import router as news_service_router from inse.patents.service import router as patents_service_router +from inse.keywords.service import router as keywords_service_router from inse.auth.router import router as auth_router from inse.account_management.router import router as account_management_router @@ -45,7 +46,12 @@ from inse.auth.service import create_predefined_accounts from . import config from .service import router as service_router -from inse.patents.service import router as patents_service_router, patents_router as patents_all_router +from inse.patents.org.service import router as org_patents_router +from inse.patents.service import ( + institution_patents_router, + patents_router as patents_all_router, + router as patents_service_router, +) logger = logging.getLogger(__name__) @@ -73,6 +79,8 @@ app = FastAPI( lifespan=lifespan, ) app.include_router(collaboration_network_router) +app.include_router(institution_patents_router) +app.include_router(org_patents_router) app.include_router(institutions_router) app.include_router(topics_service_router) app.include_router(works_service_router) @@ -84,6 +92,7 @@ app.include_router(patents_service_router) app.include_router(university_ranking_router) app.include_router(projects_router) app.include_router(patents_all_router) +app.include_router(keywords_service_router) app.include_router(service_router) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index db452b2e..222d9603 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -37,6 +37,7 @@ class ESIndex(StrEnum): EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" + ORG_PATENTS = "org_patents" PROJECTS_BUND_V1 = "projects_bund_v1" PROJECTS_DFG_ALL = "projects_dfg_all" diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py index 0a8b82ca..5a2db2bd 100644 --- a/service/src/main/inse/organization_management/router.py +++ b/service/src/main/inse/organization_management/router.py @@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Response, status from sqlmodel import Session from inse.auth import service as auth_service -from inse.auth.model import AccessToken +from inse.auth.model import AccessTokenMetadata from inse.database import get_session from inse.tags import Tags @@ -26,7 +26,7 @@ async def get_organizations( page_size: int = Query(default=25, ge=1, le=100), offset: Optional[int] = Query(default=None, ge=0), session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationPage: return service.get_organizations( session=session, @@ -46,7 +46,7 @@ async def get_organizations( async def create_organization( payload: CreateOrganizationRequest, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationProfile: return service.create_organization(session, access_token, payload) @@ -60,7 +60,7 @@ async def update_organization( organization_id: uuid.UUID, payload: UpdateOrganizationRequest, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> OrganizationProfile: return service.update_organization( session, access_token, organization_id, payload @@ -75,7 +75,7 @@ async def update_organization( async def delete_organization( organization_id: uuid.UUID, session: Session = Depends(get_session), - access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> Response: service.delete_organization(session, access_token, organization_id) return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 56d97db2..528bcf35 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -4,7 +4,7 @@ from typing import Optional from fastapi import HTTPException, status from sqlmodel import Session, func, select -from inse.auth.model import AccessToken, Account, Organization, UserRole +from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole from .model import ( CreateOrganizationRequest, @@ -14,7 +14,7 @@ from .model import ( ) -def _require_super_admin(access_token: AccessToken) -> None: +def _require_super_admin(access_token: AccessTokenMetadata) -> None: if access_token.effective_role != UserRole.SUPER_ADMIN: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -73,6 +73,7 @@ def _member_counts( .where( Account.organization_id.in_(organization_ids), Account.deleted == False, # noqa: E712 + Account.activated == True, # noqa: E712 ) .group_by(Account.organization_id) ).all() @@ -91,9 +92,24 @@ def _to_profile( ) +def _deactivate_organization_accounts( + session: Session, organization_id: uuid.UUID +) -> None: + accounts = session.exec( + select(Account).where( + Account.organization_id == organization_id, + Account.activated == True, # noqa: E712 + ) + ).all() + for account in accounts: + account.activated = False + account.epoch += 1 + session.add(account) + + def get_organizations( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, page: int, page_size: int, offset: Optional[int] = None, @@ -129,7 +145,7 @@ def get_organizations( def create_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, payload: CreateOrganizationRequest, ) -> OrganizationProfile: _require_super_admin(access_token) @@ -148,7 +164,7 @@ def create_organization( def update_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, organization_id: uuid.UUID, payload: UpdateOrganizationRequest, ) -> OrganizationProfile: @@ -162,6 +178,8 @@ def update_organization( if payload.other_inst_id is not None: organization.openalex_institution_id = payload.other_inst_id.strip() or None if payload.deleted is not None: + if payload.deleted and not organization.deleted: + _deactivate_organization_accounts(session, organization.id) organization.deleted = payload.deleted session.add(organization) @@ -173,11 +191,13 @@ def update_organization( def delete_organization( session: Session, - access_token: AccessToken, + access_token: AccessTokenMetadata, organization_id: uuid.UUID, ) -> None: _require_super_admin(access_token) organization = _get_organization_or_404(session, organization_id) + if not organization.deleted: + _deactivate_organization_accounts(session, organization.id) organization.deleted = True session.add(organization) session.commit() diff --git a/service/src/main/inse/organization_management/test_service.py b/service/src/main/inse/organization_management/test_service.py index ce3b3e03..a7ce6ff6 100644 --- a/service/src/main/inse/organization_management/test_service.py +++ b/service/src/main/inse/organization_management/test_service.py @@ -105,6 +105,66 @@ def test_superadmin_can_create_update_and_soft_delete(session): assert session.get(Organization, created.id).deleted is True +def test_deleting_organization_deactivates_all_its_accounts(session): + organization = Organization(name="Organization to delete") + session.add(organization) + session.flush() + active_account = Account( + email="active-delete@example.org", + name="Active", + password_hash="hash", + organization_id=organization.id, + epoch=3, + ) + inactive_account = Account( + email="inactive-delete@example.org", + name="Inactive", + password_hash="hash", + organization_id=organization.id, + activated=False, + epoch=5, + ) + session.add(active_account) + session.add(inactive_account) + session.commit() + + service.delete_organization( + session, token(UserRole.SUPER_ADMIN, organization.id), organization.id + ) + + session.refresh(active_account) + session.refresh(inactive_account) + assert active_account.activated is False + assert active_account.epoch == 4 + assert inactive_account.activated is False + assert inactive_account.epoch == 5 + + +def test_marking_organization_deleted_deactivates_its_accounts(session): + organization = Organization(name="Organization to update") + session.add(organization) + session.flush() + account = Account( + email="active-update@example.org", + name="Active", + password_hash="hash", + organization_id=organization.id, + ) + session.add(account) + session.commit() + + service.update_organization( + session, + token(UserRole.SUPER_ADMIN, organization.id), + organization.id, + UpdateOrganizationRequest(deleted=True), + ) + + session.refresh(account) + assert account.activated is False + assert account.epoch == 1 + + @pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER]) def test_only_superadmin_can_create_organizations(session, role): organization = Organization(name="Scope") diff --git a/service/src/main/inse/patents/all/__init__.py b/service/src/main/inse/patents/all/__init__.py new file mode 100644 index 00000000..9f21635b --- /dev/null +++ b/service/src/main/inse/patents/all/__init__.py @@ -0,0 +1 @@ +"""Global patent listing.""" diff --git a/service/src/main/inse/patents/all/logic.py b/service/src/main/inse/patents/all/logic.py new file mode 100644 index 00000000..f18b6a8d --- /dev/null +++ b/service/src/main/inse/patents/all/logic.py @@ -0,0 +1,85 @@ +"""Business logic for global patent listing.""" +import asyncio +from datetime import datetime +import httpx +from fastapi import HTTPException +from starlette.status import HTTP_404_NOT_FOUND +from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_503_SERVICE_UNAVAILABLE + +from inse.patents.common import model +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.common.parsing import ( + enrich_patents_classifications, + parse_epo_hits, + parse_uspto_hits, +) +from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.search_client import PatentSearchClient + +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", + year_from: int | None = None, + year_to: int | None = None, + 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, year_from, year_to) + ) + 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, year_from, year_to) + ) + 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, year_from, year_to) + ), + all_patents_client.search_uspto( + all_patents_client.uspto_query(page, half, search, sort_direction, year_from, year_to) + ), + ) + 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, + ) diff --git a/service/src/main/inse/patents/all/service.py b/service/src/main/inse/patents/all/service.py new file mode 100644 index 00000000..a620c93c --- /dev/null +++ b/service/src/main/inse/patents/all/service.py @@ -0,0 +1,35 @@ +"""Business logic for global patent listing.""" +from fastapi import APIRouter + +from inse.patents.all import logic +from inse.patents.common import model + +router = APIRouter(prefix="/api/inse-service", tags=["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", + year_from: int | None = None, + year_to: int | None = None, +): + return await logic.get_all_patents( + page=page, + size=size, + search=search, + source=source, + sort_by=sort_by, + sort_direction=sort_direction, + year_from=year_from, + year_to=year_to, + ) diff --git a/service/src/main/inse/patents/authors/__init__.py b/service/src/main/inse/patents/authors/__init__.py new file mode 100644 index 00000000..9fd61ab7 --- /dev/null +++ b/service/src/main/inse/patents/authors/__init__.py @@ -0,0 +1 @@ +"""Patent lookup by inventor.""" diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py new file mode 100644 index 00000000..0dc34be1 --- /dev/null +++ b/service/src/main/inse/patents/authors/logic.py @@ -0,0 +1,122 @@ +"""Business logic for patent lookup by inventor.""" +import asyncio +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 inse.patents.authors.name_matching import name_matches +from inse.patents.common import model +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.common.parsing import ( + deduplicate_patents, + enrich_patents_classifications, + parse_epo_hits, + parse_uspto_hits, +) +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.search_client import PatentSearchClient +from inse.persons import logic as person_logic +from inse.models.openalex.author import Author + +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): + return 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)), + ) + + +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 _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 diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py new file mode 100644 index 00000000..369c44ab --- /dev/null +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -0,0 +1,128 @@ +"""Inventor name normalization and matching.""" +import re + +from inse.patents.common.text_normalization import ( + name_token_variants, + normalize_name_part, + patent_transliteration_expansions, +) + + +def tokens_equal( + left: str | None, + right: str | None, + *, + allow_initial: bool = True, +) -> bool: + left_variants = name_token_variants(left) + right_variants = name_token_variants(right) + if not left_variants or not right_variants: + return False + if left_variants & right_variants: + return True + + if not allow_initial: + return False + + return _initial_tokens_match(left, right) + + +def _initial_letter(token: str | None) -> str | None: + normalized = normalize_name_part(token) + if len(normalized) == 1 and normalized.isalpha(): + return normalized + return None + + +def _initial_tokens_match(left: str | None, right: str | None) -> bool: + left_initial = _initial_letter(left) + right_initial = _initial_letter(right) + left_full = normalize_name_part(left) + right_full = normalize_name_part(right) + + if left_initial and right_full and len(right_full) > 1: + return right_full.startswith(left_initial) + if right_initial and left_full and len(left_full) > 1: + return left_full.startswith(right_initial) + if left_initial and right_initial: + return left_initial == right_initial + return False + + +def _inventor_first_token(inventor_name: str) -> str: + if "," in inventor_name: + _, first_part = [p.strip() for p in inventor_name.split(",", 1)] + return first_part.split()[0] if first_part else "" + parts = inventor_name.split() + return parts[0] if parts else "" + + +def first_name_match_kind( + inventor_name: str, + first_name: str, + last_name: str, +) -> str: + if not name_matches(inventor_name, first_name, last_name): + return "none" + + inventor_first = _inventor_first_token(inventor_name) + if tokens_equal(inventor_first, first_name, allow_initial=False): + return "full" + return "initial" + + +def search_name_variants(value: str | None) -> list[str]: + if not value or not value.strip(): + return [] + + seen: set[str] = set() + ordered: list[str] = [] + + def _add(candidate: str) -> None: + key = candidate.casefold() + if candidate.strip() and key not in seen: + seen.add(key) + ordered.append(candidate.strip()) + + _add(value.strip()) + + normalized = normalize_name_part(value) + if normalized: + _add(normalized.title()) + + for variant in name_token_variants(value): + _add(variant.title()) + + for variant in patent_transliteration_expansions(normalized): + _add(variant.title()) + + if normalized and len(normalized) > 1: + _add(normalized[0].upper()) + + return ordered + + +def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool: + if not inventor_name or not last_name: + return False + + name = inventor_name.strip() + + if "," in name: + last_part, first_part = [p.strip() for p in name.split(",", 1)] + first_token = first_part.split()[0] if first_part else "" + return ( + tokens_equal(last_part, last_name, allow_initial=False) + and bool(first_name) + and tokens_equal(first_token, first_name) + ) + + parts = name.split() + if len(parts) < 2: + return False + + return ( + tokens_equal(parts[-1], last_name, allow_initial=False) + and bool(first_name) + and tokens_equal(parts[0], first_name) + ) diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py new file mode 100644 index 00000000..2149fa98 --- /dev/null +++ b/service/src/main/inse/patents/authors/search_queries.py @@ -0,0 +1,130 @@ +"""Elasticsearch query builders for inventor-based patent search.""" +from typing import Any + +from inse.patents.authors.name_matching import search_name_variants +from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE + + +def _match_name_field(field: str, name: str) -> dict[str, Any]: + variants = search_name_variants(name) + if len(variants) <= 1: + return {"match": {field: variants[0] if variants else name}} + return { + "bool": { + "should": [{"match": {field: variant}} for variant in variants], + "minimum_should_match": 1, + } + } + + +class InventorSearchQueries: + def epo_query_by_inventor( + self, + last_name: str, + first_name: str | None = None, + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + if first_name: + query = { + "nested": { + "path": "inventors_name_nested", + "query": { + "bool": { + "must": [ + _match_name_field("inventors_name_nested.inventor", last_name), + _match_name_field("inventors_name_nested.inventor", first_name), + ] + } + }, + } + } + else: + query = { + "nested": { + "path": "inventors_name_nested", + "query": _match_name_field("inventors_name_nested.inventor", last_name), + } + } + + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"date_publication": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_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_by_inventor( + self, + last_name: str, + first_name: str | None = None, + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + if first_name: + query = { + "nested": { + "path": "inventors", + "query": { + "bool": { + "must": [ + _match_name_field("inventors.name", last_name), + _match_name_field("inventors.name", first_name), + ] + } + }, + } + } + else: + query = { + "nested": { + "path": "inventors", + "query": _match_name_field("inventors.name", last_name), + } + } + + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"publication_date": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": [ + "publication_number", + "country", + "publication_date", + "publication_year", + "application_number", + "application_date", + "application_type", + "title", + "abstract", + "inventors_names", + "assignees_orgs", + "ipcr", + "cpc", + "number_of_claims", + "status", + ], + "query": query, + } diff --git a/service/src/main/inse/patents/authors/service.py b/service/src/main/inse/patents/authors/service.py new file mode 100644 index 00000000..0872f669 --- /dev/null +++ b/service/src/main/inse/patents/authors/service.py @@ -0,0 +1,16 @@ +from fastapi import APIRouter + +from inse.patents.authors import logic +from inse.patents.common import model + +router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) + + +@router.get( + "/{author_id}/patents", + operation_id="getPatentsByAuthor", + response_model=model.PatentsByAuthorResponse, + 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) diff --git a/service/src/main/inse/patents/common/__init__.py b/service/src/main/inse/patents/common/__init__.py new file mode 100644 index 00000000..a9ef3c28 --- /dev/null +++ b/service/src/main/inse/patents/common/__init__.py @@ -0,0 +1 @@ +"""Shared patent infrastructure.""" diff --git a/service/src/main/inse/patents/common/elastic_search_client.py b/service/src/main/inse/patents/common/elastic_search_client.py new file mode 100644 index 00000000..ef20a25b --- /dev/null +++ b/service/src/main/inse/patents/common/elastic_search_client.py @@ -0,0 +1,56 @@ +"""Base HTTP client for patent Elasticsearch indices.""" +from typing import Any + +import httpx + +from ... import config + +EPO_INDEX = "epo_index_1.0" +USPTO_INDEX = "uspto_patents_3.0" +DEFAULT_SEARCH_SIZE = 100 + + +class MissingApiKeyError(Exception): + pass + + +class BasePatentSearchClient: + 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 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() diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py new file mode 100644 index 00000000..b3cc97a4 --- /dev/null +++ b/service/src/main/inse/patents/common/model.py @@ -0,0 +1,55 @@ +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): + patent_id: str + source: str + title: str | None = None + 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 + application_type: str | None = None + number_of_claims: int | None = None + status: str | None = None + 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 PatentsByInstitutionResponse(BaseModel): + institution_id: str + institution_name: str | None = None + patent_count: int + patents: list[PatentEntry] + + +class AllPatentsResponse(BaseModel): + total: int + page: int + size: int + patents: list[PatentEntry] diff --git a/service/src/main/inse/patents/common/parsing.py b/service/src/main/inse/patents/common/parsing.py new file mode 100644 index 00000000..0b3cdf3b --- /dev/null +++ b/service/src/main/inse/patents/common/parsing.py @@ -0,0 +1,138 @@ +"""Shared patent hit parsing, deduplication, and classification enrichment.""" +import logging + +import httpx + +from inse.patents.common import model +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.ipc_lookup import extract_ipc_symbol +from inse.patents.ipc_search_client import IpcSearchClient + +logger = logging.getLogger(__name__) + + +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 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, + ) + + +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 _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 + ] diff --git a/service/src/main/inse/patents/common/text_normalization.py b/service/src/main/inse/patents/common/text_normalization.py new file mode 100644 index 00000000..a5f3f22b --- /dev/null +++ b/service/src/main/inse/patents/common/text_normalization.py @@ -0,0 +1,79 @@ +"""Shared text normalization for patent name matching.""" +import re +import unicodedata + +_CHAR_REPLACEMENTS: dict[str, str] = { + "ß": "ss", + "ẞ": "ss", + "æ": "ae", + "Æ": "ae", + "œ": "oe", + "Œ": "oe", + "ø": "o", + "Ø": "o", + "đ": "d", + "Đ": "d", + "ð": "d", + "Ð": "d", + "þ": "th", + "Þ": "th", + "ł": "l", + "Ł": "l", + "ı": "i", + "ſ": "s", +} + +_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = ( + ("ae", "a"), + ("oe", "o"), + ("ue", "u"), +) + +_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = ( + (r"u([lmnrt])", r"ue\1"), + (r"o([lmnrt])", r"oe\1"), + (r"a([lmnrt])", r"ae\1"), +) + + +def normalize_name_part(value: str | None) -> str: + if not value: + return "" + + text = value.strip() + for src, dst in _CHAR_REPLACEMENTS.items(): + text = text.replace(src, dst) + + text = unicodedata.normalize("NFKD", text) + text = "".join(c for c in text if not unicodedata.combining(c)) + text = text.lower() + text = re.sub(r"[''`´]", "", text) + text = re.sub(r"[^\w\s-]", "", text) + text = re.sub(r"\s+", " ", text).strip() + return text + + +def name_token_variants(value: str | None) -> set[str]: + base = normalize_name_part(value) + if not base: + return set() + + variants = {base} + + for src, dst in _DIGRAPH_COLLAPSES: + if src in base: + variants.add(base.replace(src, dst)) + + if "-" in base: + variants.add(base.replace("-", "")) + variants.add(base.replace("-", " ")) + + return {v for v in variants if v} + + +def patent_transliteration_expansions(normalized: str) -> set[str]: + expanded = {normalized} + for pattern, repl in _PATENT_VOWEL_EXPANSIONS: + if re.search(pattern, normalized): + expanded.add(re.sub(pattern, repl, normalized)) + return expanded diff --git a/service/src/main/inse/patents/elastic_search_all_patents_client.py b/service/src/main/inse/patents/elastic_search_all_patents_client.py index cb4aacc9..f7b33cc1 100644 --- a/service/src/main/inse/patents/elastic_search_all_patents_client.py +++ b/service/src/main/inse/patents/elastic_search_all_patents_client.py @@ -36,24 +36,45 @@ class AllPatentsSearchClient: size: int = 10, search: str | None = None, sort_direction: str = "desc", + year_from: int | None = None, + year_to: int | None = None, ) -> 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] = { + search_query: dict[str, Any] = { "bool": { "should": [ - {"match_phrase": {"title_en": {"query": term}}}, - {"match_phrase": {"title_de": {"query": term}}}, + {"match": {"title_en": {"query": term, "operator": "and", "fuzziness": "AUTO"}}}, + {"match": {"title_de": {"query": term, "operator": "and", "fuzziness": "AUTO"}}}, {"term": {"doc_number": doc_number}}, ], "minimum_should_match": 1, } } else: - query = {"match_all": {}} + search_query = {"match_all": {}} + + filters = [] + if year_from or year_to: + date_range: dict[str, Any] = {} + if year_from: + date_range["gte"] = year_from * 10000 + if year_to: + date_range["lte"] = (year_to * 10000) + 9999 + filters.append({"range": {"date_publication": date_range}}) + + if filters: + query: dict[str, Any] = { + "bool": { + "must": search_query, + "filter": filters, + } + } + else: + query = search_query return { "from": page * size, @@ -68,30 +89,54 @@ class AllPatentsSearchClient: ], "query": query, } + + def remove_year(self, patent_id: str) -> str: + return patent_id[4:].strip() def uspto_query( self, page: int = 0, size: int = 10, search: str | None = None, sort_direction: str = "desc", + year_from: int | None = None, + year_to: int | None = None, ) -> 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] = { + search_query: dict[str, Any] = { "bool": { "should": [ - {"match_phrase": {"title": {"query": term}}}, + {"match": {"title": {"query": term, "operator": "and", "fuzziness": "AUTO"}}}, {"term": {"publication_number": pub_number}}, ], "minimum_should_match": 1, } } else: - query = {"match_all": {}} + search_query = {"match_all": {}} + + filters = [] + if year_from or year_to: + date_range: dict[str, Any] = {} + if year_from: + date_range["gte"] = year_from * 10000 + if year_to: + date_range["lte"] = (year_to * 10000) + 9999 + filters.append({"range": {"publication_date": date_range}}) + + if filters: + query: dict[str, Any] = { + "bool": { + "must": search_query, + "filter": filters, + } + } + else: + query = search_query return { "from": page * size, @@ -107,6 +152,103 @@ class AllPatentsSearchClient: "query": query, } + def epo_detail_query(self, doc_number: str,filling_date: str | None = None) -> dict[str, Any]: + query: dict[str, Any] = { + "bool": { + "should": [ + {"term": {"doc_number": doc_number}}, + {"term": {"doc_number": self.remove_year(doc_number)}}, + {"term": {"application_number": self.remove_year(doc_number)}}, + {"term": {"application_number": doc_number}}, + ], + "minimum_should_match": 1, + } + } + if filling_date: + query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}] + + return { + "size": 1, + "_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_detail_query(self, number: str,filling_date: str | None = None) -> dict[str, Any]: + query: dict[str, Any] = { + "bool": { + "should": [ + {"term": {"publication_number": number}}, + {"term": {"publication_number": self.remove_year(number)}}, + {"term": {"application_number": number}}, + {"term": {"application_number": self.remove_year(number)}}, + ], + "minimum_should_match": 1, + } + } + if filling_date: + query["bool"]["must"] = [{"term": {"application_date": filling_date}}] + + return { + "size": 1, + "_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, + } + + def epo_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]: + query: dict[str, Any] = { + "bool": { + "should": [ + {"match_phrase": {"title_en": title}}, + {"match_phrase": {"title_de": title}}, + ], + "minimum_should_match": 1, + } + } + if filling_date: + query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}] + + return { + "size": 1, + "_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_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]: + query: dict[str, Any] = { + "bool": { + "should": [{"match_phrase": {"title": title}}], + "minimum_should_match": 1, + } + } + if filling_date: + query["bool"]["must"] = [{"term": {"application_date": filling_date}}] + + return { + "size": 1, + "_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) diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 20221efb..4b6d8b02 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -6,21 +6,27 @@ from typing import Any from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex +import httpx import asyncio from .. import config from .name_matching import search_name_variants DEFAULT_SEARCH_SIZE = 100 +def remove_year(patent_number: str) -> str: + """Remove a 4-digit year from the end of a patent number, if present.""" + if len(patent_number) > 4 and patent_number[-4:].isdigit(): + return patent_number[:-4] + return patent_number def _match_name_field(field: str, name: str) -> dict[str, Any]: """Match a name field, including transliterated variants (Müller/Mueller).""" variants = search_name_variants(name) if len(variants) <= 1: - return {"match": {field: variants[0] if variants else name}} + return {"match_phrase": {field: variants[0] if variants else name}} return { "bool": { - "should": [{"match": {field: variant}} for variant in variants], + "should": [{"match_phrase": {field: variant}} for variant in variants], "minimum_should_match": 1, } } @@ -32,9 +38,15 @@ from inse.exceptions import MissingApiKeyError class PatentSearchClient: 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: @@ -158,9 +170,11 @@ class PatentSearchClient: } async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: + print("Searching EPO with payload:", payload) return await self._search(ESIndex.EPO_INDEX, payload) async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]: + print("Searching USPTO with payload:", payload) return await self._search(ESIndex.USPTO_INDEX, payload) async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: @@ -172,9 +186,10 @@ class PatentSearchClient: patent_id: str, prefix: str, title: str, + filling_date: str | None = None, size: int = 1, ) -> dict[str, Any]: - """Search EPO and USPTO by ID; fall back to match_phrase on title if no hits. + """Search EPO and USPTO by ID; fall back to match on title if no hits. Args: patent_id: The raw document/publication number (e.g. "1234567", "US1234567A"). @@ -202,16 +217,28 @@ class PatentSearchClient: return epo_result if epo_hits > 0 else uspto_result if prefix.upper() == "US": - payload = self._uspto_query_by_title(title, size) + payload = self._uspto_query_by_title(title, filling_date, size) return await self.search_uspto(payload) - payload = self._epo_query_by_title(title, size) + payload = self._epo_query_by_title(title,filling_date, size) return await self.search_epo(payload) + #query builders def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]: """Term query against doc_number; strips a leading 'EP' prefix if present.""" raw_id = patent_id.upper().removeprefix("EP") + query: dict[str, Any] = { + "bool": { + "should": [ + {"term": {"doc_number": raw_id}}, + {"term": {"doc_number": remove_year(raw_id)}}, + {"term": {"application_number": remove_year(raw_id)}}, + {"term": {"application_number": raw_id}}, + ], + "minimum_should_match": 1, + } + } return { "size": size, "_source": [ @@ -220,11 +247,23 @@ class PatentSearchClient: "application_filing_date", "title_en", "title_de", "abstract", "inventors_name", "applicants_name", "ipc", "cpc", ], - "query": {"term": {"doc_number": raw_id}}, + "query": query, } def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]: """Term query against publication_number; tries the ID as-is.""" + raw_id = patent_id.upper().removeprefix("US") + query: dict[str, Any] = { + "bool": { + "should": [ + {"term": {"publication_number": raw_id}}, + {"term": {"publication_number": remove_year(raw_id)}}, + {"term": {"application_number": raw_id}}, + {"term": {"application_number": remove_year(raw_id)}}, + ], + "minimum_should_match": 1, + } + } return { "size": size, "track_total_hits": True, @@ -235,11 +274,24 @@ class PatentSearchClient: "application_type", "title", "abstract", "inventors_names", "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", ], - "query": {"term": {"publication_number": patent_id}}, + "query": query, } - def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]: - """match_phrase fallback on title_en (and title_de as a should clause).""" + def _epo_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]: + """match fallback on title_en (and title_de as a should clause).""" + query: dict[str, Any] = { + "bool": { + "should": [ + {"match_phrase": {"title_en": title}}, + {"match_phrase": {"title_de": title}}, + {"match_phrase": {"title_fr": title}}, + ], + "minimum_should_match": 1, + } + } + if filling_date: + query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}] + return { "size": size, "_source": [ @@ -248,20 +300,19 @@ class PatentSearchClient: "application_filing_date", "title_en", "title_de", "abstract", "inventors_name", "applicants_name", "ipc", "cpc", ], - "query": { - "bool": { - "should": [ - {"match_phrase": {"title_en": title}}, - {"match_phrase": {"title_de": title}}, - {"match_phrase": {"title_fr": title}}, - ], - "minimum_should_match": 1, - } - }, + "query": query } - def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]: - """match_phrase fallback on title.""" + def _uspto_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]: + """match fallback on title.""" + query: dict[str, Any] = { + "bool": { + "should": [{"match_phrase": {"title": title}}], + "minimum_should_match": 1, + } + } + if filling_date: + query["bool"]["must"] = [{"term": {"application_date": filling_date}}] return { "size": size, "_source": [ @@ -270,5 +321,5 @@ class PatentSearchClient: "application_type", "title", "abstract", "inventors_names", "assignees_orgs", "ipcr", "cpc", "number_of_claims", "status", ], - "query": {"match_phrase": {"title": title}}, - } \ No newline at end of file + "query": query, + } diff --git a/service/src/main/inse/patents/institutions/__init__.py b/service/src/main/inse/patents/institutions/__init__.py new file mode 100644 index 00000000..986cd033 --- /dev/null +++ b/service/src/main/inse/patents/institutions/__init__.py @@ -0,0 +1 @@ +"""Patent lookup by institution assignee.""" diff --git a/service/src/main/inse/patents/institutions/logic.py b/service/src/main/inse/patents/institutions/logic.py new file mode 100644 index 00000000..e01ed75f --- /dev/null +++ b/service/src/main/inse/patents/institutions/logic.py @@ -0,0 +1,144 @@ +"""Business logic for patent lookup by institution assignee.""" +import asyncio +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 inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.models.openalex.institution import Institution +from inse.patents.common import model +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.common.parsing import ( + deduplicate_patents, + enrich_patents_classifications, + parse_epo_hits, + parse_uspto_hits, +) +from inse.patents.institutions.name_matching import ( + MIN_INSTITUTION_ACRONYM_LEN, + assignee_matches_institution_name, + institution_search_variants, +) +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.search_client import PatentSearchClient + +logger = logging.getLogger(__name__) + + +async def get_patents_by_institution_id( + institution_id: str, + client: PatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, + institutions_client: InstitutionsSearchClient | None = None, +) -> model.PatentsByInstitutionResponse: + search_client = client or PatentSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() + institution_client = institutions_client or InstitutionsSearchClient() + + short_id = institution_id.replace("https://openalex.org/", "") + institution = institution_client.get_institution_by_id(short_id) + search_names = _institution_search_names(institution) + + if not search_names: + return model.PatentsByInstitutionResponse( + institution_id=short_id, + institution_name=institution.display_name, + patent_count=0, + patents=[], + ) + + try: + epo_data, uspto_data = await asyncio.gather( + search_client.search_epo( + search_client.epo_query_by_applicant(search_names) + ), + search_client.search_uspto( + search_client.uspto_query_by_assignee(search_names) + ), + ) + 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) + all_patents = filter_patents_by_institution(all_patents, institution) + all_patents = deduplicate_patents(all_patents) + + await enrich_patents_classifications(all_patents, ipc_search_client) + + return model.PatentsByInstitutionResponse( + institution_id=short_id, + institution_name=institution.display_name, + patent_count=len(all_patents), + patents=all_patents, + ) + + +def _institution_search_names(institution: Institution) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + + def _add(name: str | None) -> None: + if not name or not name.strip(): + return + for variant in institution_search_variants(name.strip()): + key = variant.casefold() + if key not in seen: + seen.add(key) + names.append(variant) + + _add(institution.display_name) + for alternative in institution.display_name_alternatives or []: + _add(alternative) + for acronym in institution.display_name_acronyms or []: + if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN: + _add(acronym) + + return names + + +def _institution_canonical_names(institution: Institution) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + + def _add(name: str | None) -> None: + if not name or not name.strip(): + return + key = name.strip().casefold() + if key not in seen: + seen.add(key) + names.append(name.strip()) + + _add(institution.display_name) + for alternative in institution.display_name_alternatives or []: + _add(alternative) + for acronym in institution.display_name_acronyms or []: + if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN: + _add(acronym) + + return names + + +def filter_patents_by_institution( + patents: list[model.PatentEntry], + institution: Institution, +) -> list[model.PatentEntry]: + canonical_names = _institution_canonical_names(institution) + return [ + patent for patent in patents + if any( + assignee_matches_institution_name(assignee, name) + for assignee in patent.assignees + for name in canonical_names + ) + ] diff --git a/service/src/main/inse/patents/institutions/name_matching.py b/service/src/main/inse/patents/institutions/name_matching.py new file mode 100644 index 00000000..bb5f1aba --- /dev/null +++ b/service/src/main/inse/patents/institutions/name_matching.py @@ -0,0 +1,91 @@ +"""Institution assignee name normalization and matching.""" +from inse.patents.common.text_normalization import ( + name_token_variants, + normalize_name_part, + patent_transliteration_expansions, +) + +_INSTITUTION_GENERIC_TOKENS = frozenset({ + "university", "universitat", "universitaet", "universiteit", "college", + "institute", "institut", "institution", "national", "sciences", "science", + "school", "center", "centre", "laboratory", "department", "academy", + "the", "of", "for", "and", "de", "la", "des", "der", "die", "das", "und", + "fur", "von", +}) + +MIN_INSTITUTION_SUBSTRING_LEN = 6 +MIN_INSTITUTION_VARIANT_LEN = 4 +MIN_INSTITUTION_ACRONYM_LEN = 3 + + +def institution_search_variants(value: str | None) -> list[str]: + if not value or not value.strip(): + return [] + + stripped = value.strip() + min_len = ( + MIN_INSTITUTION_ACRONYM_LEN + if stripped.isupper() and " " not in stripped + else MIN_INSTITUTION_VARIANT_LEN + ) + + seen: set[str] = set() + ordered: list[str] = [] + + def _add(candidate: str) -> None: + candidate = candidate.strip() + if len(candidate) < min_len: + return + key = candidate.casefold() + if key not in seen: + seen.add(key) + ordered.append(candidate) + + _add(stripped) + + normalized = normalize_name_part(value) + if normalized: + _add(normalized.title()) + + for variant in name_token_variants(value): + _add(variant.title()) + + for variant in patent_transliteration_expansions(normalized): + _add(variant.title()) + + return ordered + + +def _significant_institution_tokens(text: str) -> set[str]: + return { + token + for token in normalize_name_part(text).split() + if len(token) >= MIN_INSTITUTION_VARIANT_LEN + and token not in _INSTITUTION_GENERIC_TOKENS + } + + +def assignee_matches_institution_name(assignee: str, institution_name: str) -> bool: + norm_assignee = normalize_name_part(assignee) + norm_name = normalize_name_part(institution_name) + if not norm_assignee or not norm_name: + return False + + original = institution_name.strip() + assignee_tokens = set(norm_assignee.split()) + + if len(original) <= 6 and " " not in original: + return norm_name in assignee_tokens + + if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN: + if norm_name in norm_assignee or norm_assignee in norm_name: + return True + + significant = _significant_institution_tokens(institution_name) + if not significant: + return False + + matched = significant & assignee_tokens + if len(significant) >= 2: + return len(matched) >= 2 + return bool(matched) diff --git a/service/src/main/inse/patents/institutions/search_queries.py b/service/src/main/inse/patents/institutions/search_queries.py new file mode 100644 index 00000000..1067ab16 --- /dev/null +++ b/service/src/main/inse/patents/institutions/search_queries.py @@ -0,0 +1,94 @@ +"""Elasticsearch query builders for institution assignee patent search.""" +from typing import Any + +from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE +from inse.patents.institutions.name_matching import institution_search_variants + + +class AssigneeSearchQueries: + def _match_organization_names(self, field: str, names: list[str]) -> dict[str, Any]: + clauses: list[dict[str, Any]] = [] + seen: set[str] = set() + + for name in names: + for variant in institution_search_variants(name): + key = variant.casefold() + if not variant or key in seen: + continue + seen.add(key) + clauses.append({"match_phrase": {field: {"query": variant}}}) + + if not clauses: + return {"match_none": {}} + + return { + "bool": { + "should": clauses, + "minimum_should_match": 1, + } + } + + def epo_query_by_applicant( + self, + institution_names: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"date_publication": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_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": self._match_organization_names("applicants_name", institution_names), + } + + def uspto_query_by_assignee( + self, + institution_names: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"publication_date": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": [ + "publication_number", + "country", + "publication_date", + "publication_year", + "application_number", + "application_date", + "application_type", + "title", + "abstract", + "inventors_names", + "assignees_orgs", + "ipcr", + "cpc", + "number_of_claims", + "status", + ], + "query": self._match_organization_names("assignees_orgs", institution_names), + } diff --git a/service/src/main/inse/patents/institutions/service.py b/service/src/main/inse/patents/institutions/service.py new file mode 100644 index 00000000..4978d077 --- /dev/null +++ b/service/src/main/inse/patents/institutions/service.py @@ -0,0 +1,33 @@ +from functools import lru_cache +from typing import Annotated + +from fastapi import APIRouter, Depends + +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.patents.common import model +from inse.patents.institutions import logic + +router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"]) + + +@lru_cache +def get_institutions_search_client() -> InstitutionsSearchClient: + return InstitutionsSearchClient() + + +@router.get( + "/{id}/patents", + operation_id="getPatentsByInstitution", + response_model=model.PatentsByInstitutionResponse, + summary="Get patents matched to an institution by assignee name.", +) +async def get_patents_by_institution( + id: str, + client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], +) -> model.PatentsByInstitutionResponse: + return await logic.get_patents_by_institution_id( + institution_id=id, + institutions_client=client, + ) diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index de39f902..6d2522c4 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -1,8 +1,12 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - Business logic for patent matching by author name. -""" +"""Backward-compatible re-exports.""" +from inse.patents.all.logic import get_all_patents +from inse.patents.authors.logic import get_patents_by_author_id +from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents +from inse.patents.institutions.logic import ( + filter_patents_by_institution as _filter_patents_by_institution, + get_patents_by_institution_id, +) + import logging import asyncio @@ -16,22 +20,28 @@ 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 - +from datetime import datetime logger = logging.getLogger(__name__) - +def normalize_patent_date(date_str: str) -> str: + return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d") + async def get_patent( patent_id: str, title: str, prefix: str, + filling_date: str | None = None, client: PatentSearchClient | None = None, ) -> model.PatentEntry: search_client = client or PatentSearchClient() + if filling_date: + filling_date = normalize_patent_date(filling_date) data = await search_client.get_by_id_or_title( patent_id=patent_id, prefix=prefix, title=title, + filling_date=filling_date, ) parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits @@ -309,4 +319,4 @@ async def get_all_patents( page=page, size=size, patents=patents, - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index ad26f939..fe8a1047 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -1,47 +1,2 @@ -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): - patent_id: str - source: str # "EPO" or "USPTO" - title: str | None = None - 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] \ No newline at end of file +"""Backward-compatible re-exports.""" +from inse.patents.common.model import * # noqa: F403 diff --git a/service/src/main/inse/patents/name_matching.py b/service/src/main/inse/patents/name_matching.py index 659b295c..a1e45065 100644 --- a/service/src/main/inse/patents/name_matching.py +++ b/service/src/main/inse/patents/name_matching.py @@ -1,242 +1,18 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - Name normalization and matching for patent inventor lookup. - - Handles umlauts, diacritics, and common Latin transliterations so that - e.g. 'Müller' matches 'Mueller' and 'Muller'. -""" -import re -import unicodedata - -# Characters that NFKD does not map to ASCII-friendly forms. -_CHAR_REPLACEMENTS: dict[str, str] = { - "ß": "ss", - "ẞ": "ss", - "æ": "ae", - "Æ": "ae", - "œ": "oe", - "Œ": "oe", - "ø": "o", - "Ø": "o", - "đ": "d", - "Đ": "d", - "ð": "d", - "Ð": "d", - "þ": "th", - "Þ": "th", - "ł": "l", - "Ł": "l", - "ı": "i", - "ſ": "s", -} - -# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü. -_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = ( - ("ae", "a"), - ("oe", "o"), - ("ue", "u"), +"""Backward-compatible re-exports.""" +from inse.patents.authors.name_matching import ( # noqa: F401 + first_name_match_kind, + name_matches, + search_name_variants, + tokens_equal, ) - -# Common ASCII spellings in patent records for umlaut-derived vowels. -_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = ( - (r"u([lmnrt])", r"ue\1"), - (r"o([lmnrt])", r"oe\1"), - (r"a([lmnrt])", r"ae\1"), +from inse.patents.common.text_normalization import ( # noqa: F401 + name_token_variants, + normalize_name_part, +) +from inse.patents.institutions.name_matching import ( # noqa: F401 + MIN_INSTITUTION_ACRONYM_LEN, + MIN_INSTITUTION_SUBSTRING_LEN, + MIN_INSTITUTION_VARIANT_LEN, + assignee_matches_institution_name, + institution_search_variants, ) - - -def normalize_name_part(value: str | None) -> str: - """ - Normalize a single name token for comparison. - - Steps: transliteration map -> NFKD -> strip diacritics -> lowercase - -> remove apostrophes/punctuation -> collapse whitespace. - """ - if not value: - return "" - - text = value.strip() - for src, dst in _CHAR_REPLACEMENTS.items(): - text = text.replace(src, dst) - - text = unicodedata.normalize("NFKD", text) - text = "".join(c for c in text if not unicodedata.combining(c)) - text = text.lower() - text = re.sub(r"[''`´]", "", text) - text = re.sub(r"[^\w\s-]", "", text) - text = re.sub(r"\s+", " ", text).strip() - return text - - -def name_token_variants(value: str | None) -> set[str]: - """ - Return equivalent forms of a name token. - - Includes the normalized base plus German digraph collapses - (Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre). - """ - base = normalize_name_part(value) - if not base: - return set() - - variants = {base} - - for src, dst in _DIGRAPH_COLLAPSES: - if src in base: - variants.add(base.replace(src, dst)) - - if "-" in base: - variants.add(base.replace("-", "")) - variants.add(base.replace("-", " ")) - - return {v for v in variants if v} - - -def _patent_transliteration_expansions(normalized: str) -> set[str]: - """ - ASCII spellings used in patent records (e.g. Müller indexed as Mueller). - - Used for Elasticsearch recall only; post-filter applies stricter matching. - """ - expanded = {normalized} - for pattern, repl in _PATENT_VOWEL_EXPANSIONS: - if re.search(pattern, normalized): - expanded.add(re.sub(pattern, repl, normalized)) - return expanded - - -def tokens_equal( - left: str | None, - right: str | None, - *, - allow_initial: bool = True, -) -> bool: - """True when two name tokens are equivalent after normalization.""" - left_variants = name_token_variants(left) - right_variants = name_token_variants(right) - if not left_variants or not right_variants: - return False - if left_variants & right_variants: - return True - - if not allow_initial: - return False - - return _initial_tokens_match(left, right) - - -def _initial_letter(token: str | None) -> str | None: - normalized = normalize_name_part(token) - if len(normalized) == 1 and normalized.isalpha(): - return normalized - return None - - -def _initial_tokens_match(left: str | None, right: str | None) -> bool: - """True when one token is a single-letter initial matching the other token.""" - left_initial = _initial_letter(left) - right_initial = _initial_letter(right) - left_full = normalize_name_part(left) - right_full = normalize_name_part(right) - - if left_initial and right_full and len(right_full) > 1: - return right_full.startswith(left_initial) - if right_initial and left_full and len(left_full) > 1: - return left_full.startswith(right_initial) - if left_initial and right_initial: - return left_initial == right_initial - return False - - -def _inventor_first_token(inventor_name: str) -> str: - if "," in inventor_name: - _, first_part = [p.strip() for p in inventor_name.split(",", 1)] - return first_part.split()[0] if first_part else "" - parts = inventor_name.split() - return parts[0] if parts else "" - - -def first_name_match_kind( - inventor_name: str, - first_name: str, - last_name: str, -) -> str: - """ - Match quality for the inventor first name: 'full', 'initial', or 'none'. - """ - if not name_matches(inventor_name, first_name, last_name): - return "none" - - inventor_first = _inventor_first_token(inventor_name) - if tokens_equal(inventor_first, first_name, allow_initial=False): - return "full" - return "initial" - - -def search_name_variants(value: str | None) -> list[str]: - """ - Distinct search strings for Elasticsearch, preserving original casing - where useful but including normalized and transliterated forms. - """ - if not value or not value.strip(): - return [] - - seen: set[str] = set() - ordered: list[str] = [] - - def _add(candidate: str) -> None: - key = candidate.casefold() - if candidate.strip() and key not in seen: - seen.add(key) - ordered.append(candidate.strip()) - - _add(value.strip()) - - normalized = normalize_name_part(value) - if normalized: - _add(normalized.title()) - - for variant in name_token_variants(value): - _add(variant.title()) - - for variant in _patent_transliteration_expansions(normalized): - _add(variant.title()) - - if normalized and len(normalized) > 1: - _add(normalized[0].upper()) - - return ordered - - -def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool: - """ - True when an inventor entry matches first_name + last_name. - - Supports: - - USPTO: 'Christian Weber', 'Christian Hans Weber' - - EPO: 'Weber, Christian', 'Weber, Christian Hans' - """ - if not inventor_name or not last_name: - return False - - name = inventor_name.strip() - - if "," in name: - last_part, first_part = [p.strip() for p in name.split(",", 1)] - first_token = first_part.split()[0] if first_part else "" - return ( - tokens_equal(last_part, last_name, allow_initial=False) - and bool(first_name) - and tokens_equal(first_token, first_name) - ) - - parts = name.split() - if len(parts) < 2: - return False - - return ( - tokens_equal(parts[-1], last_name, allow_initial=False) - and bool(first_name) - and tokens_equal(parts[0], first_name) - ) diff --git a/service/src/main/inse/patents/org/__init__.py b/service/src/main/inse/patents/org/__init__.py new file mode 100644 index 00000000..89bdee15 --- /dev/null +++ b/service/src/main/inse/patents/org/__init__.py @@ -0,0 +1 @@ +"""Org patents index: institution-scoped patent aggregation.""" diff --git a/service/src/main/inse/patents/org/elastic_search_client.py b/service/src/main/inse/patents/org/elastic_search_client.py new file mode 100644 index 00000000..c8ef2d8a --- /dev/null +++ b/service/src/main/inse/patents/org/elastic_search_client.py @@ -0,0 +1,199 @@ +"""HTTP client for the org_patents Elasticsearch index.""" +import json +import logging +from typing import Any + +import httpx + +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.org.mapping import ORG_PATENTS_INDEX, ORG_PATENTS_MAPPING +from inse.patents.org.model import MatchTypeFilter, OrgPatentEntry +from inse import config + +logger = logging.getLogger(__name__) + +DEFAULT_PAGE_SIZE = 20 + + +class OrgPatentsSearchClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float = 60.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, content_type: str = "application/json") -> 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": content_type, + } + + async def ensure_index(self) -> None: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.head( + f"/{ORG_PATENTS_INDEX}", + headers=self._headers(), + ) + if response.status_code == 404: + create_response = await client.put( + f"/{ORG_PATENTS_INDEX}", + headers=self._headers(), + json={"mappings": ORG_PATENTS_MAPPING}, + ) + create_response.raise_for_status() + logger.info("Created index %s", ORG_PATENTS_INDEX) + return + + response.raise_for_status() + mapping_response = await client.put( + f"/{ORG_PATENTS_INDEX}/_mapping", + headers=self._headers(), + json=ORG_PATENTS_MAPPING, + ) + mapping_response.raise_for_status() + + async def delete_by_institution(self, institution_id: str) -> int: + payload = { + "query": {"term": {"institution_id": institution_id.upper()}}, + } + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{ORG_PATENTS_INDEX}/_delete_by_query", + headers=self._headers(), + json=payload, + params={"refresh": "true"}, + ) + if response.status_code == 404: + return 0 + response.raise_for_status() + return response.json().get("deleted", 0) + + async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None: + if not documents: + return + + batch_size = 500 + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + for start in range(0, len(documents), batch_size): + batch = documents[start : start + batch_size] + bulk_lines: list[str] = [] + for doc_id, source in batch: + bulk_lines.append(json.dumps({"index": {"_index": ORG_PATENTS_INDEX, "_id": doc_id}})) + bulk_lines.append(json.dumps(source)) + + payload = "\n".join(bulk_lines) + "\n" + response = await client.post( + "/_bulk", + content=payload, + headers=self._headers("application/x-ndjson"), + params={"refresh": "true"}, + ) + response.raise_for_status() + result = response.json() + if result.get("errors"): + failed = [ + item + for item in result.get("items", []) + if item.get("index", {}).get("status", 200) >= 400 + ] + logger.error("Bulk index errors: %s", failed[:3]) + raise RuntimeError("Bulk indexing into org_patents failed.") + + async def search_by_institution( + self, + institution_id: str, + match_type: MatchTypeFilter = "all", + page: int = 0, + size: int = DEFAULT_PAGE_SIZE, + source: str | None = None, + ) -> tuple[list[OrgPatentEntry], int]: + short_id = institution_id.replace("https://openalex.org/", "").upper() + filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}] + + if match_type == "institution": + filters.append({"terms": {"match_type": ["institution", "both"]}}) + elif match_type == "name": + filters.append({"terms": {"match_type": ["name", "both"]}}) + elif match_type == "both": + filters.append({"term": {"match_type": "both"}}) + + if source in ("EPO", "USPTO"): + filters.append({"term": {"source": source}}) + + payload = { + "from": page * size, + "size": size, + "track_total_hits": True, + "query": {"bool": {"filter": filters}}, + "sort": [ + {"publication_year": {"order": "desc", "missing": "_last"}}, + {"patent_id": {"order": "asc"}}, + ], + } + + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.post( + f"/{ORG_PATENTS_INDEX}/_search", + headers=self._headers(), + json=payload, + ) + if response.status_code == 404: + return [], 0 + response.raise_for_status() + data = response.json() + + total = data.get("hits", {}).get("total", {}).get("value", 0) + patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])] + return patents, total + + +def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry: + source = hit.get("_source", {}) + publication_year = source.get("publication_year") + return OrgPatentEntry( + institution_id=source.get("institution_id", ""), + institution_name=source.get("institution_name"), + patent_id=source.get("patent_id", ""), + source=source.get("source", ""), + match_type=source.get("match_type", "institution"), + title=source.get("title"), + abstract=source.get("abstract"), + publication_date=source.get("publication_date"), + publication_year=str(publication_year) if publication_year is not None else None, + application_number=source.get("application_number"), + application_date=source.get("application_date"), + kind=source.get("kind"), + application_type=source.get("application_type"), + number_of_claims=source.get("number_of_claims"), + status=source.get("status"), + inventors=source.get("inventors") or [], + assignees=source.get("assignees") or [], + ipc=source.get("ipc") or [], + cpc=source.get("cpc") or [], + country=source.get("country"), + matched_authors=source.get("matched_authors") or [], + ) diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py new file mode 100644 index 00000000..4e8f8308 --- /dev/null +++ b/service/src/main/inse/patents/org/logic.py @@ -0,0 +1,429 @@ +"""Business logic for org_patents index build and retrieval.""" +import asyncio +import logging +import re +from dataclasses import dataclass, field + +import httpx +from fastapi import HTTPException +from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_503_SERVICE_UNAVAILABLE + +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.integrations import elasticsearch +from inse.models.openalex.author import Author +from inse.patents.authors.name_matching import name_matches +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.common.model import PatentEntry +from inse.patents.common.parsing import ( + deduplicate_patents, + enrich_patents_classifications, + parse_epo_hits, + parse_uspto_hits, + patent_dedup_key, +) +from inse.patents.institutions.logic import get_patents_by_institution_id +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.patents.org.model import ( + MatchType, + MatchTypeFilter, + MatchedAuthor, + OrgPatentEntry, + OrgPatentsResponse, +) +from inse.patents.search_client import PatentSearchClient + +logger = logging.getLogger(__name__) + +AUTHOR_PAGE_SIZE = 500 +ORG_PATENT_SEARCH_SIZE = 500 +AUTHOR_SEARCH_CONCURRENCY = 8 + + +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 + + +def _filter_patents_by_name( + patents: list[PatentEntry], + first_name: str, + last_name: str, +) -> list[PatentEntry]: + return [ + patent + for patent in patents + if any( + name_matches(inventor, first_name, last_name) + for inventor in patent.inventors + ) + ] + + +@dataclass +class _AccumulatedPatent: + patent: PatentEntry + institution_match: bool = False + matched_authors: dict[str, MatchedAuthor] = field(default_factory=dict) + + +def normalize_institution_id(institution_id: str) -> str: + return institution_id.replace("https://openalex.org/", "").upper() + + +def normalize_author_id(author_id: str | None) -> str: + if not author_id: + return "" + return author_id.replace("https://openalex.org/", "").upper() + + +def org_patent_document_id(institution_id: str, patent: PatentEntry) -> str: + stage = patent.kind or patent.application_type or "none" + safe_patent_id = re.sub(r"[^A-Za-z0-9_-]", "_", patent.patent_id) + safe_date = patent.publication_date or "none" + safe_stage = re.sub(r"[^A-Za-z0-9_-]", "_", stage) + return f"{normalize_institution_id(institution_id)}_{patent.source}_{safe_patent_id}_{safe_date}_{safe_stage}" + + +def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchType: + if institution_match and has_name_match: + return "both" + if institution_match: + return "institution" + return "name" + + +def merge_org_patents( + institution_id: str, + institution_name: str | None, + institution_patents: list[PatentEntry], + author_patents: list[tuple[Author, list[PatentEntry]]], +) -> list[OrgPatentEntry]: + accumulated: dict[tuple[str, str, str, str], _AccumulatedPatent] = {} + + for patent in institution_patents: + key = patent_dedup_key(patent) + entry = accumulated.get(key) + if entry is None: + accumulated[key] = _AccumulatedPatent(patent=patent, institution_match=True) + else: + entry.institution_match = True + + for author, patents in author_patents: + author_id = normalize_author_id(author.id) + author_name = author.display_name or "" + if not author_id or not author_name: + continue + + matched_author = MatchedAuthor( + openalex_author_id=author_id, + author_name=author_name, + ) + for patent in patents: + key = patent_dedup_key(patent) + entry = accumulated.get(key) + if entry is None: + accumulated[key] = _AccumulatedPatent( + patent=patent, + matched_authors={author_id: matched_author}, + ) + else: + entry.matched_authors[author_id] = matched_author + + org_patents: list[OrgPatentEntry] = [] + short_institution_id = normalize_institution_id(institution_id) + + for entry in accumulated.values(): + has_name_match = bool(entry.matched_authors) + match_type = resolve_match_type(entry.institution_match, has_name_match) + org_patents.append( + OrgPatentEntry( + institution_id=short_institution_id, + institution_name=institution_name, + match_type=match_type, + matched_authors=list(entry.matched_authors.values()), + **entry.patent.model_dump(), + ) + ) + + org_patents.sort( + key=lambda patent: ( + patent.publication_year or "", + patent.patent_id, + ), + reverse=True, + ) + return org_patents + + +def org_patent_to_es_document(patent: OrgPatentEntry) -> dict: + publication_year = None + if patent.publication_year: + try: + publication_year = int(patent.publication_year) + except ValueError: + publication_year = None + + return { + "institution_id": patent.institution_id, + "institution_name": patent.institution_name, + "patent_id": patent.patent_id, + "source": patent.source, + "match_type": patent.match_type, + "title": patent.title, + "abstract": patent.abstract, + "publication_date": patent.publication_date, + "publication_year": publication_year, + "application_number": patent.application_number, + "application_date": patent.application_date, + "kind": patent.kind, + "application_type": patent.application_type, + "number_of_claims": patent.number_of_claims, + "status": patent.status, + "inventors": patent.inventors, + "assignees": patent.assignees, + "ipc": patent.ipc, + "cpc": patent.cpc, + "country": patent.country, + "matched_authors": [ + author.model_dump() for author in patent.matched_authors + ], + } + + +def fetch_authors_for_institution(institution_id: str) -> list[Author]: + short_id = normalize_institution_id(institution_id) + query = { + "nested": { + "path": "last_known_institutions", + "query": { + "term": { + "last_known_institutions.id": f"https://openalex.org/{short_id}", + } + }, + } + } + + authors: list[Author] = [] + search_after: list | None = None + sort = [ + {"works_count": {"order": "desc"}}, + {"id": {"order": "asc"}}, + ] + + while True: + body: dict = { + "size": AUTHOR_PAGE_SIZE, + "query": query, + "sort": sort, + } + if search_after: + body["search_after"] = search_after + + response = elasticsearch.search(index="openalex-authors", body=body) + hits = response.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + source = dict(hit.get("_source", {})) + source["id"] = source.get("id") or hit.get("_id", "") + author = Author.from_dict(source) + if author: + authors.append(author) + + if len(hits) < AUTHOR_PAGE_SIZE: + break + search_after = hits[-1].get("sort") + if not search_after: + break + + return authors + + +async def _search_patents_by_author( + author: Author, + search_client: PatentSearchClient, +) -> list[PatentEntry]: + author_name = author.display_name + last_name = _extract_last_name(author_name) + first_name = _extract_first_name(author_name) + if not last_name: + return [] + + try: + epo_data, uspto_data = await asyncio.gather( + search_client.search_epo( + search_client.epo_query_by_inventor( + last_name, first_name, size=ORG_PATENT_SEARCH_SIZE + ) + ), + search_client.search_uspto( + search_client.uspto_query_by_inventor( + last_name, first_name, size=ORG_PATENT_SEARCH_SIZE + ) + ), + ) + except (MissingApiKeyError, httpx.HTTPError): + raise + + patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + if first_name and last_name: + patents = _filter_patents_by_name(patents, first_name, last_name) + return deduplicate_patents(patents) + + +async def build_org_patents_for_institution( + institution_id: str, + search_client: PatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, + institutions_client: InstitutionsSearchClient | None = None, +) -> list[OrgPatentEntry]: + patent_client = search_client or PatentSearchClient() + ipc_search_client = ipc_client or IpcSearchClient() + institution_client = institutions_client or InstitutionsSearchClient() + + short_id = normalize_institution_id(institution_id) + institution = institution_client.get_institution_by_id(short_id) + institution_name = institution.display_name + + institution_response = await get_patents_by_institution_id( + institution_id=short_id, + client=patent_client, + ipc_client=ipc_search_client, + institutions_client=institution_client, + ) + institution_patents = institution_response.patents + + authors = fetch_authors_for_institution(short_id) + logger.info( + "Building org_patents for %s (%s): %d authors, %d institution patents", + institution_name, + short_id, + len(authors), + len(institution_patents), + ) + + semaphore = asyncio.Semaphore(AUTHOR_SEARCH_CONCURRENCY) + + async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]: + async with semaphore: + patents = await _search_patents_by_author(author, patent_client) + return author, patents + + author_results = await asyncio.gather( + *[_fetch_for_author(author) for author in authors], + return_exceptions=True, + ) + + author_patents: list[tuple[Author, list[PatentEntry]]] = [] + for result in author_results: + if isinstance(result, Exception): + logger.warning("Author patent search failed: %s", result) + continue + author_patents.append(result) + + org_patents = merge_org_patents( + institution_id=short_id, + institution_name=institution_name, + institution_patents=institution_patents, + author_patents=author_patents, + ) + + await enrich_patents_classifications( + [patent for patent in org_patents], + ipc_search_client, + ) + return org_patents + + +async def index_org_patents_for_institution( + institution_id: str, + search_client: PatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, + institutions_client: InstitutionsSearchClient | None = None, + org_client: OrgPatentsSearchClient | None = None, +) -> int: + short_id = normalize_institution_id(institution_id) + org_patents_client = org_client or OrgPatentsSearchClient() + + org_patents = await build_org_patents_for_institution( + institution_id=short_id, + search_client=search_client, + ipc_client=ipc_client, + institutions_client=institutions_client, + ) + + await org_patents_client.ensure_index() + deleted = await org_patents_client.delete_by_institution(short_id) + logger.info("Deleted %d existing org_patents documents for %s", deleted, short_id) + + documents = [ + ( + org_patent_document_id(short_id, patent), + org_patent_to_es_document(patent), + ) + for patent in org_patents + ] + await org_patents_client.bulk_index(documents) + logger.info("Indexed %d org_patents documents for %s", len(documents), short_id) + return len(documents) + + +async def get_org_patents_by_institution_id( + institution_id: str, + match_type: MatchTypeFilter = "all", + page: int = 0, + size: int = 20, + source: str | None = None, + org_client: OrgPatentsSearchClient | None = None, + institutions_client: InstitutionsSearchClient | None = None, +) -> OrgPatentsResponse: + short_id = normalize_institution_id(institution_id) + org_patents_client = org_client or OrgPatentsSearchClient() + institution_client = institutions_client or InstitutionsSearchClient() + + try: + institution = institution_client.get_institution_by_id(short_id) + institution_name = institution.display_name + except Exception: + institution_name = None + + try: + await org_patents_client.ensure_index() + patents, total = await org_patents_client.search_by_institution( + institution_id=short_id, + match_type=match_type, + page=page, + size=size, + source=source, + ) + 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="org_patents search request failed.", + ) from exc + + return OrgPatentsResponse( + institution_id=short_id, + institution_name=institution_name, + patent_count=total, + page=page, + size=size, + patents=patents, + ) diff --git a/service/src/main/inse/patents/org/mapping.py b/service/src/main/inse/patents/org/mapping.py new file mode 100644 index 00000000..d3191a46 --- /dev/null +++ b/service/src/main/inse/patents/org/mapping.py @@ -0,0 +1,33 @@ +ORG_PATENTS_INDEX = "org_patents" + +ORG_PATENTS_MAPPING = { + "properties": { + "institution_id": {"type": "keyword"}, + "institution_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "patent_id": {"type": "keyword"}, + "source": {"type": "keyword"}, + "match_type": {"type": "keyword"}, + "title": {"type": "text"}, + "abstract": {"type": "text"}, + "publication_date": {"type": "keyword"}, + "publication_year": {"type": "integer"}, + "application_number": {"type": "keyword"}, + "application_date": {"type": "keyword"}, + "kind": {"type": "keyword"}, + "application_type": {"type": "keyword"}, + "number_of_claims": {"type": "integer"}, + "status": {"type": "keyword"}, + "inventors": {"type": "keyword"}, + "assignees": {"type": "keyword"}, + "ipc": {"type": "keyword"}, + "cpc": {"type": "keyword"}, + "country": {"type": "keyword"}, + "matched_authors": { + "type": "nested", + "properties": { + "openalex_author_id": {"type": "keyword"}, + "author_name": {"type": "keyword"}, + }, + }, + } +} diff --git a/service/src/main/inse/patents/org/model.py b/service/src/main/inse/patents/org/model.py new file mode 100644 index 00000000..3de95d01 --- /dev/null +++ b/service/src/main/inse/patents/org/model.py @@ -0,0 +1,29 @@ +from typing import Literal + +from pydantic import BaseModel, Field + +from inse.patents.common.model import PatentEntry + +MatchType = Literal["institution", "name", "both"] +MatchTypeFilter = Literal["institution", "name", "both", "all"] + + +class MatchedAuthor(BaseModel): + openalex_author_id: str + author_name: str + + +class OrgPatentEntry(PatentEntry): + institution_id: str + institution_name: str | None = None + match_type: MatchType + matched_authors: list[MatchedAuthor] = Field(default_factory=list) + + +class OrgPatentsResponse(BaseModel): + institution_id: str + institution_name: str | None = None + patent_count: int + page: int = 0 + size: int = 20 + patents: list[OrgPatentEntry] diff --git a/service/src/main/inse/patents/org/service.py b/service/src/main/inse/patents/org/service.py new file mode 100644 index 00000000..df04d86b --- /dev/null +++ b/service/src/main/inse/patents/org/service.py @@ -0,0 +1,44 @@ +from functools import lru_cache +from typing import Annotated + +from fastapi import APIRouter, Depends, Query + +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.patents.org import logic +from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse + +router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"]) + + +@lru_cache +def get_institutions_search_client() -> InstitutionsSearchClient: + return InstitutionsSearchClient() + + +@router.get( + "/{id}/org-patents", + operation_id="getOrgPatentsByInstitution", + response_model=OrgPatentsResponse, + summary="Get pre-indexed org patents for an institution.", +) +async def get_org_patents_by_institution( + id: str, + client: Annotated[ + InstitutionsSearchClient, Depends(get_institutions_search_client) + ], + match_type: Annotated[ + MatchTypeFilter, + Query(description="Filter patents by match type."), + ] = "all", + page: int = 0, + size: int = 20, + source: str | None = None, +) -> OrgPatentsResponse: + return await logic.get_org_patents_by_institution_id( + institution_id=id, + match_type=match_type, + page=page, + size=size, + source=source, + institutions_client=client, + ) diff --git a/service/src/main/inse/patents/org/test_logic.py b/service/src/main/inse/patents/org/test_logic.py new file mode 100644 index 00000000..ca01887e --- /dev/null +++ b/service/src/main/inse/patents/org/test_logic.py @@ -0,0 +1,100 @@ +from inse.patents.common.model import PatentEntry +from inse.patents.org.logic import merge_org_patents, org_patent_document_id, resolve_match_type +from inse.patents.org.model import MatchedAuthor +from inse.models.openalex.author import Author + + +def _patent( + patent_id: str = "EP1234567", + source: str = "EPO", +) -> PatentEntry: + return PatentEntry( + patent_id=patent_id, + source=source, + title="Example patent", + publication_year="2024", + ) + + +def _author(author_id: str, name: str) -> Author: + return Author( + id=f"https://openalex.org/{author_id}", + display_name=name, + ) + + +def test_resolve_match_type() -> None: + assert resolve_match_type(True, True) == "both" + assert resolve_match_type(True, False) == "institution" + assert resolve_match_type(False, True) == "name" + + +def test_merge_org_patents_keeps_institution_only_patents() -> None: + result = merge_org_patents( + institution_id="I62318514", + institution_name="University of Duisburg-Essen", + institution_patents=[_patent("EP111")], + author_patents=[], + ) + + assert len(result) == 1 + assert result[0].match_type == "institution" + assert result[0].matched_authors == [] + + +def test_merge_org_patents_keeps_name_only_patents() -> None: + author = _author("A123", "Max Mustermann") + result = merge_org_patents( + institution_id="I62318514", + institution_name="University of Duisburg-Essen", + institution_patents=[], + author_patents=[(author, [_patent("EP222")])], + ) + + assert len(result) == 1 + assert result[0].match_type == "name" + assert result[0].matched_authors[0].openalex_author_id == "A123" + + +def test_merge_org_patents_marks_both_when_same_patent_found_twice() -> None: + author = _author("A123", "Max Mustermann") + patent = _patent("EP333") + result = merge_org_patents( + institution_id="I62318514", + institution_name="University of Duisburg-Essen", + institution_patents=[patent], + author_patents=[(author, [patent])], + ) + + assert len(result) == 1 + assert result[0].match_type == "both" + assert len(result[0].matched_authors) == 1 + + +def test_merge_org_patents_deduplicates_and_collects_multiple_authors() -> None: + author_one = _author("A111", "Max Mustermann") + author_two = _author("A222", "Maria Muster") + patent = _patent("EP444") + result = merge_org_patents( + institution_id="I62318514", + institution_name="University of Duisburg-Essen", + institution_patents=[], + author_patents=[ + (author_one, [patent]), + (author_two, [patent]), + ], + ) + + assert len(result) == 1 + assert result[0].match_type == "name" + assert {author.openalex_author_id for author in result[0].matched_authors} == {"A111", "A222"} + + +def test_org_patent_document_id_is_stable() -> None: + patent = _patent("EP1234567") + patent.kind = "A1" + patent.publication_date = "20240101" + + doc_id = org_patent_document_id("I62318514", patent) + + assert doc_id == "I62318514_EPO_EP1234567_20240101_A1" diff --git a/service/src/main/inse/patents/search_client.py b/service/src/main/inse/patents/search_client.py new file mode 100644 index 00000000..38feee9e --- /dev/null +++ b/service/src/main/inse/patents/search_client.py @@ -0,0 +1,27 @@ +"""Combined patent Elasticsearch client.""" +from inse.patents.authors.search_queries import InventorSearchQueries +from inse.patents.common.elastic_search_client import ( + DEFAULT_SEARCH_SIZE, + EPO_INDEX, + USPTO_INDEX, + BasePatentSearchClient, + MissingApiKeyError, +) +from inse.patents.institutions.search_queries import AssigneeSearchQueries + + +class PatentSearchClient( + InventorSearchQueries, + AssigneeSearchQueries, + BasePatentSearchClient, +): + pass + + +__all__ = [ + "DEFAULT_SEARCH_SIZE", + "EPO_INDEX", + "MissingApiKeyError", + "PatentSearchClient", + "USPTO_INDEX", +] diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py index 0aff125a..39b30968 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -1,5 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +"""Aggregates patent API routers.""" from fastapi import APIRouter from . import logic from . import model @@ -11,6 +10,10 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"]) +from inse.patents.all.service import router as all_patents_router +from inse.patents.authors.service import router as author_patents_router +from inse.patents.institutions.service import router as institution_patents_router + @router.get( "/{author_id}/patents", @@ -37,8 +40,11 @@ async def get_patent_by_identifier( description="Do we want to fallback to title search if ID and DOI dont work?" ), ] = "", + filling_date: Annotated[ + Optional[str], Query(description="Filling date in YYYY-MM-DD format") + ] = "", ) -> model.PatentEntry | None: - return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title) + return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title,filling_date=filling_date) @patents_router.get( diff --git a/service/src/main/inse/patents/test_institution_matching.py b/service/src/main/inse/patents/test_institution_matching.py new file mode 100644 index 00000000..3dc109cd --- /dev/null +++ b/service/src/main/inse/patents/test_institution_matching.py @@ -0,0 +1,83 @@ +from inse.patents import model +from inse.patents.institutions.logic import filter_patents_by_institution +from inse.patents.institutions.name_matching import ( + assignee_matches_institution_name, + institution_search_variants, +) + + +def test_institution_search_variants_exclude_single_letter_initials() -> None: + variants = institution_search_variants("Harvard University") + + assert "H" not in variants + assert "U" not in variants + assert any("Harvard" in variant for variant in variants) + + +def test_assignee_matches_institution_name_accepts_valid_university() -> None: + assert assignee_matches_institution_name( + "Universitaet Duisburg-Essen", + "University of Duisburg-Essen", + ) + assert assignee_matches_institution_name( + "President and Fellows of Harvard College", + "Harvard University", + ) + + +def test_assignee_matches_institution_name_rejects_false_positives() -> None: + assert not assignee_matches_institution_name("u-blox AG", "Harvard University") + assert not assignee_matches_institution_name( + "LG H&H CO., LTD.", + "Harvard University", + ) + assert not assignee_matches_institution_name( + "K & N Engineering, Inc.", + "National Institute for Fusion Science", + ) + assert not assignee_matches_institution_name( + "K&K INC.", + "National Institute for Fusion Science", + ) + + +def test_filter_patents_by_institution_removes_unrelated_assignees() -> None: + institution = _institution( + display_name="Harvard University", + alternatives=["Universidad de Harvard"], + ) + patents = [ + model.PatentEntry( + patent_id="US1", + source="USPTO", + assignees=["President and Fellows of Harvard College"], + ), + model.PatentEntry( + patent_id="US2", + source="USPTO", + assignees=["u-blox AG"], + ), + model.PatentEntry( + patent_id="US3", + source="USPTO", + assignees=["LG H&H CO., LTD."], + ), + ] + + result = filter_patents_by_institution(patents, institution) + + assert len(result) == 1 + assert result[0].patent_id == "US1" + + +def _institution( + display_name: str, + alternatives: list[str] | None = None, +): + from inse.models.openalex.institution import Institution + + return Institution( + id="https://openalex.org/I123", + display_name=display_name, + display_name_alternatives=alternatives, + ) diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py index 6c81e218..5e60288d 100644 --- a/service/src/main/inse/patents/test_logic.py +++ b/service/src/main/inse/patents/test_logic.py @@ -1,4 +1,6 @@ -from inse.patents import logic, model +from inse.patents import model +from inse.patents.common.parsing import deduplicate_patents +from inse.patents.institutions.logic import filter_patents_by_institution def _uspto_patent( @@ -34,7 +36,7 @@ def _epo_patent( def test_deduplicate_patents_removes_exact_duplicates() -> None: patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()] - result = logic._deduplicate_patents(patents) + result = deduplicate_patents(patents) assert len(result) == 1 assert result[0].patent_id == "US12508845" @@ -43,7 +45,7 @@ def test_deduplicate_patents_removes_exact_duplicates() -> None: def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None: patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")] - result = logic._deduplicate_patents(patents) + result = deduplicate_patents(patents) assert len(result) == 2 assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"] @@ -55,7 +57,7 @@ def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None duplicate = _uspto_patent() duplicate.abstract = "Second abstract" - result = logic._deduplicate_patents([first, duplicate]) + result = deduplicate_patents([first, duplicate]) assert len(result) == 1 assert result[0].abstract == "First abstract" @@ -65,7 +67,7 @@ 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]) + result = deduplicate_patents([application, grant]) assert len(result) == 2 assert [patent.kind for patent in result] == ["A1", "B1"] @@ -75,7 +77,7 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() -> earlier = _uspto_patent(publication_date="20241230") later = _uspto_patent(publication_date="20251230") - result = logic._deduplicate_patents([earlier, later]) + result = deduplicate_patents([earlier, later]) assert len(result) == 2 assert [patent.publication_date for patent in result] == ["20241230", "20251230"] @@ -85,7 +87,58 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types utility = _uspto_patent(application_type="utility") reissue = _uspto_patent(application_type="reissue") - result = logic._deduplicate_patents([utility, reissue]) + result = deduplicate_patents([utility, reissue]) assert len(result) == 2 assert [patent.application_type for patent in result] == ["utility", "reissue"] + + +def test_assignee_matches_institution_name_accepts_alternative_names() -> None: + from inse.patents.name_matching import assignee_matches_institution_name + + assert assignee_matches_institution_name( + "Universitaet Duisburg-Essen", + "University of Duisburg-Essen", + ) + assert not assignee_matches_institution_name( + "Harvard University", + "University of Duisburg-Essen", + ) + + +def test_filter_patents_by_institution_keeps_matching_assignees() -> None: + institution = _institution( + display_name="University of Duisburg-Essen", + alternatives=["Universität Duisburg-Essen"], + ) + matching = model.PatentEntry( + patent_id="EP123", + source="EPO", + assignees=["University of Duisburg-Essen"], + ) + other = model.PatentEntry( + patent_id="EP456", + source="EPO", + assignees=["Harvard University"], + ) + + result = filter_patents_by_institution( + [matching, other], + institution, + ) + + assert len(result) == 1 + assert result[0].patent_id == "EP123" + + +def _institution( + display_name: str, + alternatives: list[str] | None = None, +): + from inse.models.openalex.institution import Institution + + return Institution( + id="https://openalex.org/I123", + display_name=display_name, + display_name_alternatives=alternatives, + ) diff --git a/webapp/openapitools.json b/webapp/openapitools.json index 7af6e36f..a20f2fa7 100644 --- a/webapp/openapitools.json +++ b/webapp/openapitools.json @@ -12,9 +12,9 @@ "ngVersion": "21.2.14", "providedInRoot": true, "serviceSuffix": "Service", - "withInterfaces": true, + "withInterfaces": false, "enumPropertyNaming": "original", - "fileNaming": "kebab-case" + "fileNaming": "camelCase" } } } diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index b7a3c1d3..f9ac2e32 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -9,6 +9,7 @@ api/companyConnections.service.ts api/funding.service.ts api/iNSEService.service.ts api/institutions.service.ts +api/keywords.service.ts api/news.service.ts api/organization.service.ts api/patents.service.ts @@ -72,6 +73,9 @@ model/euCordisProjectResponse.ts model/euOrganizationProjectSummary.ts model/euOrganizationProjectSummaryPage.ts model/euProjectData.ts +model/extractedKeywords.ts +model/extractedKeywordsLLM.ts +model/extractedKeywordsResponse.ts model/filterInformation.ts model/filterProperties.ts model/fp7EurosciVoc.ts @@ -109,7 +113,7 @@ model/hEUReportSummary.ts model/hEUTopic.ts model/hEUWebLink.ts model/hTTPValidationError.ts -model/idToken.ts +model/idTokenMetadata.ts model/inseAccountManagementModelOrganizationProfile.ts model/inseOrganizationManagementModelOrganizationProfile.ts model/institution.ts @@ -121,11 +125,18 @@ model/institutionNetworkNode.ts model/institutionPage.ts model/institutionsListResponse.ts model/ipcClassification.ts +model/keywordEntry.ts +model/keywordEntryWithTopic.ts +model/keywordTopicMatch.ts model/keywords.ts +model/keywordsRequest.ts +model/keywordsTopicsRequest.ts +model/keywordsTopicsResponse.ts model/latitude.ts model/location.ts model/loginResponse.ts model/longitude.ts +model/matchedAuthor.ts model/matchedOfficer.ts model/mentionedPerson.ts model/meta.ts @@ -135,9 +146,13 @@ model/newsArticle.ts model/newsArticleDetail.ts model/newsPage.ts model/openAccess.ts +model/orgPatentEntry.ts +model/orgPatentsResponse.ts model/organizationPage.ts +model/otkResponse.ts model/patentEntry.ts model/patentsByAuthorResponse.ts +model/patentsByInstitutionResponse.ts model/personBio.ts model/projectType.ts model/projectsFilteringProperties.ts @@ -146,7 +161,6 @@ model/publicationDetailByFunder.ts model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/rankingResponse.ts -model/refreshToken.ts model/score.ts model/sortDirection.ts model/tokenType.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index e7f2ddc4..8ea55e0b 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -8,6 +8,8 @@ export * from './iNSEService.service'; import { INSEServiceService } from './iNSEService.service'; export * from './institutions.service'; import { InstitutionsService } from './institutions.service'; +export * from './keywords.service'; +import { KeywordsService } from './keywords.service'; export * from './news.service'; import { NewsService } from './news.service'; export * from './organization.service'; @@ -30,6 +32,7 @@ export const APIS = [ FundingService, INSEServiceService, InstitutionsService, + KeywordsService, NewsService, OrganizationService, PatentsService, diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 6f269457..7fe92c42 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -47,6 +47,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco // @ts-ignore import { LoginResponse } from '../model/loginResponse'; // @ts-ignore +import { OtkResponse } from '../model/otkResponse'; +// @ts-ignore import { UpdateAccountRequest } from '../model/updateAccountRequest'; // @ts-ignore @@ -71,11 +73,13 @@ export class AuthService extends BaseService { * Change the user\'s password and invalidate existing tokens. * @endpoint post /api/auth/v2/change-password * @param bodyChangePassword + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public changePassword( bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -86,6 +90,7 @@ export class AuthService extends BaseService { ): Observable; public changePassword( bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -96,6 +101,7 @@ export class AuthService extends BaseService { ): Observable>; public changePassword( bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -106,6 +112,7 @@ export class AuthService extends BaseService { ): Observable>; public changePassword( bodyChangePassword: BodyChangePassword, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -189,11 +196,13 @@ export class AuthService extends BaseService { * Create Account * @endpoint post /api/accounts * @param createAccountRequest + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public createAccount( createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -204,6 +213,7 @@ export class AuthService extends BaseService { ): Observable; public createAccount( createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -214,6 +224,7 @@ export class AuthService extends BaseService { ): Observable>; public createAccount( createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -224,6 +235,7 @@ export class AuthService extends BaseService { ): Observable>; public createAccount( createAccountRequest: CreateAccountRequest, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -311,11 +323,13 @@ export class AuthService extends BaseService { * Delete Account * @endpoint delete /api/accounts/{account_id} * @param accountId + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public deleteAccount( accountId: string, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -326,6 +340,7 @@ export class AuthService extends BaseService { ): Observable; public deleteAccount( accountId: string, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -336,6 +351,7 @@ export class AuthService extends BaseService { ): Observable>; public deleteAccount( accountId: string, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -346,6 +362,7 @@ export class AuthService extends BaseService { ): Observable>; public deleteAccount( accountId: string, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -422,11 +439,13 @@ export class AuthService extends BaseService { * Retrieve an access token for the authenticated user. * @endpoint post /api/auth/v2/access * @param bodyGetAccessToken + * @param idToken * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public getAccessToken( bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -437,6 +456,7 @@ export class AuthService extends BaseService { ): Observable; public getAccessToken( bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -447,6 +467,7 @@ export class AuthService extends BaseService { ): Observable>; public getAccessToken( bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -457,6 +478,7 @@ export class AuthService extends BaseService { ): Observable>; public getAccessToken( bodyGetAccessToken: BodyGetAccessToken, + idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -473,14 +495,6 @@ export class AuthService extends BaseService { let localVarHeaders = this.defaultHeaders; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'HTTPBearer', - 'Authorization', - localVarHeaders, - 'Bearer ', - ); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept(['application/json']); @@ -543,10 +557,12 @@ export class AuthService extends BaseService { /** * Get Current Account * @endpoint get /api/accounts/me + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public getCurrentAccount( + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -556,6 +572,7 @@ export class AuthService extends BaseService { }, ): Observable; public getCurrentAccount( + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -565,6 +582,7 @@ export class AuthService extends BaseService { }, ): Observable>; public getCurrentAccount( + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -574,6 +592,7 @@ export class AuthService extends BaseService { }, ): Observable>; public getCurrentAccount( + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -729,10 +748,12 @@ export class AuthService extends BaseService { /** * List Organizations * @endpoint get /api/accounts/organizations + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public listAccountOrganizations( + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -742,6 +763,7 @@ export class AuthService extends BaseService { }, ): Observable>; public listAccountOrganizations( + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -753,6 +775,7 @@ export class AuthService extends BaseService { HttpResponse> >; public listAccountOrganizations( + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -764,6 +787,7 @@ export class AuthService extends BaseService { HttpEvent> >; public listAccountOrganizations( + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -835,6 +859,7 @@ export class AuthService extends BaseService { * @param offset * @param search * @param organizationId + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -844,6 +869,7 @@ export class AuthService extends BaseService { offset?: number, search?: string, organizationId?: string, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -858,6 +884,7 @@ export class AuthService extends BaseService { offset?: number, search?: string, organizationId?: string, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -872,6 +899,7 @@ export class AuthService extends BaseService { offset?: number, search?: string, organizationId?: string, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -886,6 +914,7 @@ export class AuthService extends BaseService { offset?: number, search?: string, organizationId?: string, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -1098,10 +1127,12 @@ export class AuthService extends BaseService { * Logout * Logout the authenticated user. * @endpoint post /api/auth/v2/logout + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public logout( + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -1111,6 +1142,7 @@ export class AuthService extends BaseService { }, ): Observable; public logout( + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -1120,6 +1152,7 @@ export class AuthService extends BaseService { }, ): Observable>; public logout( + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -1129,6 +1162,7 @@ export class AuthService extends BaseService { }, ): Observable>; public logout( + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -1194,10 +1228,12 @@ export class AuthService extends BaseService { * Refresh Access Token * Refresh the access token using a valid refresh token. * @endpoint post /api/auth/v2/refresh + * @param refreshToken * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public refreshAccessToken( + refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -1207,6 +1243,7 @@ export class AuthService extends BaseService { }, ): Observable; public refreshAccessToken( + refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -1216,6 +1253,7 @@ export class AuthService extends BaseService { }, ): Observable>; public refreshAccessToken( + refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -1225,6 +1263,7 @@ export class AuthService extends BaseService { }, ): Observable>; public refreshAccessToken( + refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -1235,14 +1274,6 @@ export class AuthService extends BaseService { ): Observable { let localVarHeaders = this.defaultHeaders; - // authentication (HTTPBearer) required - localVarHeaders = this.configuration.addCredentialToHeaders( - 'HTTPBearer', - 'Authorization', - localVarHeaders, - 'Bearer ', - ); - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept(['application/json']); @@ -1307,7 +1338,7 @@ export class AuthService extends BaseService { context?: HttpContext; transferCache?: boolean; }, - ): Observable; + ): Observable; public requestOtk( bodyRequestOtk: BodyRequestOtk, observe?: 'response', @@ -1317,7 +1348,7 @@ export class AuthService extends BaseService { context?: HttpContext; transferCache?: boolean; }, - ): Observable>; + ): Observable>; public requestOtk( bodyRequestOtk: BodyRequestOtk, observe?: 'events', @@ -1327,7 +1358,7 @@ export class AuthService extends BaseService { context?: HttpContext; transferCache?: boolean; }, - ): Observable>; + ): Observable>; public requestOtk( bodyRequestOtk: BodyRequestOtk, observe: any = 'body', @@ -1387,18 +1418,22 @@ export class AuthService extends BaseService { let localVarPath = `/api/auth/v2/request-otk`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('post', `${basePath}${localVarPath}`, { - context: localVarHttpContext, - body: bodyRequestOtk, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }); + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyRequestOtk, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); } /** @@ -1406,12 +1441,14 @@ export class AuthService extends BaseService { * @endpoint put /api/accounts/{account_id} * @param accountId * @param updateAccountRequest + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public updateAccount( accountId: string, updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -1423,6 +1460,7 @@ export class AuthService extends BaseService { public updateAccount( accountId: string, updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -1434,6 +1472,7 @@ export class AuthService extends BaseService { public updateAccount( accountId: string, updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -1445,6 +1484,7 @@ export class AuthService extends BaseService { public updateAccount( accountId: string, updateAccountRequest: UpdateAccountRequest, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { diff --git a/webapp/src/app/api/api/keywords.service.ts b/webapp/src/app/api/api/keywords.service.ts new file mode 100644 index 00000000..172d077c --- /dev/null +++ b/webapp/src/app/api/api/keywords.service.ts @@ -0,0 +1,162 @@ +/** + * 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 { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { KeywordsRequest } from '../model/keywordsRequest'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + +@Injectable({ + providedIn: 'root', +}) +export class KeywordsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } + + /** + * Extracts keywords from text. + * @endpoint post /api/inse-service/keywords/extract + * @param keywordsRequest + * @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 extractKeywords( + keywordsRequest: KeywordsRequest, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public extractKeywords( + keywordsRequest: KeywordsRequest, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public extractKeywords( + keywordsRequest: KeywordsRequest, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public extractKeywords( + keywordsRequest: KeywordsRequest, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (keywordsRequest === null || keywordsRequest === undefined) { + throw new Error( + 'Required parameter keywordsRequest was null or undefined when calling extractKeywords.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/keywords/extract`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: keywordsRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/api/api/organization.service.ts b/webapp/src/app/api/api/organization.service.ts index 69fa3159..4315e7c1 100644 --- a/webapp/src/app/api/api/organization.service.ts +++ b/webapp/src/app/api/api/organization.service.ts @@ -54,11 +54,13 @@ export class OrganizationService extends BaseService { * Create Organization * @endpoint post /api/organizations * @param createOrganizationRequest + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public createOrganisation( createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -69,6 +71,7 @@ export class OrganizationService extends BaseService { ): Observable; public createOrganisation( createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -81,6 +84,7 @@ export class OrganizationService extends BaseService { >; public createOrganisation( createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -91,6 +95,7 @@ export class OrganizationService extends BaseService { ): Observable>; public createOrganisation( createOrganizationRequest: CreateOrganizationRequest, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -181,11 +186,13 @@ export class OrganizationService extends BaseService { * Delete Organization * @endpoint delete /api/organizations/{organization_id} * @param organizationId + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public deleteOrganisation( organizationId: string, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -196,6 +203,7 @@ export class OrganizationService extends BaseService { ): Observable; public deleteOrganisation( organizationId: string, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -206,6 +214,7 @@ export class OrganizationService extends BaseService { ): Observable>; public deleteOrganisation( organizationId: string, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -216,6 +225,7 @@ export class OrganizationService extends BaseService { ): Observable>; public deleteOrganisation( organizationId: string, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -293,6 +303,7 @@ export class OrganizationService extends BaseService { * @param page * @param pageSize * @param offset + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -300,6 +311,7 @@ export class OrganizationService extends BaseService { page?: number, pageSize?: number, offset?: number, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -312,6 +324,7 @@ export class OrganizationService extends BaseService { page?: number, pageSize?: number, offset?: number, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -324,6 +337,7 @@ export class OrganizationService extends BaseService { page?: number, pageSize?: number, offset?: number, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -336,6 +350,7 @@ export class OrganizationService extends BaseService { page?: number, pageSize?: number, offset?: number, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -424,12 +439,14 @@ export class OrganizationService extends BaseService { * @endpoint put /api/organizations/{organization_id} * @param organizationId * @param updateOrganizationRequest + * @param secureFgpAcc * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public updateOrganisation( organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -441,6 +458,7 @@ export class OrganizationService extends BaseService { public updateOrganisation( organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -454,6 +472,7 @@ export class OrganizationService extends BaseService { public updateOrganisation( organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -465,6 +484,7 @@ export class OrganizationService extends BaseService { public updateOrganisation( organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, + secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: { diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index d08ec699..904279c3 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -27,9 +27,13 @@ import { AllPatentsResponse } from '../model/allPatentsResponse'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { OrgPatentsResponse } from '../model/orgPatentsResponse'; +// @ts-ignore import { PatentEntry } from '../model/patentEntry'; // @ts-ignore import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; +// @ts-ignore +import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -202,12 +206,158 @@ export class PatentsService extends BaseService { ); } + /** + * Get pre-indexed org patents for an institution. + * @endpoint get /api/inse-service/institutions/{id}/org-patents + * @param id + * @param matchType Filter patents by match type. + * @param page + * @param size + * @param source + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrgPatentsByInstitution( + id: string, + matchType?: 'institution' | 'name' | 'both' | 'all', + page?: number, + size?: number, + source?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getOrgPatentsByInstitution( + id: string, + matchType?: 'institution' | 'name' | 'both' | 'all', + page?: number, + size?: number, + source?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrgPatentsByInstitution( + id: string, + matchType?: 'institution' | 'name' | 'both' | 'all', + page?: number, + size?: number, + source?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getOrgPatentsByInstitution( + id: string, + matchType?: 'institution' | 'name' | 'both' | 'all', + page?: number, + size?: number, + source?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getOrgPatentsByInstitution.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + matchType, + 'match_type', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + source, + 'source', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/org-patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Returns one publication by OpenAlex ID or DOI. * @endpoint get /api/inse-service/patents/{identifier} * @param identifier * @param prefix Application Prefix (EP or US) * @param title Do we want to fallback to title search if ID and DOI dont work? + * @param fillingDate Filling date in YYYY-MM-DD format * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -215,6 +365,7 @@ export class PatentsService extends BaseService { identifier: string, prefix?: string, title?: string, + fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -227,6 +378,7 @@ export class PatentsService extends BaseService { identifier: string, prefix?: string, title?: string, + fillingDate?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -239,6 +391,7 @@ export class PatentsService extends BaseService { identifier: string, prefix?: string, title?: string, + fillingDate?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -251,6 +404,7 @@ export class PatentsService extends BaseService { identifier: string, prefix?: string, title?: string, + fillingDate?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -276,6 +430,11 @@ export class PatentsService extends BaseService { title, 'title', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + fillingDate, + 'filling_date', + ); let localVarHeaders = this.defaultHeaders; @@ -428,4 +587,106 @@ export class PatentsService extends BaseService { }, ); } + + /** + * Get patents matched to an institution by assignee name. + * @endpoint get /api/inse-service/institutions/{id}/patents + * @param id + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPatentsByInstitution( + id: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPatentsByInstitution( + id: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentsByInstitution( + id: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentsByInstitution( + id: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getPatentsByInstitution.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/api/topics.service.ts b/webapp/src/app/api/api/topics.service.ts index 1e6bf279..5a51e233 100644 --- a/webapp/src/app/api/api/topics.service.ts +++ b/webapp/src/app/api/api/topics.service.ts @@ -27,6 +27,10 @@ import { AutocompleteResponse } from '../model/autocompleteResponse'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { KeywordsTopicsRequest } from '../model/keywordsTopicsRequest'; +// @ts-ignore +import { KeywordsTopicsResponse } from '../model/keywordsTopicsResponse'; +// @ts-ignore import { TopicsListResponse } from '../model/topicsListResponse'; // @ts-ignore @@ -828,4 +832,131 @@ export class TopicsService extends BaseService { }, ); } + + /** + * Batch semantic / vector search for multiple keywords. + * @endpoint post /api/topics/vector-search/batch + * @param keywordsTopicsRequest + * @param searchType Search approach: \'hybrid\' or \'semantic\'. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public vectorSearchTopicsBatch( + keywordsTopicsRequest: KeywordsTopicsRequest, + searchType?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public vectorSearchTopicsBatch( + keywordsTopicsRequest: KeywordsTopicsRequest, + searchType?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public vectorSearchTopicsBatch( + keywordsTopicsRequest: KeywordsTopicsRequest, + searchType?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public vectorSearchTopicsBatch( + keywordsTopicsRequest: KeywordsTopicsRequest, + searchType?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (keywordsTopicsRequest === null || keywordsTopicsRequest === undefined) { + throw new Error( + 'Required parameter keywordsTopicsRequest was null or undefined when calling vectorSearchTopicsBatch.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + searchType, + 'searchType', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/topics/vector-search/batch`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: keywordsTopicsRequest, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/model/accessResponse.ts b/webapp/src/app/api/model/accessResponse.ts index 6ea36bce..2a188f73 100644 --- a/webapp/src/app/api/model/accessResponse.ts +++ b/webapp/src/app/api/model/accessResponse.ts @@ -7,7 +7,6 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { RefreshToken } from './refreshToken'; import { AccessToken } from './accessToken'; export interface AccessResponse { @@ -15,8 +14,4 @@ export interface AccessResponse { * The access token issued upon successful authentication. */ access_token: AccessToken; - /** - * The refresh token issued alongside the access token for obtaining new access tokens. - */ - refresh_token: RefreshToken; } diff --git a/webapp/src/app/api/model/accessToken.ts b/webapp/src/app/api/model/accessToken.ts index 2f20bcef..405d3521 100644 --- a/webapp/src/app/api/model/accessToken.ts +++ b/webapp/src/app/api/model/accessToken.ts @@ -11,10 +11,6 @@ import { TokenType } from './tokenType'; import { UserRole } from './userRole'; export interface AccessToken { - /** - * The type of the token, which is always ACCESS_TOKEN for this class. - */ - token_type?: TokenType; /** * The unique identifier of the real account associated with this token. */ @@ -28,13 +24,13 @@ export interface AccessToken { */ epoch?: number; /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. + * The type of the token, which is always ACCESS_TOKEN for this class. + */ + token_type?: TokenType; + /** + * A unique fingerprint of the user, used for additional security checks. */ user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; /** * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. */ @@ -47,5 +43,9 @@ export interface AccessToken { * The unique identifier of the organization associated with this access token. */ effective_organization_id: string; + /** + * The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes. + */ + raw_token: string; } export namespace AccessToken {} diff --git a/webapp/src/app/api/model/accountProfile.ts b/webapp/src/app/api/model/accountProfile.ts index 6777791a..b40876f2 100644 --- a/webapp/src/app/api/model/accountProfile.ts +++ b/webapp/src/app/api/model/accountProfile.ts @@ -17,6 +17,7 @@ export interface AccountProfile { organization_id: string; organization_name: string; deleted: boolean; + activated: boolean; is_current?: boolean; is_real_account?: boolean; is_impersonating?: boolean; diff --git a/webapp/src/app/api/model/extractedKeywords.ts b/webapp/src/app/api/model/extractedKeywords.ts new file mode 100644 index 00000000..4038c211 --- /dev/null +++ b/webapp/src/app/api/model/extractedKeywords.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { KeywordEntryWithTopic } from './keywordEntryWithTopic'; + +export interface ExtractedKeywords { + /** + * The extracted broad keywords from text. + */ + broad_keywords: Array; + /** + * The extracted coarse-grained keywords from text. + */ + coarse_grained: Array; + /** + * The extracted fine-grained keywords from text. + */ + fine_grained: Array; +} diff --git a/webapp/src/app/api/model/extractedKeywordsLLM.ts b/webapp/src/app/api/model/extractedKeywordsLLM.ts new file mode 100644 index 00000000..b49b98d7 --- /dev/null +++ b/webapp/src/app/api/model/extractedKeywordsLLM.ts @@ -0,0 +1,25 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { KeywordEntry } from './keywordEntry'; + +export interface ExtractedKeywordsLLM { + /** + * The extracted broad keywords from text. + */ + broad_keywords: Array; + /** + * The extracted coarse-grained keywords from text. + */ + coarse_grained: Array; + /** + * The extracted fine-grained keywords from text. + */ + fine_grained: Array; +} diff --git a/webapp/src/app/api/model/extractedKeywordsResponse.ts b/webapp/src/app/api/model/extractedKeywordsResponse.ts new file mode 100644 index 00000000..8fe10a5f --- /dev/null +++ b/webapp/src/app/api/model/extractedKeywordsResponse.ts @@ -0,0 +1,26 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { ExtractedKeywordsLLM } from './extractedKeywordsLLM'; +import { ExtractedKeywords } from './extractedKeywords'; + +export interface ExtractedKeywordsResponse { + results_llm?: ExtractedKeywordsLLM | null; + results?: ExtractedKeywords | null; + /** + * The source of the input text, e.g., \'url\', \'text\', or \'keywords\'. + */ + source: string; + source_url?: string | null; + /** + * The actual content from which keywords were extracted. + */ + source_content: string; + duration?: number | null; +} diff --git a/webapp/src/app/api/model/idToken.ts b/webapp/src/app/api/model/idTokenMetadata.ts similarity index 73% rename from webapp/src/app/api/model/idToken.ts rename to webapp/src/app/api/model/idTokenMetadata.ts index 3d3cbc1f..ab99fb1c 100644 --- a/webapp/src/app/api/model/idToken.ts +++ b/webapp/src/app/api/model/idTokenMetadata.ts @@ -9,11 +9,7 @@ */ import { TokenType } from './tokenType'; -export interface IdToken { - /** - * The type of the token, which is always ID_TOKEN for this class. - */ - token_type?: TokenType; +export interface IdTokenMetadata { /** * The unique identifier of the real account associated with this token. */ @@ -27,12 +23,8 @@ export interface IdToken { */ epoch?: number; /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. + * The type of the token, which is always ID_TOKEN for this class. */ - user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; + token_type?: TokenType; } -export namespace IdToken {} +export namespace IdTokenMetadata {} diff --git a/webapp/src/app/api/model/keywordEntry.ts b/webapp/src/app/api/model/keywordEntry.ts new file mode 100644 index 00000000..94dd6e18 --- /dev/null +++ b/webapp/src/app/api/model/keywordEntry.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface KeywordEntry { + /** + * The extracted keyword. + */ + keyword: string; + /** + * The relevance score of the keyword. + */ + relevance_score: number; +} diff --git a/webapp/src/app/api/model/keywordEntryWithTopic.ts b/webapp/src/app/api/model/keywordEntryWithTopic.ts new file mode 100644 index 00000000..4670f554 --- /dev/null +++ b/webapp/src/app/api/model/keywordEntryWithTopic.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { KeywordEntry } from './keywordEntry'; +import { KeywordTopicMatch } from './keywordTopicMatch'; + +export interface KeywordEntryWithTopic { + /** + * The keyword extracted by the LLM. + */ + llm_keyword: KeywordEntry; + topic_mapping?: KeywordTopicMatch | null; +} diff --git a/webapp/src/app/api/model/keywordTopicMatch.ts b/webapp/src/app/api/model/keywordTopicMatch.ts new file mode 100644 index 00000000..ee4c8326 --- /dev/null +++ b/webapp/src/app/api/model/keywordTopicMatch.ts @@ -0,0 +1,15 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Topic } from './topic'; + +export interface KeywordTopicMatch { + keyword: string; + topic?: Topic | null; +} diff --git a/webapp/src/app/api/model/keywordsRequest.ts b/webapp/src/app/api/model/keywordsRequest.ts new file mode 100644 index 00000000..1860b68b --- /dev/null +++ b/webapp/src/app/api/model/keywordsRequest.ts @@ -0,0 +1,24 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface KeywordsRequest { + /** + * The input text from which to extract keywords. + */ + query: string; + /** + * The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'. + */ + mode: string; + /** + * The maximum number of keywords to extract. + */ + limit?: number; +} diff --git a/webapp/src/app/api/model/keywordsTopicsRequest.ts b/webapp/src/app/api/model/keywordsTopicsRequest.ts new file mode 100644 index 00000000..883ed079 --- /dev/null +++ b/webapp/src/app/api/model/keywordsTopicsRequest.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface KeywordsTopicsRequest { + /** + * List of keywords/sentences to query by similarity. + */ + keywords: Array; +} diff --git a/webapp/src/app/api/model/keywordsTopicsResponse.ts b/webapp/src/app/api/model/keywordsTopicsResponse.ts new file mode 100644 index 00000000..78a2f9d2 --- /dev/null +++ b/webapp/src/app/api/model/keywordsTopicsResponse.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { KeywordTopicMatch } from './keywordTopicMatch'; + +export interface KeywordsTopicsResponse { + /** + * Top matching topics for each keyword in the requested list. + */ + results: Array; +} diff --git a/webapp/src/app/api/model/loginResponse.ts b/webapp/src/app/api/model/loginResponse.ts index 216d0fb0..b0ccb902 100644 --- a/webapp/src/app/api/model/loginResponse.ts +++ b/webapp/src/app/api/model/loginResponse.ts @@ -7,11 +7,11 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { IdToken } from './idToken'; +import { IdTokenMetadata } from './idTokenMetadata'; export interface LoginResponse { /** * The ID token issued upon successful login. */ - id_token: IdToken; + id_token: IdTokenMetadata; } diff --git a/webapp/src/app/api/model/matchedAuthor.ts b/webapp/src/app/api/model/matchedAuthor.ts new file mode 100644 index 00000000..311e2184 --- /dev/null +++ b/webapp/src/app/api/model/matchedAuthor.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface MatchedAuthor { + openalex_author_id: string; + author_name: string; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index e8a70f23..3bf537d5 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -49,6 +49,9 @@ export * from './euCordisProjectResponse'; export * from './euOrganizationProjectSummary'; export * from './euOrganizationProjectSummaryPage'; export * from './euProjectData'; +export * from './extractedKeywords'; +export * from './extractedKeywordsLLM'; +export * from './extractedKeywordsResponse'; export * from './filterInformation'; export * from './filterProperties'; export * from './fp7EurosciVoc'; @@ -86,7 +89,7 @@ export * from './hEUReportSummary'; export * from './hEUTopic'; export * from './hEUWebLink'; export * from './hTTPValidationError'; -export * from './idToken'; +export * from './idTokenMetadata'; export * from './inseAccountManagementModelOrganizationProfile'; export * from './inseOrganizationManagementModelOrganizationProfile'; export * from './institution'; @@ -98,11 +101,18 @@ export * from './institutionNetworkNode'; export * from './institutionPage'; export * from './institutionsListResponse'; export * from './ipcClassification'; +export * from './keywordEntry'; +export * from './keywordEntryWithTopic'; +export * from './keywordTopicMatch'; export * from './keywords'; +export * from './keywordsRequest'; +export * from './keywordsTopicsRequest'; +export * from './keywordsTopicsResponse'; export * from './latitude'; export * from './location'; export * from './loginResponse'; export * from './longitude'; +export * from './matchedAuthor'; export * from './matchedOfficer'; export * from './mentionedPerson'; export * from './meta'; @@ -111,9 +121,13 @@ export * from './newsArticle'; export * from './newsArticleDetail'; export * from './newsPage'; export * from './openAccess'; +export * from './orgPatentEntry'; +export * from './orgPatentsResponse'; export * from './organizationPage'; +export * from './otkResponse'; export * from './patentEntry'; export * from './patentsByAuthorResponse'; +export * from './patentsByInstitutionResponse'; export * from './personBio'; export * from './projectType'; export * from './projectsFilteringProperties'; @@ -122,7 +136,6 @@ export * from './publicationDetailByFunder'; export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './rankingResponse'; -export * from './refreshToken'; export * from './score'; export * from './sortDirection'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/orgPatentEntry.ts b/webapp/src/app/api/model/orgPatentEntry.ts new file mode 100644 index 00000000..7c4d0ce0 --- /dev/null +++ b/webapp/src/app/api/model/orgPatentEntry.ts @@ -0,0 +1,46 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { MatchedAuthor } from './matchedAuthor'; +import { IpcClassification } from './ipcClassification'; + +export interface OrgPatentEntry { + patent_id: string; + source: string; + title?: string | null; + abstract?: string | null; + publication_date?: string | null; + publication_year?: string | null; + application_number?: string | null; + application_date?: string | null; + kind?: string | null; + application_type?: string | null; + number_of_claims?: number | null; + status?: string | null; + inventors?: Array; + assignees?: Array; + ipc?: Array; + ipc_descriptions?: Array; + cpc?: Array; + cpc_descriptions?: Array; + country?: string | null; + institution_id: string; + institution_name?: string | null; + match_type: OrgPatentEntry.MatchTypeEnum; + matched_authors?: Array; +} +export namespace OrgPatentEntry { + export const MatchTypeEnum = { + Institution: 'institution', + Name: 'name', + Both: 'both', + } as const; + export type MatchTypeEnum = + (typeof MatchTypeEnum)[keyof typeof MatchTypeEnum]; +} diff --git a/webapp/src/app/api/model/orgPatentsResponse.ts b/webapp/src/app/api/model/orgPatentsResponse.ts new file mode 100644 index 00000000..68b2be7a --- /dev/null +++ b/webapp/src/app/api/model/orgPatentsResponse.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { OrgPatentEntry } from './orgPatentEntry'; + +export interface OrgPatentsResponse { + institution_id: string; + institution_name?: string | null; + patent_count: number; + page?: number; + size?: number; + patents: Array; +} diff --git a/webapp/src/app/api/model/otkResponse.ts b/webapp/src/app/api/model/otkResponse.ts new file mode 100644 index 00000000..3b69c11d --- /dev/null +++ b/webapp/src/app/api/model/otkResponse.ts @@ -0,0 +1,20 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface OtkResponse { + /** + * The status of the one-time code (OTC) request. + */ + status: string; + /** + * The unique identifier of the account for which the OTC was requested. + */ + account_id: string; +} diff --git a/webapp/src/app/api/model/patentsByInstitutionResponse.ts b/webapp/src/app/api/model/patentsByInstitutionResponse.ts new file mode 100644 index 00000000..d80972d0 --- /dev/null +++ b/webapp/src/app/api/model/patentsByInstitutionResponse.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { PatentEntry } from './patentEntry'; + +export interface PatentsByInstitutionResponse { + institution_id: string; + institution_name?: string | null; + patent_count: number; + patents: Array; +} diff --git a/webapp/src/app/api/model/refreshToken.ts b/webapp/src/app/api/model/refreshToken.ts deleted file mode 100644 index b09d9184..00000000 --- a/webapp/src/app/api/model/refreshToken.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { TokenType } from './tokenType'; -import { UserRole } from './userRole'; - -export interface RefreshToken { - /** - * The type of the token, which is always REFRESH_TOKEN for this class. - */ - token_type?: TokenType; - /** - * The unique identifier of the real account associated with this token. - */ - real_account_id: string; - /** - * The timestamp indicating when the token will expire. - */ - expires_at: string; - /** - * The epoch value for the token. Used for versioning of tokens. - */ - epoch?: number; - /** - * A hash of the user\'s fingerprint to ensure the token is used by the same user. - */ - user_fingerprint_hash: string; - /** - * The raw token string. - */ - raw_token: string; - /** - * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. - */ - effective_account_id: string; - /** - * The specific role this access token grants within its organization. - */ - effective_role?: UserRole; - /** - * The unique identifier of the organization associated with this access token. - */ - effective_organization_id: string; -} -export namespace RefreshToken {} diff --git a/webapp/src/app/api/model/tokenType.ts b/webapp/src/app/api/model/tokenType.ts index 58abaadf..88512eb6 100644 --- a/webapp/src/app/api/model/tokenType.ts +++ b/webapp/src/app/api/model/tokenType.ts @@ -9,8 +9,8 @@ */ export const TokenType = { - Id: 'ID', - Refresh: 'REFRESH', - Access: 'ACCESS', + IdToken: 'ID_TOKEN', + RefreshToken: 'REFRESH_TOKEN', + AccessToken: 'ACCESS_TOKEN', } as const; export type TokenType = (typeof TokenType)[keyof typeof TokenType]; diff --git a/webapp/src/app/api/model/updateAccountRequest.ts b/webapp/src/app/api/model/updateAccountRequest.ts index ca2e3cd6..f486df74 100644 --- a/webapp/src/app/api/model/updateAccountRequest.ts +++ b/webapp/src/app/api/model/updateAccountRequest.ts @@ -17,5 +17,6 @@ export interface UpdateAccountRequest { password?: string | null; openalex_person_id?: string | null; deleted?: boolean | null; + activated?: boolean | null; } export namespace UpdateAccountRequest {} diff --git a/webapp/src/app/app.config.ts b/webapp/src/app/app.config.ts index 3b700752..0d7f746c 100644 --- a/webapp/src/app/app.config.ts +++ b/webapp/src/app/app.config.ts @@ -5,6 +5,7 @@ import { Router, withComponentInputBinding, withNavigationErrorHandler, + withRouterConfig, } from '@angular/router'; import { routes } from './app.routes'; @@ -37,6 +38,7 @@ export const appConfig: ApplicationConfig = { provideRouter( routes, withComponentInputBinding(), + withRouterConfig({ onSameUrlNavigation: 'reload' }), withNavigationErrorHandler((navigationError: NavigationError) => { const router = inject(Router); const errorService = inject(ErrorService); diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index efc1388d..ac603aae 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -1,6 +1,5 @@ import { Routes } from '@angular/router'; import { userGuard } from './shared/guards/user.guard'; -import { adminGuard } from './shared/guards/admin.guard'; import { superAdminGuard } from './shared/guards/super-admin.guard'; import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver'; import { personListResolver } from './resolvers/person-list.resolver'; @@ -9,7 +8,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'; @@ -17,10 +15,13 @@ 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'; import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver'; import { publicationResolver } from './resolvers/publication-resolver'; import { accountResolver } from './resolvers/account.resolver'; +import { accountViewerGuard } from './shared/guards/account-viewer.guard'; +import { accountsPageResolver } from './resolvers/accounts-page.resolver'; +import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver'; +import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver'; export const routes: Routes = [ { @@ -83,6 +84,14 @@ export const routes: Routes = [ return scalarChanged || topicsChanged; }, }, + { + path: 'keywords', + canActivate: [userGuard], + loadComponent: () => + import('./modules/keywords-search/keywords-search.component').then( + (mod) => mod.KeywordsSearchComponent, + ), + }, { path: 'news', canActivate: [userGuard], @@ -102,11 +111,16 @@ export const routes: Routes = [ }, { path: 'accounts', - canActivate: [adminGuard], + canActivate: [accountViewerGuard], loadComponent: () => import('./modules/accounts/accounts.component').then( (mod) => mod.AccountsComponent, ), + resolve: { + accountPage: accountsPageResolver, + organizations: accountsOrganizationResolver, + }, + runGuardsAndResolvers: 'always', }, { path: 'organizations', @@ -115,7 +129,12 @@ export const routes: Routes = [ import('./modules/organizations/organizations.component').then( (mod) => mod.OrganizationsComponent, ), + resolve: { + organizationPage: organizationsOrganizationsResolver, + }, + runGuardsAndResolvers: 'always', }, + { path: 'news/:id', canActivate: [userGuard], @@ -135,6 +154,14 @@ export const routes: Routes = [ publication: publicationResolver, }, }, + { + path: 'patent/:patentId', + canActivate: [userGuard], + loadComponent: () => + import('./modules/patent-detail/patent-detail.component').then( + (mod) => mod.PatentDetailComponent, + ), + }, { path: 'projects/dfg/:id', canActivate: [userGuard], @@ -196,7 +223,7 @@ export const routes: Routes = [ ), resolve: { dfgProjectPage: dfgProjectsResolver, - personCordisEuProjectPage: personCordisEuProjectPageResolver, + personCordisEuProjectPage: cordisEuProjectPageResolver, }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; @@ -317,6 +344,13 @@ export const routes: Routes = [ ); }, }, + { + path: 'patents', + loadComponent: () => + import('./modules/institution-patents/institution-patents.component').then( + (mod) => mod.InstitutionPatentsComponent, + ), + }, ], }, { diff --git a/webapp/src/app/modules/account/account.component.html b/webapp/src/app/modules/account/account.component.html index 7590acb3..da753236 100644 --- a/webapp/src/app/modules/account/account.component.html +++ b/webapp/src/app/modules/account/account.component.html @@ -16,5 +16,58 @@ - + +
+
Passwort ändern
+
+ + Altes Passwort + + @if (oldPasswordErrorMessage()) { + {{ oldPasswordErrorMessage() }} + } + + +
+ + Neues Passwort + + @if (newPasswordErrorMessage()) { + {{ newPasswordErrorMessage() }} + } + + + + Neues Passwort wiederholen + + @if (newPasswordRepeatErrorMessage()) { + {{ newPasswordRepeatErrorMessage() }} + } + +
+ + Passwörter anzeigen + +
+ +
+
diff --git a/webapp/src/app/modules/account/account.component.scss b/webapp/src/app/modules/account/account.component.scss index 25c46861..ff03e82e 100644 --- a/webapp/src/app/modules/account/account.component.scss +++ b/webapp/src/app/modules/account/account.component.scss @@ -42,3 +42,25 @@ font-weight: 600; color: var(--sg-text-muted); } + +.settings-tab { + padding: 1rem; + max-width: 50%; + display: flex; + flex-direction: column; + gap: 1rem; +} + +.change-password-form { + display: flex; + flex-direction: column; + gap: 1.5rem; +} + +.new-password-fields { + display: flex; + gap: 1rem; + > mat-form-field { + width: 100%; + } +} diff --git a/webapp/src/app/modules/account/account.component.ts b/webapp/src/app/modules/account/account.component.ts index 7a953dee..647e5a99 100644 --- a/webapp/src/app/modules/account/account.component.ts +++ b/webapp/src/app/modules/account/account.component.ts @@ -1,21 +1,172 @@ -import { Component, effect, input } from '@angular/core'; +import { + Component, + computed, + effect, + inject, + input, + signal, +} from '@angular/core'; import { AccountProfile, UserRole } from '../../api'; import { RolePipe } from '../../shared/pipes/role.pipe'; import { MatChipsModule } from '@angular/material/chips'; import { MatTabsModule } from '@angular/material/tabs'; import { MatDividerModule } from '@angular/material/divider'; +import { MatInputModule } from '@angular/material/input'; +import { FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { + form, + FormField, + maxLength, + minLength, + required, + validate, + FormRoot, +} from '@angular/forms/signals'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { MatSlideToggleModule } from '@angular/material/slide-toggle'; +import { CredentialService } from '../../shared/services/credential.service'; +import { MatSnackBar } from '@angular/material/snack-bar'; + +interface ChangePasswordForm { + oldPassword: string; + newPassword: string; + newPasswordRepeat: string; + showPasswords: boolean; +} @Component({ selector: 'app-account', - imports: [RolePipe, MatChipsModule, MatTabsModule, MatDividerModule], + imports: [ + RolePipe, + MatChipsModule, + MatTabsModule, + MatDividerModule, + MatInputModule, + FormsModule, + ReactiveFormsModule, + MatFormFieldModule, + MatDividerModule, + MatIconModule, + MatButtonModule, + MatSlideToggleModule, + FormField, + FormRoot, + ], templateUrl: './account.component.html', styleUrl: './account.component.scss', }) export class AccountComponent { readonly accountProfile = input.required(); + private readonly _credentialService = inject(CredentialService); + private readonly _snackBar = inject(MatSnackBar); + roles: UserRole[] = []; + changePasswordModel = signal({ + oldPassword: '', + newPassword: '', + newPasswordRepeat: '', + showPasswords: false, + }); + + oldPasswordErrorMessage = computed(() => { + const errors = this.changePasswordForm.oldPassword().errors(); + return errors.length > 0 && errors[0].message ? errors[0].message : null; + }); + + newPasswordErrorMessage = computed(() => { + const errors = this.changePasswordForm.newPassword().errors(); + return errors.length > 0 && errors[0].message ? errors[0].message : null; + }); + + newPasswordRepeatErrorMessage = computed(() => { + const errors = this.changePasswordForm.newPasswordRepeat().errors(); + return errors.length > 0 && errors[0].message ? errors[0].message : null; + }); + + changePasswordForm = form( + this.changePasswordModel, + (schemaPath) => { + required(schemaPath.oldPassword, { + message: 'Altes Passwort ist erforderlich.', + }); + required(schemaPath.newPassword, { + message: 'Neues Passwort ist erforderlich.', + }); + required(schemaPath.newPasswordRepeat, { + message: 'Neues Passwort wiederholen ist erforderlich.', + }); + + minLength(schemaPath.newPassword, 8, { + message: 'Neues Passwort muss mindestens 8 Zeichen lang sein.', + }); + maxLength(schemaPath.newPassword, 64, { + message: 'Neues Passwort darf maximal 64 Zeichen lang sein.', + }); + + validate(schemaPath.newPasswordRepeat, ({ value, valueOf }) => { + const newPassword = valueOf(schemaPath.newPassword).trim(); + const newPasswordRepeat = value().trim(); + + if (newPassword !== newPasswordRepeat) { + return { + kind: 'passwordMismatch', + message: 'Passwörter stimmen nicht überein.', + }; + } + + return null; + }); + + validate(schemaPath.newPassword, ({ value }) => { + const oldPassword = this.changePasswordModel().oldPassword.trim(); + const newPassword = value().trim(); + + if (oldPassword && newPassword && oldPassword === newPassword) { + return { + kind: 'passwordSameAsOld', + message: + 'Neues Passwort darf nicht dasselbe wie das alte Passwort sein.', + }; + } + + return null; + }); + }, + { + submission: { + action: async (field) => { + const oldPassword = field.oldPassword().value().trim(); + const newPassword = field.newPassword().value().trim(); + + if (!oldPassword || !newPassword) { + return; + } + try { + await this._credentialService.changePassword( + oldPassword, + newPassword, + ); + } catch (error) { + console.error('Error changing password:', error); + this._snackBar.open( + 'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.', + 'OK', + { duration: 7000 }, + ); + } + }, + }, + }, + ); + + inputFieldType = computed(() => + this.changePasswordModel().showPasswords ? 'text' : 'password', + ); + constructor() { effect(() => { this.roles = [this.accountProfile().role]; diff --git a/webapp/src/app/modules/accounts/account-dialog.component.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts index a10cff43..87fb87f2 100644 --- a/webapp/src/app/modules/accounts/account-dialog.component.ts +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -16,22 +16,38 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; -import type { - AccountPayload, +import { AccountProfile, - AccountRole, - CreateAccountPayload, - OrganizationProfile, -} from '../../shared/services/account-management.service'; + InseAccountManagementModelOrganizationProfile, + UserRole, +} from '../../api'; export type AccountDialogMode = 'create' | 'edit'; export interface AccountDialogData { mode: AccountDialogMode; account?: AccountProfile; - organizations: OrganizationProfile[]; + organizations: InseAccountManagementModelOrganizationProfile[]; canSelectOrganization: boolean; - roles: AccountRole[]; + roles: UserRole[]; +} + +export interface AccountPayload { + email?: string; + name?: string; + role?: UserRole; + organization_id?: string; + password?: string; + deleted?: boolean; + activated?: boolean; +} + +export interface CreateAccountPayload { + email: string; + name: string; + role: UserRole; + organization_id: string; + password: string; } export type AccountDialogResult = @@ -69,7 +85,7 @@ export class AccountDialogComponent { name: new FormControl(this.data.account?.name ?? '', [ Validators.required, ]), - role: new FormControl(this.data.account?.role ?? 'USER', [ + role: new FormControl(this.data.account?.role ?? 'USER', [ Validators.required, ]), organizationId: new FormControl( @@ -148,6 +164,6 @@ export class AccountDialogComponent { } protected close(): void { - this.dialogRef.close(undefined); + this.dialogRef.close(); } } diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index 6a5fdb83..7e1f45e0 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -2,145 +2,94 @@ -
- - Name oder E-Mail - - - - @if (credentialService.isEffectiveSuperAdmin()) { - - Organisation - - Alle Organisationen - @for (organization of organizations; track organization.id) { - - {{ organization.name }} - - } - - - } - -
- - -
-
- -
-
- {{ total }} Accounts - @if (isLoading) { - Wird geladen... - } -
- -
- - - - - - - - - - - - - @for (account of accounts; track account.id) { - - - - - - - - - } @empty { - - - - } - -
NameE-MailOrganisationRolleStatusAktionen
- - {{ account.email }}{{ account.organization_name }} - {{ account.role | role }} - - - {{ account.deleted ? 'deleted' : 'active' }} - - -
- - - -
-
Keine Accounts gefunden.
-
- - +
+ +
+ + + + + +
+ + + {{ row.role | role }} + + + + + {{ + (row.deleted ? 'deleted' : row.activated ? 'active' : 'inactive') | status + }} + + + + +
+ + + + +
+
diff --git a/webapp/src/app/modules/accounts/accounts.component.scss b/webapp/src/app/modules/accounts/accounts.component.scss index 53149e49..dc24d512 100644 --- a/webapp/src/app/modules/accounts/accounts.component.scss +++ b/webapp/src/app/modules/accounts/accounts.component.scss @@ -88,6 +88,11 @@ tr.deleted { color: #94a3b8; } +tr.deactivated:not(.deleted) { + color: #64748b; + background: #f8fafc; +} + .link-button { border: 0; background: transparent; @@ -120,6 +125,11 @@ tr.deleted { color: #991b1b; } +.status--deactivated { + background: #fef3c7; + color: #92400e; +} + .row-actions { gap: 4px; } @@ -145,3 +155,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index f02fa6da..127d259c 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -1,27 +1,49 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit, inject } from '@angular/core'; -import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { + Component, + OnInit, + TemplateRef, + computed, + inject, + input, + viewChild, +} from '@angular/core'; +import { ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { Router } from '@angular/router'; -import { finalize } from 'rxjs'; -import { AccountManagementService } from '../../shared/services/account-management.service'; -import type { - AccountProfile, - AccountRole, - OrganizationProfile, -} from '../../shared/services/account-management.service'; + import { CredentialService } from '../../shared/services/credential.service'; import type { AccountDialogComponent, AccountDialogResult, } from './account-dialog.component'; import { RolePipe } from '../../shared/pipes/role.pipe'; +import { + GenericColumn, + DataTableComponent, +} from '../../shared/ui/data-table/data-table.component'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; +import { MatCardModule } from '@angular/material/card'; +import { + AccountPage, + AccountProfile, + AuthService, + InseAccountManagementModelOrganizationProfile, + UserRole, +} from '../../api'; +import { StatusPipe } from '../../shared/pipes/status.pipe'; @Component({ selector: 'app-accounts', @@ -34,84 +56,95 @@ import { RolePipe } from '../../shared/pipes/role.pipe'; MatInputModule, MatSelectModule, MatSnackBarModule, + MatTooltipModule, MatDialogModule, RolePipe, + DataTableComponent, + QueryParamPaginatorComponent, + QueryParamInputComponent, + QueryParamSelectorComponent, + MatCardModule, + StatusPipe, ], templateUrl: './accounts.component.html', styleUrl: './accounts.component.scss', standalone: true, }) export class AccountsComponent implements OnInit { - private readonly accountService = inject(AccountManagementService); protected readonly credentialService = inject(CredentialService); private readonly snackBar = inject(MatSnackBar); private readonly router = inject(Router); private readonly dialog = inject(MatDialog); + private readonly authService = inject(AuthService); - protected get availableRoles(): AccountRole[] { + protected get isReadOnly(): boolean { + return this.credentialService.isEffectiveManager(); + } + + accountColumns: GenericColumn[] = []; + accountRoleTmp = viewChild.required>('accountRoleTmp'); + accountStatusTmp = viewChild.required>('accountStatusTmp'); + accountActionsTmp = viewChild.required>('accountActionsTmp'); + + availableRoles = computed(() => { if (this.credentialService.isEffectiveSuperAdmin()) { return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER']; } return ['MANAGER', 'USER']; - } - protected accounts: AccountProfile[] = []; - protected organizations: OrganizationProfile[] = []; - protected total = 0; - protected page = 0; - protected readonly pageSize = 10; - protected isLoading = false; - - protected filterForm = new FormGroup({ - search: new FormControl(''), - organizationId: new FormControl(''), }); + selectorOptions = computed(() => { + return this.organizations().map((org) => ({ + value: org.id, + display_name: org.name, + })); + }); + + accountPage = input.required(); + organizations = + input.required(); + ngOnInit(): void { - this.loadOrganizations(); - this.loadAccounts(); - } - - protected loadAccounts(page = this.page): void { - this.page = page; - this.isLoading = true; - this.accountService - .listAccounts({ - page: this.page, - pageSize: this.pageSize, - search: this.filterForm.controls.search.value?.trim() || undefined, - organizationId: - this.filterForm.controls.organizationId.value || undefined, - }) - .pipe(finalize(() => (this.isLoading = false))) - .subscribe({ - next: (result) => { - this.accounts = result.items; - this.total = result.total; - }, - error: () => { - this.snackBar.open('Accounts konnten nicht geladen werden.', 'OK', { - duration: 5000, - }); - }, - }); - } - - protected loadOrganizations(): void { - this.accountService.listOrganizations().subscribe({ - next: (organizations) => { - this.organizations = organizations; + this.accountColumns = [ + { + id: 'name', + header: 'Name', + type: 'accessor', + accessorKey: 'name', }, - }); - } - - protected applyFilters(): void { - this.loadAccounts(0); - } - - protected resetFilters(): void { - this.filterForm.reset({ search: '', organizationId: '' }); - this.loadAccounts(0); + { + id: 'email', + header: 'E-Mail', + type: 'accessor', + accessorKey: 'email', + }, + { + id: 'organization_name', + header: 'Organisation', + type: 'accessor', + accessorKey: 'organization_name', + }, + { + id: 'role', + header: 'Rolle', + type: 'accessor', + accessorKey: 'role', + cellTemplate: this.accountRoleTmp(), + }, + { + id: 'status', + header: 'Status', + type: 'display', + cellTemplate: this.accountStatusTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.accountActionsTmp(), + }, + ]; } protected startCreate(): void { @@ -125,15 +158,18 @@ export class AccountsComponent implements OnInit { private saveDialogResult(result: AccountDialogResult): void { const request = result.mode === 'create' - ? this.accountService.createAccount(result.payload) - : this.accountService.updateAccount(result.accountId, result.payload); + ? this.authService.createAccount(result.payload) + : this.authService.updateAccount(result.accountId, result.payload); request.subscribe({ next: () => { this.snackBar.open('Account wurde gespeichert.', 'OK', { duration: 3000, }); - this.loadAccounts(0); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, error: (error) => { const message = @@ -155,9 +191,9 @@ export class AccountsComponent implements OnInit { { mode: 'create' | 'edit'; account?: AccountProfile; - organizations: OrganizationProfile[]; + organizations: InseAccountManagementModelOrganizationProfile[]; canSelectOrganization: boolean; - roles: AccountRole[]; + roles: UserRole[]; }, AccountDialogResult | undefined >(AccountDialogComponent, { @@ -165,9 +201,9 @@ export class AccountsComponent implements OnInit { maxWidth: 'calc(100vw - 32px)', data: { ...data, - organizations: this.organizations, + organizations: this.organizations(), canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(), - roles: this.availableRoles, + roles: this.availableRoles(), }, }); @@ -184,12 +220,15 @@ export class AccountsComponent implements OnInit { return; } - this.accountService.deleteAccount(account.id).subscribe({ + this.authService.deleteAccount(account.id).subscribe({ next: () => { this.snackBar.open('Account wurde deaktiviert.', 'OK', { duration: 3000, }); - this.loadAccounts(); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, error: () => { this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', { @@ -199,40 +238,84 @@ export class AccountsComponent implements OnInit { }); } - protected impersonate(account: AccountProfile): void { - if (!this.canImpersonate(account)) { + protected toggleAccountActivation(account: AccountProfile): void { + if ( + !this.credentialService.isEffectiveSuperAdmin() || + account.is_current || + account.deleted + ) { return; } - this.credentialService.impersonateAccount(account.id).subscribe({ + const activated = !account.activated; + const action = activated ? 'aktivieren' : 'deaktivieren'; + + import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( + ({ ConfirmationDialogComponent }) => { + const dialogRef = this.dialog.open(ConfirmationDialogComponent, { + data: { + title: activated ? 'Account aktivieren' : 'Account deaktivieren', + message: `Möchtest Du den Account „${account.name}“ wirklich ${action}?`, + confirmText: activated ? 'Aktivieren' : 'Deaktivieren', + cancelText: 'Abbrechen', + }, + }); + + dialogRef.componentInstance.confirmDelete.subscribe(() => { + this.updateAccountActivation(account, activated); + }); + }, + ); + } + + private updateAccountActivation( + account: AccountProfile, + activated: boolean, + ): void { + this.authService.updateAccount(account.id, { activated }).subscribe({ next: () => { - this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { - duration: 4000, + this.snackBar.open( + activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.', + 'OK', + { duration: 3000 }, + ); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', }); - this.router.navigate(['/dashboard']); }, error: () => { this.snackBar.open( - 'Impersonation konnte nicht gestartet werden.', + 'Account-Status konnte nicht geändert werden.', 'OK', - { - duration: 5000, - }, + { duration: 5000 }, ); }, }); } - protected get canPageBack(): boolean { - return this.page > 0; - } + protected async impersonate(account: AccountProfile): Promise { + if (!this.canImpersonate(account)) { + return; + } - protected get canPageForward(): boolean { - return (this.page + 1) * this.pageSize < this.total; + try { + await this.credentialService.impersonateAccount(account.id); + this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', { + duration: 4000, + }); + this.router.navigate(['/dashboard']); + } catch (error) { + console.error('Impersonation failed:', error); + this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', { + duration: 5000, + }); + return; + } } protected canImpersonate(account: AccountProfile): boolean { - if (account.is_current || account.deleted) { + if (account.is_current || account.deleted || !account.activated) { return false; } diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 7d3b0cf7..a8bd7fea 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -1,4 +1,4 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component, effect, OnDestroy } from '@angular/core'; import { FormControl, FormGroup, @@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input'; import { CredentialService } from '../../shared/services/credential.service'; import { MatIconModule } from '@angular/material/icon'; import { CommonModule } from '@angular/common'; -import { finalize, Subscription } from 'rxjs'; +import { Subscription } from 'rxjs'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { Router, RouterLink } from '@angular/router'; import { HttpErrorResponse } from '@angular/common/http'; @@ -34,7 +34,7 @@ type LoginStep = 'credentials' | 'otk'; styleUrl: './app-login.component.scss', standalone: true, }) -export class AppLoginComponent implements OnInit, OnDestroy { +export class AppLoginComponent implements OnDestroy { credentialsForm = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ @@ -64,28 +64,21 @@ export class AppLoginComponent implements OnInit, OnDestroy { protected credentialService: CredentialService, protected router: Router, protected snackBar: MatSnackBar, - ) {} - - ngOnInit(): void { - this.subscription = this.credentialService.validating.subscribe( - (validating) => { - if (validating) { - this.credentialsForm.disable(); - this.otkForm.disable(); - } else { - this.credentialsForm.enable(); - this.otkForm.enable(); - this.checkEnter(); - } - }, - ); - if (!this.credentialService.validating.value) { - this.checkEnter(); - } + ) { + effect(() => { + if (this.credentialService.isValidating()) { + this.credentialsForm.disable(); + this.otkForm.disable(); + } else { + this.credentialsForm.enable(); + this.otkForm.enable(); + this.checkEnter(); + } + }); } checkEnter(): void { - if (this.credentialService.isAuthenticated.value) { + if (this.credentialService.isAuthenticated()) { this.router.navigate(['/dashboard']); } } @@ -110,39 +103,35 @@ export class AppLoginComponent implements OnInit, OnDestroy { const email = this.credentialsForm.controls.email.value ?? ''; const password = this.credentialsForm.controls.password.value ?? ''; - this.credentialService - .requestOtk(email, password) - .pipe( - finalize(() => { - this.isSubmitting = false; - this.credentialsForm.enable(); - }), - ) - .subscribe({ - next: (accountId) => { - if (!accountId) { - return; - } - - this.accountId = accountId; - this.currentStep = 'otk'; - this.otkForm.reset(); - this.startCountdown(); - this.snackBar.open( - 'OTK-Code wurde an die E-Mail-Adresse gesendet.', - 'OK', - { - duration: 4000, - }, - ); - }, - error: (error: HttpErrorResponse) => { - this.credentialService.clearLocalAuthState(); - this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { + this.credentialService.requestOtk(email, password).subscribe({ + next: (otkResponse) => { + const accountId = otkResponse.account_id; + this.accountId = accountId; + this.currentStep = 'otk'; + this.otkForm.reset(); + this.startCountdown(); + this.snackBar.open( + 'OTK-Code wurde an die E-Mail-Adresse gesendet.', + 'OK', + { + duration: 4000, + }, + ); + }, + error: (error: unknown) => { + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { duration: 5000, - }); - }, - }); + }, + ); + }, + complete: () => { + this.isSubmitting = false; + this.credentialsForm.enable(); + }, + }); } resendCode() { @@ -178,29 +167,32 @@ export class AppLoginComponent implements OnInit, OnDestroy { this.isSubmitting = true; this.otkForm.disable(); - const email = this.credentialsForm.controls.email.value ?? ''; const code = this.otkForm.controls.code.value ?? ''; - this.credentialService - .loginWithOtk(this.accountId, email, code) - .pipe( - finalize(() => { - this.isSubmitting = false; - this.otkForm.enable(); - }), - ) - .subscribe({ - next: () => { - this.stopCountdown(); - this.router.navigate(['/dashboard']); - }, - error: (error: HttpErrorResponse) => { - this.credentialService.clearLocalAuthState(); - this.snackBar.open(this.getLoginErrorMessage(error), 'OK', { + this.credentialService.loginWithOtk(this.accountId, code).subscribe({ + next: () => { + this.credentialService.reauthenticateViaIdToken().subscribe({ + next: () => { + this.checkEnter(); + this.stopCountdown(); + this.router.navigate(['/dashboard']); + }, + }); + }, + error: (error: unknown) => { + this.snackBar.open( + this.getLoginErrorMessage(error as HttpErrorResponse), + 'OK', + { duration: 5000, - }); - }, - }); + }, + ); + }, + complete: () => { + this.isSubmitting = false; + this.otkForm.enable(); + }, + }); } editCredentials() { @@ -240,12 +232,13 @@ export class AppLoginComponent implements OnInit, OnDestroy { } private getLoginErrorMessage(error: HttpErrorResponse): string { + console.error('Login error:', error); if (error.status === 401) { return 'E-Mail, Passwort oder OTK-Code ist ungültig.'; } if (error.status === 403) { - return 'Dieses Konto ist nicht für die Anmeldung freigeschaltet.'; + return 'Dieser Account ist deaktiviert und kann sich nicht anmelden.'; } return 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.'; diff --git a/webapp/src/app/modules/app-register/app-register.component.html b/webapp/src/app/modules/app-register/app-register.component.html index e6349bc5..a9e758c6 100644 --- a/webapp/src/app/modules/app-register/app-register.component.html +++ b/webapp/src/app/modules/app-register/app-register.component.html @@ -84,9 +84,7 @@ mat-raised-button class="button" (click)="submit()" - [disabled]=" - !registerForm.valid || (credentialService.validating | async) - "> + [disabled]="!registerForm.valid || credentialService.isValidating()"> Registrieren diff --git a/webapp/src/app/modules/app-register/app-register.component.ts b/webapp/src/app/modules/app-register/app-register.component.ts index d4169732..a2341a1a 100644 --- a/webapp/src/app/modules/app-register/app-register.component.ts +++ b/webapp/src/app/modules/app-register/app-register.component.ts @@ -4,7 +4,7 @@ import { OnDestroy, signal, DestroyRef, - OnInit, + effect, } from '@angular/core'; import { CommonModule } from '@angular/common'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @@ -54,7 +54,7 @@ import { InstitutionsService } from '../../api'; templateUrl: './app-register.component.html', styleUrl: './app-register.component.scss', }) -export class AppRegisterComponent implements OnDestroy, OnInit { +export class AppRegisterComponent implements OnDestroy { private readonly fb = inject(FormBuilder); protected readonly credentialService = inject(CredentialService); private readonly router = inject(Router); @@ -73,42 +73,37 @@ export class AppRegisterComponent implements OnDestroy, OnInit { showPassword = false; constructor() { + effect(() => { + if (this.credentialService.isValidating()) { + this.registerForm.disable(); + } else { + this.registerForm.enable(); + this.checkEnter(); + } + }); + this.setupInstitutionAutocomplete(); } - ngOnInit(): void { - this.subscription = this.credentialService.validating.subscribe( - (validating) => { - if (validating) { - this.registerForm.disable(); - } else { - this.registerForm.enable(); - this.checkEnter(); - } - }, - ); - if (!this.credentialService.validating) { - this.checkEnter(); - } - } + ngOnDestroy(): void { this.subscription?.unsubscribe(); } checkEnter(): void { - if (this.credentialService.isAuthenticated.value) { + if (this.credentialService.isAuthenticated()) { this.router.navigate(['/dashboard']); } } submit() { if (this.registerForm.valid) { - this.credentialService.validating.next(true); + this.credentialService.isValidating.set(true); this.registerForm.disable(); this.subscription = this.credentialService .registerAccount(this.registerForm.value) .subscribe({ next: () => { - this.credentialService.validating.next(false); + this.credentialService.isValidating.set(false); this.snackBar.open( 'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.', 'OK', @@ -117,7 +112,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit { this.router.navigate(['/login']); }, error: (err) => { - this.credentialService.validating.next(false); + this.credentialService.isValidating.set(false); this.registerForm.enable(); const message = err.error?.message || diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html new file mode 100644 index 00000000..a68cbaea --- /dev/null +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -0,0 +1,252 @@ +@if (loading) { +

Lade Patente...

+} @else if (error) { +

Fehler beim Laden der Patente.

+} @else if (patents.length === 0) { +

+ Keine Patente in org_patents für diese Institution gefunden. +

+

+ Der Index muss zuerst befüllt werden: + python service/scripts/index_org_patents.py --institution-id + {{ institutionId }} +

+} @else { +
+
+
+
+ + + +
+ + + + + + + + + + + + + + + @for ( + patent of getPagedPatents(); + track trackPatent($index, patent) + ) { + + + + + + + + + + } + +
PatentQuelleJahrErfinderApplicant/AssigneeMatch-TypPersonen
+ {{ patent.title ?? patent.patent_id }} + + + {{ patent.source }} + + {{ patent.publication_year ?? '-' }}{{ getInventorsPreview(patent) }}{{ getAssigneesPreview(patent) }} + + {{ getMatchTypeLabel(patent) }} + + + @if ( + patent.matched_authors && patent.matched_authors.length + ) { + @for ( + author of patent.matched_authors.slice(0, 2); + track author.openalex_author_id + ) { + + {{ author.author_name }} + + } + } @else { + - + } +
+ + @if (hasPagination()) { + + } +
+ + @if (selectedPatent) { +
+

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

+
+
+ Quelle + + + {{ selectedPatent.source }} + + +
+
+ Patent-Nr. + {{ selectedPatent.patent_id }} +
+
+ Datum + @if (selectedPatent.publication_date) { + {{ + formatDate(selectedPatent.publication_date) + }} + } +
+
+ Match-Typ + {{ + getMatchTypeLabel(selectedPatent) + }} +
+ @if (getPublicationStageLabel(selectedPatent); as stageLabel) { +
+ Publikationsstufe + {{ stageLabel }} +
+ } +
+ + @if (selectedPatent.matched_authors?.length) { +
+

Verknüpfte Personen

+ +
+ } + + @if ( + getAbstractPreview(selectedPatent.abstract); + as abstractPreview + ) { +

{{ abstractPreview }}

+ } + + +

+ Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation +

+
+ } @else { +
+

Patentübersicht

+

+ @if (institutionName) { + Alle Patente von {{ institutionName }} im Überblick. + } @else { + Alle Patente dieser Institution im Überblick. + } +

+
+
+ {{ totalPatents }} + Patente +
+
+ {{ + getInstitutionMatchCount() + }} + Institution +
+
+ {{ getNameMatchCount() }} + Name +
+
+ {{ getBothMatchCount() }} + Beides +
+
+

+ Wähle links ein Patent aus, um Kurzinfos und Details zu sehen. +

+
+ } +
+
+} diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.scss b/webapp/src/app/modules/institution-patents/institution-patents.component.scss new file mode 100644 index 00000000..b5f3fa12 --- /dev/null +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.scss @@ -0,0 +1,636 @@ +.message { + padding: 16px; + color: #666; + + &.message-hint { + padding-top: 0; + font-size: 13px; + color: #888; + + code { + display: inline-block; + margin-top: 6px; + padding: 4px 8px; + border-radius: 6px; + background: #f5f5f5; + color: #333; + font-size: 12px; + } + } +} + +.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: 280px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .cell-preview { + max-width: 160px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: #555; + font-size: 13px; + } + + .cell-authors { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 120px; + } + } +} + +.match-badge { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 999px; + font-size: 0.72rem; + font-weight: 700; + + &--institution { + background: #f5f3ff; + color: #6d28d9; + border: 1px solid #ddd6fe; + } + + &--name { + background: #fff7ed; + color: #c2410c; + border: 1px solid #fed7aa; + } + + &--both { + background: #ecfdf5; + color: #047857; + border: 1px solid #a7f3d0; + } +} + +.author-link { + color: #2563eb; + text-decoration: none; + font-size: 0.82rem; + + &:hover { + text-decoration: underline; + } +} + +.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; + 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; + } +} diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts new file mode 100644 index 00000000..3b90b1b5 --- /dev/null +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -0,0 +1,288 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { PatentsService } from '../../api/api/patents.service'; +import { OrgPatentEntry } from '../../api/model/orgPatentEntry'; +import { + formatPatentDate, + getPublicationStageLabel, +} from '../patent-detail/patent-detail.utils'; + +type SortMode = 'date' | 'title'; +type SourceFilter = 'all' | 'EPO' | 'USPTO'; +type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; + +@Component({ + selector: 'app-institution-patents', + imports: [CommonModule, RouterLink], + templateUrl: './institution-patents.component.html', + styleUrl: './institution-patents.component.scss', +}) +export class InstitutionPatentsComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private patentsApi = inject(PatentsService); + + patents: OrgPatentEntry[] = []; + filteredPatents: OrgPatentEntry[] = []; + institutionName: string | null = null; + institutionId: string | null = null; + selectedPatent: OrgPatentEntry | null = null; + + loading = true; + error = false; + + activeFilter: SourceFilter = 'all'; + activeMatchType: OrgPatentMatchTypeFilter = 'all'; + sortMode: SortMode = 'date'; + + selectedPage = 1; + readonly pageSize = 20; + totalPatents = 0; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe((params) => { + const institutionId = params.get('institutionId') ?? ''; + + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + const matchTypeFromUrl = + this.route.snapshot.queryParamMap.get('matchType'); + + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } + if (this.isValidMatchType(matchTypeFromUrl)) { + this.activeMatchType = matchTypeFromUrl; + } + + if (institutionId) { + this.institutionId = institutionId; + this.loadPatents(institutionId); + } + }); + } + + setFilter(filter: SourceFilter): void { + this.activeFilter = filter; + this.selectedPage = 1; + this.selectedPatent = null; + this.reloadPatents(); + } + + setMatchType(matchType: OrgPatentMatchTypeFilter): void { + if (this.activeMatchType === matchType) return; + this.activeMatchType = matchType; + this.selectedPage = 1; + this.selectedPatent = null; + this.reloadPatents(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode = sortMode; + this.filteredPatents = this.sortPatents(this.patents); + this.updateQueryParams(); + } + + selectPatent(patent: OrgPatentEntry): void { + this.selectedPatent = patent; + this.updateQueryParams(); + } + + openDetail(): void { + if (!this.selectedPatent) return; + this.router.navigate(['/patent', this.selectedPatent.patent_id]); + } + + setPage(page: number): void { + this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); + this.selectedPatent = null; + this.reloadPatents(); + } + + getPagedPatents(): OrgPatentEntry[] { + return this.filteredPatents; + } + + getPageCount(): number { + return Math.max(1, Math.ceil(this.totalPatents / this.pageSize)); + } + + hasPagination(): boolean { + return this.totalPatents > this.pageSize; + } + + private reloadPatents(): void { + const institutionId = + this.institutionId ?? + this.route.parent?.snapshot.paramMap.get('institutionId') ?? + ''; + if (institutionId) { + this.loadPatents(institutionId); + } + } + + private loadPatents(institutionId: string): void { + this.loading = true; + this.error = false; + + this.patentsApi + .getOrgPatentsByInstitution( + institutionId, + this.activeMatchType, + this.selectedPage - 1, + this.pageSize, + this.activeFilter !== 'all' ? this.activeFilter : undefined, + ) + .subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.totalPatents = result.patent_count ?? 0; + this.institutionName = result.institution_name ?? null; + this.filteredPatents = this.sortPatents(this.patents); + this.loading = false; + this.updateQueryParams(); + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + + private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] { + if (this.sortMode === 'title') { + return [...patents].sort((a, b) => + (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }), + ); + } + return [...patents]; + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + sortBy: this.sortMode, + matchType: this.activeMatchType, + page: this.selectedPage, + }, + 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'; + } + + private isValidMatchType( + value: string | null, + ): value is OrgPatentMatchTypeFilter { + return ( + value === 'all' || + value === 'institution' || + value === 'name' || + value === 'both' + ); + } + + formatDate(date: string | null): string { + return formatPatentDate(date); + } + + getEpoCount(): number { + return this.patents.filter((p) => p.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.patents.filter((p) => p.source === 'USPTO').length; + } + + getInstitutionMatchCount(): number { + return this.patents.filter( + (p) => p.match_type === 'institution' || p.match_type === 'both', + ).length; + } + + getNameMatchCount(): number { + return this.patents.filter( + (p) => p.match_type === 'name' || p.match_type === 'both', + ).length; + } + + getBothMatchCount(): number { + return this.patents.filter((p) => p.match_type === 'both').length; + } + + trackPatent(_index: number, patent: OrgPatentEntry): 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: OrgPatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + getMatchTypeLabel(patent: OrgPatentEntry): string { + switch (patent.match_type) { + case 'institution': + return 'Institution'; + case 'name': + return 'Name'; + case 'both': + return 'Beides'; + default: + return patent.match_type; + } + } + + getInventorsPreview(patent: OrgPatentEntry): string { + if (!patent.inventors?.length) { + return '-'; + } + return patent.inventors.slice(0, 2).join(', '); + } + + getAssigneesPreview(patent: OrgPatentEntry): string { + if (!patent.assignees?.length) { + return '-'; + } + return patent.assignees.slice(0, 2).join(', '); + } + + getMatchedAuthorsPreview(patent: OrgPatentEntry): string { + if (!patent.matched_authors?.length) { + return '-'; + } + return patent.matched_authors + .slice(0, 2) + .map((author) => author.author_name) + .join(', '); + } +} diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts index 03ffd347..61d0d938 100644 --- a/webapp/src/app/modules/institution/institution.component.ts +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -40,6 +40,7 @@ export class InstitutionComponent implements OnInit { sort_direction: 'asc', }, }, + { label: 'Patente', path: 'patents', disabled: false }, ]; constructor(private readonly activatedRoute: ActivatedRoute) {} diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index ce12b7ed..5edb4c3c 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -12,11 +12,13 @@
+ [queryParamKey]="'sort_by'" + label="Sortieren nach" /> + [queryParamKey]="'sorting_order'" + label="Sortierreihenfolge" />
@@ -78,6 +80,13 @@ work Projekte + + verified + Patente + diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index 7303fdd7..8edbecef 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -25,7 +25,7 @@ .cards { display: grid; gap: 1.5rem; - grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(550px, 1fr)); padding: 0 1rem; } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html new file mode 100644 index 00000000..8eb10128 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -0,0 +1,233 @@ +
+ +
+ + +
+ + Füge eine URL ein, um Keywords zu extrahieren + + + +
+
+ + +
+ + Schreibe einen Text, um Keywords zu extrahieren + + +
+ +
+
+
+
+ + +
+ + + +
+ +
+
Breite Keywords
+
Coarse Keywords
+
Fine Keywords
+
Eigene Keywords
+
+ + +
+
+ @if (broadKeywords().length > 0) { + + @for (keyword of broadKeywords(); track keyword) { + + {{ keyword }} + + } + + } @else { +

–

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

–

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

–

+ } +
+ +
+ + + @if (manualKeywords().length > 0) { + @for (keyword of manualKeywords(); track keyword) { + + {{ keyword }} + cancel + + } + } + +
+
+
+ + + @if (extractedKeywordsExist()) { +
+ @if (areAllExtractedSelected()) { + + } @else { + + } + +
+ } + + @if (isExtracting()) { +
+ + +
{{ statusMessage() }}
+
+ } @else if ( + !extractedKeywordsExist() && manualKeywords().length === 0 + ) { +

+ Keine Keywords vorhanden. Extrahiere Keywords oder füge eigene + hinzu. +

+ } + + @if (sourceContent().length > 0) { + + + + Quellentext: {{ sourceUrl() }} + +
{{ sourceContent() }}
+
+ } +
+
+
+ + +
+ +
+
+
diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss new file mode 100644 index 00000000..3162536f --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -0,0 +1,459 @@ +.content { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 1rem; +} + +.tab-content { + padding: 0.5rem 0; + display: grid; + grid-template-columns: 5fr 1fr; + gap: 0.5rem; +} + +.full-width { + width: 100%; +} + +.actions { + display: flex; + justify-content: center; +} + +.extraction-grid { + display: grid; + grid-template-columns: 1fr; + gap: 1rem; +} + +.keyword-card { + background-color: var(--sg-background); + padding: 0.5rem; + + .mat-card-header { + padding: 0 0 0.5rem 0; + } + + .mat-card-content { + padding: 0; + } +} + +/* === Table-like keyword grid === */ +.keyword-table { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin: 0.5rem 0; +} + +.table-head { + display: grid; + grid-template-columns: repeat(3, 1fr) 1.3fr; + grid-template-rows: auto; + column-gap: 1rem; + border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); + padding-bottom: 0.5rem; +} + +.head-cell { + min-width: 0; + text-align: center; /* Center header text */ +} + +.extracted-header { + grid-column: 1 / span 3; + grid-row: 0; + font-size: 0.95rem; + font-weight: 600; + color: var(--sg-text-primary); + align-self: end; +} + +.own-header { + grid-column: 4; + grid-row: 1 / span 2; + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.own-header-title { + font-size: 0.95rem; + font-weight: 600; + color: var(--sg-text-primary); + text-align: center; /* Center own header title */ +} + +.sub-cell { + font-weight: 500; + color: var(--sg-text-secondary); + font-size: 1rem; + text-transform: uppercase; + letter-spacing: 0.05em; + align-self: end; + grid-row: 2; + text-align: center; /* Center sub-cell text */ +} + +.broad-sub { + grid-column: 1; +} +.coarse-sub { + grid-column: 2; +} +.fine-sub { + grid-column: 3; +} +.manual-sub { + grid-column: 4; +} +.keyword-input-row { + margin-left: 0.5rem; + width: 100%; + display: grid; + grid-column: 1 / span 4; + display: flex; + align-items: center; + gap: 0.35rem; + + &.compact { + .small-field { + flex: 10; + // collapse the outline field to a compact, chip-like height + ::ng-deep .mat-mdc-text-field-wrapper { + padding: 0 0.6rem; + } + + ::ng-deep .mat-mdc-form-field-flex { + min-height: 8px; + align-items: center; + } + + ::ng-deep .mat-mdc-form-field-infix { + min-height: 8px; + padding: 1rem 0; + } + + // hide the hint/error subscript strip to remove extra height + ::ng-deep .mat-mdc-form-field-subscript-wrapper { + display: none; + } + + ::ng-deep input.mat-mdc-input-element { + font-size: 0.8rem; + } + + ::ng-deep .mat-mdc-form-field-label, + ::ng-deep mat-label { + font-size: 1rem; + } + } + + button.mat-mdc-icon-button { + width: 28px; + height: 28px; + padding: 0; + line-height: 28px; + flex: 1; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + + ::ng-deep .mat-mdc-button-touch-target { + width: 28px; + height: 28px; + } + } + } +} + +.table-body { + display: grid; + grid-template-columns: repeat(3, 1fr) 1.3fr; + column-gap: 1rem; + row-gap: 0.4rem; + align-items: start; + border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); /* Left border for columns */ +} + +/* Add vertical separators between columns */ +.table-col { + display: flex; + flex-direction: column; + min-width: 0; + padding: 0.5rem; + height: 100%; + border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + + &:last-child { + border-right: none; + } + &:nth-child(3) { + border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + } + + mat-chip-listbox { + width: 100%; + margin-top: 0.5rem; + } +} + +/* Make chips removable and add hover effect */ +.compact-chip { + font-size: 1rem; + padding: 0.2rem 0.6rem; + min-height: 28px; + line-height: 1.2; + width: 80%; + box-sizing: border-box; + animation: popIn 0.2s ease-in-out; + cursor: default; + + // Add removable indicator and hover effect + &.mat-mdc-chip-option { + .mat-mdc-chip-action { + padding: 0 4px; + + .mat-mdc-chip-action-label { + padding: 0 4px; + display: flex; + align-items: center; + gap: 4px; + } + } + + // Show remove button on hover for removable chips + &:hover { + ::ng-deep .mat-mdc-chip-remove { + opacity: 1; + } + } + } + + // Style for removable chips + ::ng-deep .mat-mdc-chip-remove { + opacity: 0; + transition: opacity 0.2s ease; + cursor: pointer; + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + } + } +} + +@keyframes popIn { + from { + opacity: 0; + transform: scale(0.9); + } + to { + opacity: 1; + transform: scale(1); + } +} + +::ng-deep .mat-mdc-chip-option.compact-chip { + .mat-mdc-chip-action-label { + padding: 0 4px; + } + .mat-mdc-chip-action { + padding: 0 4px; + } +} + +.empty-state { + text-align: center; + color: var(--sg-text-secondary); + margin: 0; + font-size: 0.85rem; + padding: 0.35rem 0; + + &.small { + opacity: 0.6; + } +} + +.select-all-container { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + justify-content: flex-end; + margin-top: 0.5rem; + + button { + font-size: 0.75rem; + padding: 0 12px; + line-height: 30px; + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } + } +} + +.search-container { + display: flex; + justify-content: flex-end; + margin-top: 0.5rem; +} + +/* Responsive: stack columns on small screens */ +@media (max-width: 768px) { + .table-head, + .table-body { + grid-template-columns: 1fr; + } + + .extracted-header { + grid-column: 1; + grid-row: 1; + } + + .own-header { + grid-column: 1; + grid-row: 2; + } + + .broad-sub { + grid-column: 1; + grid-row: 3; + } + .coarse-sub { + grid-column: 1; + grid-row: 4; + } + .fine-sub { + grid-column: 1; + grid-row: 5; + } + + .actions { + align-self: center; + justify-content: flex-start; + } + + .search-container { + justify-content: flex-start; + } + + .table-col { + border-right: none; /* Remove column borders on mobile */ + border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + + &:last-child { + border-bottom: none; + } + } +} +/* Source expansion panel */ +.source-expansion { + margin: 0.75rem 0; + background: var(--sg-background-muted, #f5f5f5); + border-radius: 4px; + border-left: 4px solid var(--sg-primary, #1976d2); + + .mat-expansion-panel-header { + padding: 0.5rem 0.75rem; + height: auto; + min-height: 36px; + font-size: 1rem; + text-transform: uppercase; + color: var(--sg-text-secondary); + letter-spacing: 0.05em; + + .mat-expansion-panel-header-title { + font-size: 0.8rem; + font-weight: 500; + color: inherit; + } + + .mat-expansion-indicator { + margin-left: 0.5rem; + } + } + + ::ng-deep .mat-expansion-panel-content { + font-size: 0.85rem; + line-height: 1.5; + color: var(--sg-text-primary); + } + + ::ng-deep .mat-expansion-panel-body { + padding: 0 0.75rem 0.75rem 0.75rem; + max-height: 350px; + overflow-y: auto; + white-space: pre-wrap; + word-break: break-word; + } + + ::ng-deep .mat-expansion-panel { + box-shadow: none !important; + background: transparent; + } + + ::ng-deep .mat-expansion-panel-header:hover { + background: rgba(0, 0, 0, 0.03); + } +} +.progress-container { + margin-top: 1rem; + padding: 0.5rem 0; + + // Make the progress bar container relative for the shimmer overlay + mat-progress-bar { + position: relative; + overflow: hidden; // keeps the shimmer inside the bar + + // --- Set the bar fill to a constant blue --- + // Using the primary blue (adjust to your preferred "hell blue") + ::ng-deep .mat-progress-bar-fill::after { + background-color: #2196f3; // bright blue + } + + // --- Shimmer overlay (a moving highlight) --- + &::after { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; // allow clicks to pass through + background: linear-gradient( + 105deg, + transparent 0%, + rgba(5, 65, 230, 0.4) 100%, + transparent 0% + ); + animation: shimmer 2s ease-in-out infinite; + } + } + + .status-message { + margin-top: 0.5rem; + font-size: 0.9rem; + color: var(--sg-text-secondary); + text-align: center; + font-weight: 500; + } +} + +@keyframes shimmer { + 0% { + transform: translateX(-100%); + } + 100% { + transform: translateX(100%); + } +} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts new file mode 100644 index 00000000..03a02061 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -0,0 +1,838 @@ +import { + Component, + computed, + signal, + Signal, + WritableSignal, +} from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatTabsModule } from '@angular/material/tabs'; +import { ActivatedRoute, Router } from '@angular/router'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; +import { KeywordsRequest } from '../../api/model/keywordsRequest'; +import { MatExpansionModule } from '@angular/material/expansion'; +import { ExtractedKeywords } from '../../api/model/extractedKeywords'; +import { ExtractedKeywordsResponse } from '../../api/model/extractedKeywordsResponse'; +import { DestroyRef } from '@angular/core'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { KeywordWebSocketService, WsEvent } from './keywords-websocket.service'; +import { TopicsService } from '../../api/api/topics.service'; +import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest'; +import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; +import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component'; + +type InputMode = 'url' | 'text'; +type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; + +@Component({ + selector: 'app-keywords-search', + imports: [ + ReactiveFormsModule, + MatTabsModule, + MatFormFieldModule, + MatInputModule, + MatButtonModule, + MatIconModule, + MatChipsModule, + MatDividerModule, + MatCardModule, + MatExpansionModule, + MatProgressBarModule, + TopicAutocompleteComponent, + ], + templateUrl: './keywords-search.component.html', + styleUrl: './keywords-search.component.scss', +}) +export class KeywordsSearchComponent { + readonly form = this.formBuilder.nonNullable.group({ + selectedInputType: 'url' as InputMode, + urlInput: '', + textInput: '', + }); + + private readonly SESSION_KEY = 'keywords-search-source'; + + // Category signals - the full backend entries are the source of truth; + // the *Keywords() computed signals below just project the label out of them. + private readonly broadKeywordEntries = signal([]); + private readonly coarseKeywordEntries = signal([]); + private readonly fineKeywordEntries = signal([]); + private readonly manualKeywordEntries = signal([]); + + readonly broadKeywords = computed(() => + this.broadKeywordEntries().map((item) => this.getKeywordLabel(item)), + ); + readonly coarseKeywords = computed(() => + this.coarseKeywordEntries().map((item) => this.getKeywordLabel(item)), + ); + readonly fineKeywords = computed(() => + this.fineKeywordEntries().map((item) => this.getKeywordLabel(item)), + ); + readonly manualKeywords = computed(() => + this.manualKeywordEntries().map((item) => this.getKeywordLabel(item)), + ); + + readonly selectedKeywords = signal([]); + readonly isExtracting = signal(false); + readonly extractionSource = signal(null); + + // Single place mapping a category name to its label signal and its + // backing entries signal. Replaces four near-identical computed()s and + // a category switch statement that used to live below. + private readonly categoryKeywordsMap: Record< + KeywordCategory, + Signal + > = { + broad: this.broadKeywords, + coarse: this.coarseKeywords, + fine: this.fineKeywords, + manual: this.manualKeywords, + }; + private readonly categoryEntriesMap: Record< + KeywordCategory, + WritableSignal + > = { + broad: this.broadKeywordEntries, + coarse: this.coarseKeywordEntries, + fine: this.fineKeywordEntries, + manual: this.manualKeywordEntries, + }; + + readonly selectedBroadKeywords = this.selectedInCategory('broad'); + readonly selectedCoarseKeywords = this.selectedInCategory('coarse'); + readonly selectedFineKeywords = this.selectedInCategory('fine'); + readonly selectedManualKeywords = this.selectedInCategory('manual'); + + readonly extractedKeywordsExist = computed( + () => + this.broadKeywords().length > 0 || + this.coarseKeywords().length > 0 || + this.fineKeywords().length > 0, + ); + + readonly sourceContent = signal(''); + readonly sourceUrl = signal(null); + + private isRestoringState = false; + + // Set right before we call router.navigate() ourselves (from + // updateQueryParams()). Lets the queryParamMap subscription below tell + // "we just wrote this URL" apart from "someone else navigated here" (a + // fresh mount, a deep link such as ?selected=x&manual=y from another + // page, a manual URL edit, browser back/forward). Only the latter should + // trigger a full restoreStateFromQueryParams(). + private isOwnNavigation = false; + + readonly progress = signal(0); + readonly statusMessage = signal(''); + + constructor( + private readonly formBuilder: FormBuilder, + private readonly route: ActivatedRoute, + private readonly router: Router, + private readonly destroyRef: DestroyRef, + private readonly websocketService: KeywordWebSocketService, + private readonly topicsService: TopicsService, + ) { + this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => { + if (this.isOwnNavigation) { + // This emission is just the router confirming the navigation we + // triggered ourselves in updateQueryParams(); our signals are + // already correct, so skip re-deriving state from the URL. + this.isOwnNavigation = false; + return; + } + this.restoreStateFromQueryParams(); + }); + + this.form.controls.selectedInputType.valueChanges + .pipe(distinctUntilChanged(), takeUntilDestroyed()) + .subscribe(() => this.updateQueryParams()); + + this.form.controls.urlInput.valueChanges + .pipe(debounceTime(400), distinctUntilChanged(), takeUntilDestroyed()) + .subscribe(() => this.updateQueryParams()); + + this.form.controls.textInput.valueChanges + .pipe(debounceTime(400), distinctUntilChanged(), takeUntilDestroyed()) + .subscribe(() => this.updateQueryParams()); + + this.websocketService + .getMessages() + .subscribe((event: WsEvent) => this.handleWsEvent(event)); + + // Clear session storage on component destroy, unless this is a page + // reload (in which case we want the cache to survive). + this.destroyRef.onDestroy(() => { + this.websocketService.close(); + const isReload = this.router.lastSuccessfulNavigation === null; + if (!isReload) { + this.clearSourceFromSession(); + } + }); + } + + // --- Websocket event handling --------------------------------------- + + private handleWsEvent(event: WsEvent): void { + switch (event.type) { + case 'status': + this.handleStatusEvent(event); + break; + case 'keywords': + if (event.keywords) this.addExtractedKeyword(event.keywords); + break; + case 'completed': + this.handleCompletedEvent(event); + break; + case 'error': + this.handleErrorEvent(event); + break; + } + } + + private handleStatusEvent(event: WsEvent): void { + this.statusMessage.set(event.message || ''); + this.progress.set(this.getProgressForStep(event.step || '')); + } + + private handleCompletedEvent(event: WsEvent): void { + this.processExtractedKeywords(event.result as ExtractedKeywordsResponse); + this.progress.set(100); + this.statusMessage.set('Fertig!'); + this.websocketService.close(); + this.isExtracting.set(false); + } + + private handleErrorEvent(event: WsEvent): void { + this.progress.set(0); + this.statusMessage.set('Fehler: ' + event.message); + this.broadKeywordEntries.set([]); + this.coarseKeywordEntries.set([]); + this.fineKeywordEntries.set([]); + this.websocketService.close(); + this.isExtracting.set(false); + // Keep manual, but remove selected that are not in manual + this.selectedKeywords.set( + this.selectedKeywords().filter((k) => this.manualKeywords().includes(k)), + ); + this.updateQueryParams(); + } + + // --- Topic enrichment -------------------------------------------------- + + enrichManualKeywordsWithTopics(keywords: string[]): void { + if (keywords.length === 0) return; + + const currentEntries = this.manualKeywordEntries(); + const entriesByKeyword = new Map( + currentEntries.map((e) => [ + this.normalizeKeyword(e.llm_keyword.keyword), + e, + ]), + ); + + const toEnrich = keywords.filter((k) => { + const entry = entriesByKeyword.get(this.normalizeKeyword(k)); + return entry && !entry.topic_mapping?.topic; + }); + if (toEnrich.length === 0) return; + + const request: KeywordsTopicsRequest = { keywords: toEnrich }; + + this.topicsService.vectorSearchTopicsBatch(request).subscribe({ + next: ({ results }) => { + const current = this.manualKeywordEntries(); + const resultMap = new Map( + results.map((r) => [this.normalizeKeyword(r.keyword), r]), + ); + + const updated = current.map((entry) => { + const normalized = this.normalizeKeyword(entry.llm_keyword.keyword); + const enriched = resultMap.get(normalized); + if (enriched && !entry.topic_mapping?.topic) { + return { + ...entry, + topic_mapping: { + keyword: entry.llm_keyword.keyword, + topic: enriched.topic, + }, + }; + } + return entry; + }); + + this.manualKeywordEntries.set(updated); + this.updateQueryParams(); + }, + error: (error) => { + console.error('Error enriching topics:', error); + }, + }); + } + + // --- Tabs --------------------------------------------------------------- + + selectedTabIndex(): number { + return this.form.controls.selectedInputType.value === 'text' ? 1 : 0; + } + + onTabChange(index: number): void { + const nextMode: InputMode = index === 1 ? 'text' : 'url'; + this.form.controls.selectedInputType.setValue(nextMode); + } + + // --- Keyword selection & manual entry ------------------------------------ + + private keywordExists(keyword: string): boolean { + const normalized = this.normalizeKeyword(keyword); + return [ + ...this.broadKeywords(), + ...this.coarseKeywords(), + ...this.fineKeywords(), + ...this.manualKeywords(), + ].some((k) => this.normalizeKeyword(k) === normalized); + } + + // Add manually from Keywords tab + addKeywordFromInput(keyword: string): void { + const normalizedKeyword = keyword.trim(); + if (!normalizedKeyword) return; + + if (this.keywordExists(normalizedKeyword)) { + this.statusMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`); + return; + } + + this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({ + next: ({ results }) => { + const newEntry: KeywordEntryWithTopic = { + llm_keyword: { + keyword: normalizedKeyword, + relevance_score: 1, + }, + topic_mapping: { + keyword: normalizedKeyword, + topic: results?.[0], + }, + }; + + const updated = this.uniqueKeywordEntries([ + ...this.manualKeywordEntries(), + newEntry, + ]); + + this.manualKeywordEntries.set(updated); + this.selectedKeywords.set([ + ...this.selectedKeywords(), + normalizedKeyword, + ]); + + // Explicit enrichment trigger for new keywords + this.enrichManualKeywordsWithTopics([normalizedKeyword]); + this.updateQueryParams(); + }, + }); + } + + removeSelectedKeyword(keyword: string): void { + this.selectedKeywords.set( + this.selectedKeywords().filter((v) => v !== keyword), + ); + this.updateQueryParams(); + } + + onCategoryChange( + category: KeywordCategory, + event: MatChipListboxChange, + ): void { + const newSelection = (event.value as string[]) || []; + const otherCategories = ( + Object.keys(this.categoryKeywordsMap) as KeywordCategory[] + ).filter((c) => c !== category); + const otherSelected = otherCategories.flatMap((c) => { + const keywords = this.categoryKeywordsMap[c](); + return this.selectedKeywords().filter((k) => keywords.includes(k)); + }); + const updated = [...otherSelected, ...newSelection]; + this.selectedKeywords.set(this.uniqueKeywords(updated)); + this.updateQueryParams(); + } + + selectAllExtracted(): void { + const all = [ + ...this.selectedManualKeywords(), + ...this.broadKeywords(), + ...this.coarseKeywords(), + ...this.fineKeywords(), + ]; + this.selectedKeywords.set(this.uniqueKeywords(all)); + this.updateQueryParams(); + } + + deselectAllExtracted(): void { + this.selectedKeywords.set( + this.uniqueKeywords(this.selectedManualKeywords()), + ); + this.updateQueryParams(); + } + + clearExtractedKeywords(): void { + this.broadKeywordEntries.set([]); + this.coarseKeywordEntries.set([]); + this.fineKeywordEntries.set([]); + this.sourceContent.set(''); + this.sourceUrl.set(null); + + // Keep only selected keywords that are in the manual list + const manualSet = new Set(this.manualKeywords()); + this.selectedKeywords.set( + this.selectedKeywords().filter((k) => manualSet.has(k)), + ); + + // Reset the extraction source (no extracted keywords left) + this.extractionSource.set(null); + + // updateQueryParams() persists this cleared state to sessionStorage too + // (see saveSourceToSession() call inside it), so there's no need to + // separately wipe the session key here. + this.updateQueryParams(); + } + + areAllExtractedSelected(): boolean { + const allExtracted = [ + ...this.broadKeywords(), + ...this.coarseKeywords(), + ...this.fineKeywords(), + ]; + return allExtracted.every((k) => this.selectedKeywords().includes(k)); + } + + isSearchDisabled(): boolean { + return this.selectedKeywords().length === 0 || this.isExtracting(); + } + + onExtractKeywordsClick(): void { + if (this.isExtracting()) { + this.cancelKeywordExtraction(); + return; + } + void this.extractKeywords(); + } + + addExtractedKeyword(keywords: ExtractedKeywords): void { + this.applyExtractedKeywords(keywords); + } + + onKeywordRemoved(category: KeywordCategory, keyword: string): void { + const entries = this.categoryEntriesMap[category]; + entries.set(this.filterKeywordEntries(entries(), keyword)); + + this.selectedKeywords.set( + this.selectedKeywords().filter((k) => k !== keyword), + ); + this.updateQueryParams(); + } + + processExtractedKeywords(result: ExtractedKeywordsResponse): void { + if (result === undefined || !result.results) return; + + const { results, source, source_content, source_url } = result; + + this.applyExtractedKeywords(results); + this.sourceContent.set(source_content); + this.extractionSource.set(source as InputMode); + this.sourceUrl.set(source_url ?? ''); + + // Keep only selected keywords that still exist in any category (including manual) + const allExtracted = [ + ...this.broadKeywords(), + ...this.coarseKeywords(), + ...this.fineKeywords(), + ...this.manualKeywords(), + ]; + this.selectedKeywords.set( + this.selectedKeywords().filter((k) => allExtracted.includes(k)), + ); + + // updateQueryParams() also calls saveSourceToSession() - no need to call + // it separately here. + this.updateQueryParams(); + } + + async extractKeywords(): Promise { + this.clearExtractedKeywords(); + const query = this.getCurrentExtractionQuery(); + if (!query) return; + + this.progress.set(0); + this.statusMessage.set('Starte Extraktion...'); + + const currentMode = this.form.controls.selectedInputType.value; + const keywordsRequest: KeywordsRequest = { + query, + mode: currentMode, + limit: undefined, + }; + + this.isExtracting.set(true); + + try { + // sendRequest now waits internally for the connection to open + await this.websocketService.sendRequest(keywordsRequest); + } catch (error) { + console.error('WebSocket send error:', error); + this.isExtracting.set(false); + this.statusMessage.set('Fehler beim Senden der Anfrage'); + } + } + + cancelKeywordExtraction(): void { + this.websocketService.close(); + this.isExtracting.set(false); + this.progress.set(0); + this.statusMessage.set('Extraktion abgebrochen'); + } + + search(): void { + const payload = { + extractedKeywords: this.getSelectedExtractedKeywordEntries(), + manualKeywords: this.getSelectedManualKeywordEntries(), + keywords: this.selectedKeywords(), + }; + + console.log('searching for keywords:', payload); + // e.g. navigate to search results page with the full payload in navigation state + // this.router.navigate(['/search'], { state: payload }); + } + + // --- Helpers -------------------------------------------------------------- + + private selectedInCategory(category: KeywordCategory): Signal { + return computed(() => + this.selectedKeywords().filter((k) => + this.categoryKeywordsMap[category]().includes(k), + ), + ); + } + + private applyExtractedKeywords(keywords: ExtractedKeywords): void { + const seenKeywords = new Set( + this.manualKeywords().map((keyword) => this.normalizeKeyword(keyword)), + ); + this.broadKeywordEntries.set( + this.uniqueKeywordEntries(keywords.broad_keywords, seenKeywords), + ); + this.coarseKeywordEntries.set( + this.uniqueKeywordEntries(keywords.coarse_grained, seenKeywords), + ); + this.fineKeywordEntries.set( + this.uniqueKeywordEntries(keywords.fine_grained, seenKeywords), + ); + } + + private getSelectedExtractedKeywordEntries(): KeywordEntryWithTopic[] { + const selected = new Set( + this.selectedKeywords().map((k) => this.normalizeKeyword(k)), + ); + return [ + ...this.broadKeywordEntries(), + ...this.coarseKeywordEntries(), + ...this.fineKeywordEntries(), + ].filter((item) => + selected.has(this.normalizeKeyword(this.getKeywordLabel(item))), + ); + } + + private getSelectedManualKeywordEntries(): KeywordEntryWithTopic[] { + const selected = new Set( + this.selectedKeywords().map((k) => this.normalizeKeyword(k)), + ); + return this.manualKeywordEntries().filter((item) => + selected.has(this.normalizeKeyword(this.getKeywordLabel(item))), + ); + } + + private filterKeywordEntries( + items: KeywordEntryWithTopic[], + keyword: string, + ): KeywordEntryWithTopic[] { + const normalized = this.normalizeKeyword(keyword); + return items.filter( + (item) => + this.normalizeKeyword(this.getKeywordLabel(item)) !== normalized, + ); + } + + private getKeywordLabel(item: KeywordEntryWithTopic): string { + return item.llm_keyword.keyword.trim(); + } + + private keywordEntriesFromStrings( + keywords: string[], + seenKeywords: Set = new Set(), + ): KeywordEntryWithTopic[] { + const entries: KeywordEntryWithTopic[] = []; + + for (const keyword of this.uniqueKeywords(keywords)) { + const normalized = this.normalizeKeyword(keyword); + if (!normalized || seenKeywords.has(normalized)) continue; + + seenKeywords.add(normalized); + entries.push({ + llm_keyword: { keyword, relevance_score: 0 }, + topic_mapping: null, + }); + } + + return entries; + } + + private uniqueKeywordEntries( + items: KeywordEntryWithTopic[], + seenKeywords: Set = new Set(), + ): KeywordEntryWithTopic[] { + const uniqueItems: KeywordEntryWithTopic[] = []; + for (const item of items ?? []) { + const normalized = this.normalizeKeyword(this.getKeywordLabel(item)); + if (!normalized || seenKeywords.has(normalized)) continue; + + seenKeywords.add(normalized); + uniqueItems.push(item); + } + return uniqueItems; + } + + // --- URL <-> state sync ----------------------------------------------- + + restoreStateFromQueryParams(): void { + const queryParams = this.route.snapshot.queryParamMap; + const mode = this.parseMode(queryParams.get('mode')); + const urlInput = queryParams.get('url') ?? ''; + const textInput = queryParams.get('text') ?? ''; + const manual = this.parseKeywordList(queryParams.get('manual')); + const selected = this.parseKeywordList(queryParams.get('selected')); + const source = queryParams.get('source') ?? ''; + + this.isRestoringState = true; + + this.form.patchValue( + { selectedInputType: mode, urlInput, textInput }, + { emitEvent: false }, + ); + + this.extractionSource.set(source as InputMode); + this.restoreSourceFromSession(); + + const merged = this.uniqueKeywordEntries([ + ...this.manualKeywordEntries(), // session restored entries + ...this.keywordEntriesFromStrings(manual), // query param entries + ]); + this.manualKeywordEntries.set(merged); + + // enrich only newly added keywords that have no topic yet + this.enrichManualKeywordsWithTopics(manual); + + // User intent (the current selection): the URL is always authoritative + // here, deliberately overriding whatever the session cache had. This + // is what makes a deep link like ?selected=foo&manual=bar from another + // page reliably preselect keywords, instead of getting merged with (or + // hidden behind) leftover state from a previous visit in the same tab. + + // clean up the selection to only include keywords that actually exist in + const manualKeywordSet = new Set( + this.manualKeywords().map((k) => this.normalizeKeyword(k)), + ); + const broadKeywordSet = new Set( + this.broadKeywords().map((k) => this.normalizeKeyword(k)), + ); + const coarseKeywordSet = new Set( + this.coarseKeywords().map((k) => this.normalizeKeyword(k)), + ); + const fineKeywordSet = new Set( + this.fineKeywords().map((k) => this.normalizeKeyword(k)), + ); + const validSelected = selected.filter( + (k) => + manualKeywordSet.has(this.normalizeKeyword(k)) || + broadKeywordSet.has(this.normalizeKeyword(k)) || + coarseKeywordSet.has(this.normalizeKeyword(k)) || + fineKeywordSet.has(this.normalizeKeyword(k)), + ); + const selectionWasTrimmed = validSelected.length !== selected.length; + + this.selectedKeywords.set(this.uniqueKeywords(validSelected)); + + if (selectionWasTrimmed) { + this.updateQueryParams(); + } + this.isRestoringState = false; + } + + updateQueryParams(): void { + if (this.isRestoringState) return; + + const queryParams = { + mode: this.form.controls.selectedInputType.value, + url: this.toNullableParam(this.form.controls.urlInput.value), + text: this.toNullableParam(this.form.controls.textInput.value), + broad: this.serializeKeywords(this.broadKeywords()), + coarse: this.serializeKeywords(this.coarseKeywords()), + fine: this.serializeKeywords(this.fineKeywords()), + manual: this.serializeKeywords(this.manualKeywords()), + selected: this.serializeKeywords(this.selectedKeywords()), + }; + + this.isOwnNavigation = true; + this.router + .navigate([], { + relativeTo: this.route, + queryParams, + queryParamsHandling: 'merge', + replaceUrl: true, + }) + .then((navigated) => { + // If Angular decided there was nothing to navigate (e.g. the URL + // would be identical), queryParamMap never emits, so the flag would + // otherwise stay stuck `true` and incorrectly swallow the *next* + // real external navigation. Reset it defensively in that case. + if (!navigated) { + this.isOwnNavigation = false; + } + }); + + // IMPORTANT: every state mutation flows through here, so this is also + // the single place that keeps sessionStorage in sync. Previously the + // session cache was only saved after a full extraction completed, so + // adding a manual keyword (or removing one, etc.) never updated it. The + // *next* query-param change then triggered restoreStateFromQueryParams() + // -> restoreSourceFromSession(), which overwrote the fresh manual + // keyword with that stale snapshot - making manually added keywords + // seem to vanish immediately. Saving here fixes that race. + this.saveSourceToSession(); + } + + private saveSourceToSession(): void { + const data = { + source: this.extractionSource(), + sourceContent: this.sourceContent(), + sourceUrl: this.sourceUrl(), + broadKeywordEntries: this.broadKeywordEntries(), + coarseKeywordEntries: this.coarseKeywordEntries(), + fineKeywordEntries: this.fineKeywordEntries(), + manualKeywordEntries: this.manualKeywordEntries(), + }; + + try { + sessionStorage.setItem(this.SESSION_KEY, JSON.stringify(data)); + } catch (error) { + console.error('Failed to persist keyword search state:', error); + } + } + + private restoreSourceFromSession(): void { + const raw = sessionStorage.getItem(this.SESSION_KEY); + if (!raw) return; + + try { + const { + source, + sourceContent, + sourceUrl, + broadKeywordEntries, + coarseKeywordEntries, + fineKeywordEntries, + manualKeywordEntries, + } = JSON.parse(raw); + + this.extractionSource.set(source as InputMode); + this.sourceContent.set(sourceContent ?? ''); + this.sourceUrl.set(sourceUrl ?? null); + this.broadKeywordEntries.set(broadKeywordEntries ?? []); + this.coarseKeywordEntries.set(coarseKeywordEntries ?? []); + this.fineKeywordEntries.set(fineKeywordEntries ?? []); + this.manualKeywordEntries.set(manualKeywordEntries ?? []); + } catch { + sessionStorage.removeItem(this.SESSION_KEY); + } + } + + private clearSourceFromSession(): void { + sessionStorage.removeItem(this.SESSION_KEY); + } + + private getCurrentExtractionQuery(): string { + const mode = this.form.controls.selectedInputType.value; + if (mode === 'url') return this.form.controls.urlInput.value.trim(); + if (mode === 'text') return this.form.controls.textInput.value.trim(); + return this.selectedKeywords().join(', ').trim(); + } + + private parseMode(mode: string | null): InputMode { + return mode === 'text' ? 'text' : 'url'; + } + + private parseKeywordList(rawValue: string | null): string[] { + if (!rawValue) return []; + return this.uniqueKeywords( + rawValue + .split(',') + .map((v) => v.trim()) + .filter((v) => !!v), + ); + } + + private serializeKeywords(keywords: string[]): string | null { + const sanitized = this.uniqueKeywords(keywords); + return sanitized.length ? sanitized.join(',') : null; + } + + private uniqueKeywords(values: string[]): string[] { + const uniqueValues: string[] = []; + const seenKeywords = new Set(); + + for (const value of values) { + const normalized = this.normalizeKeyword(value); + if (!normalized || seenKeywords.has(normalized)) continue; + + seenKeywords.add(normalized); + uniqueValues.push(value.trim()); + } + + return uniqueValues; + } + + private normalizeKeyword(value: string): string { + return value.trim().toLowerCase(); + } + + private toNullableParam(value: string): string | null { + const normalized = value.trim(); + return normalized.length ? normalized : null; + } + + private getProgressForStep(step: string): number { + switch (step) { + case 'started': + return 10; + case 'fetching_url': + return 20; + case 'content_extracted': + return 30; + case 'calling_llm': + return 40; + case 'enriching': + return 60; + default: + return 50; // fallback for unknown steps + } + } +} diff --git a/webapp/src/app/modules/keywords-search/keywords-websocket.service.ts b/webapp/src/app/modules/keywords-search/keywords-websocket.service.ts new file mode 100644 index 00000000..86622360 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-websocket.service.ts @@ -0,0 +1,117 @@ +// keyword-websocket.service.ts + +import { Injectable, Inject, Optional } from '@angular/core'; +import { webSocket, WebSocketSubject } from 'rxjs/webSocket'; +import { Observable, Subject, Subscription } from 'rxjs'; +import { KeywordsRequest } from '../../api/model/keywordsRequest'; +import { Configuration } from '../../api/configuration'; +import { BaseService } from '../../api/api.base.service'; +import { BASE_PATH } from '../../api/variables'; +import { ExtractedKeywords } from '../../api/model/extractedKeywords'; +import { ExtractedKeywordsResponse } from '../../api/model/extractedKeywordsResponse'; + +export interface WsEvent { + type: string; + step?: string | null; + message?: string | null; + result?: ExtractedKeywordsResponse; + content?: string | null; + level?: string | null; + keywords?: ExtractedKeywords; + duration?: number | null; +} + +@Injectable({ providedIn: 'root' }) +export class KeywordWebSocketService extends BaseService { + private socket$?: WebSocketSubject; + private socketSubscription?: Subscription; + private readonly messageSubject$ = new Subject(); // created once, stays for app lifetime + private connectionPromise: Promise | null = null; + + constructor( + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + this.url = + `${'http://localhost:8000'}/api/inse-service/keywords/extract/ws`.replace( + /^http/, + 'ws', + ); + } + private readonly url: string; + + connect(): Promise { + if (this.socket$ && this.socket$.closed === false) { + return Promise.resolve(); + } + if (this.connectionPromise) { + return this.connectionPromise; + } + + this.closeSocket(); + + // no longer recreate messageSubject$ here + + this.connectionPromise = new Promise((resolve, reject) => { + this.socket$ = webSocket({ + url: this.url, + deserializer: (msg) => JSON.parse(msg.data), + serializer: (value) => JSON.stringify(value), + openObserver: { + next: () => resolve(), + }, + closeObserver: { + next: () => { + this.connectionPromise = null; + }, + }, + }); + + this.socketSubscription = this.socket$.subscribe({ + next: (event: WsEvent) => this.messageSubject$.next(event), + error: (err) => { + // don't error/complete the shared subject — just reject this connection attempt + console.error('WebSocket error', err); + reject(err); + this.connectionPromise = null; + }, + complete: () => { + this.connectionPromise = null; + }, + }); + }); + + return this.connectionPromise; + } + + async sendRequest(req: KeywordsRequest): Promise { + await this.connect(); + if (this.socket$) { + this.socket$.next(req); + } else { + throw new Error('WebSocket not available'); + } + } + + getMessages(): Observable { + return this.messageSubject$.asObservable(); + } + + close(): void { + this.closeSocket(); + // don't complete messageSubject$ — it must survive across connections + } + + private closeSocket(): void { + if (this.socketSubscription) { + this.socketSubscription.unsubscribe(); + this.socketSubscription = undefined; + } + if (this.socket$) { + this.socket$.complete(); + this.socket$ = undefined; + } + this.connectionPromise = null; + } +} diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index cdb886cf..d1bd9864 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -116,9 +116,12 @@ track keyword; let i = $index ) { - {{ - keyword - }} + {{ keyword }} } } @else {

Keine Schlüsselwörter gefunden.

diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index e93ec298..8f721f20 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -6,7 +6,7 @@ import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; - +import { Router } from '@angular/router'; import { WorksService } from '../../api'; interface MentionedPerson { @@ -45,6 +45,7 @@ export class NewsDetailComponent implements OnInit { private readonly httpClient = inject(HttpClient); private readonly worksService = inject(WorksService); private readonly location = inject(Location); + private readonly router = inject(Router); article: NewsArticleDetail | null = null; loading = false; @@ -70,7 +71,11 @@ export class NewsDetailComponent implements OnInit { navigateBack(): void { this.location.back(); } - + onKeywordClick(keyword: string): void { + this.router.navigate(['/keywords'], { + queryParams: { selected: keyword, manual: keyword }, + }); + } formatDate(dateStr?: string | null): string { if (!dateStr) return '-'; const date = new Date(dateStr); diff --git a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts index 3005dfc5..a192c306 100644 --- a/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts +++ b/webapp/src/app/modules/organizations/organization-dialog/organization-dialog.component.ts @@ -16,15 +16,22 @@ import { import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; -import type { - CreateOrganizationPayload, - OrganizationProfile, - UpdateOrganizationPayload, -} from '../../../shared/services/organization-management.service'; +import { InseOrganizationManagementModelOrganizationProfile } from '../../../api'; + +export interface CreateOrganizationPayload { + name: string; + other_inst_id?: string | null; +} + +export interface UpdateOrganizationPayload { + name?: string; + other_inst_id?: string | null; + deleted?: boolean; +} export interface OrganizationDialogData { mode: 'create' | 'edit'; - organization?: OrganizationProfile; + organization?: InseOrganizationManagementModelOrganizationProfile; } export type OrganizationDialogResult = @@ -99,6 +106,6 @@ export class OrganizationDialogComponent { } protected close(): void { - this.dialogRef.close(undefined); + this.dialogRef.close(); } } diff --git a/webapp/src/app/modules/organizations/organizations.component.html b/webapp/src/app/modules/organizations/organizations.component.html index a6486b74..14853ec0 100644 --- a/webapp/src/app/modules/organizations/organizations.component.html +++ b/webapp/src/app/modules/organizations/organizations.component.html @@ -3,6 +3,7 @@

Organisationen

Mandanten, externe Institutions-IDs und Status verwalten.

+
- Seite {{ page + 1 }} - - - + + + + + + + + + + {{ (row.deleted ? 'inactive' : 'active') | status }} + + + + +
+ + +
+
diff --git a/webapp/src/app/modules/organizations/organizations.component.scss b/webapp/src/app/modules/organizations/organizations.component.scss index b558f858..e455d7e3 100644 --- a/webapp/src/app/modules/organizations/organizations.component.scss +++ b/webapp/src/app/modules/organizations/organizations.component.scss @@ -5,15 +5,9 @@ padding: 24px; } -.page-header, -.table-header, -.pagination, -.row-actions { +.page-header { display: flex; align-items: center; -} - -.page-header { justify-content: space-between; gap: 16px; } @@ -32,60 +26,6 @@ p { margin-top: 6px; } -.table-panel { - overflow: hidden; - border: 1px solid #d7dde6; - border-radius: 8px; - background: #fff; -} - -.table-header { - justify-content: space-between; - padding: 16px; - border-bottom: 1px solid #e5e7eb; -} - -.table-wrap { - overflow-x: auto; -} - -table { - width: 100%; - border-collapse: collapse; -} - -th, -td { - padding: 12px 16px; - text-align: left; - border-bottom: 1px solid #edf1f7; - white-space: nowrap; -} - -th { - color: #475569; - font-weight: 700; - background: #f8fafc; -} - -tr.deleted { - color: #94a3b8; -} - -.identifier { - font-family: monospace; - font-size: 12px; -} - -.link-button { - border: 0; - background: transparent; - color: #1d4ed8; - padding: 0; - font: inherit; - cursor: pointer; -} - .status { display: inline-flex; align-items: center; @@ -103,21 +43,6 @@ tr.deleted { color: #991b1b; } -.row-actions { - gap: 4px; -} - -.empty { - color: #64748b; - text-align: center; -} - -.pagination { - justify-content: flex-end; - gap: 8px; - padding: 12px 16px; -} - @media (max-width: 640px) { .organizations-page { padding: 16px; @@ -128,3 +53,8 @@ tr.deleted { flex-direction: column; } } + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} diff --git a/webapp/src/app/modules/organizations/organizations.component.ts b/webapp/src/app/modules/organizations/organizations.component.ts index b857d1fd..6cbaecb4 100644 --- a/webapp/src/app/modules/organizations/organizations.component.ts +++ b/webapp/src/app/modules/organizations/organizations.component.ts @@ -1,19 +1,34 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit, inject } from '@angular/core'; +import { + Component, + inject, + input, + OnInit, + TemplateRef, + viewChild, +} from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; -import { finalize } from 'rxjs'; -import { - OrganizationManagementService, - OrganizationProfile, -} from '../../shared/services/organization-management.service'; import type { OrganizationDialogComponent, OrganizationDialogData, OrganizationDialogResult, } from './organization-dialog/organization-dialog.component'; +import { + InseOrganizationManagementModelOrganizationProfile, + OrganizationPage, + OrganizationService, +} from '../../api'; +import { + GenericColumn, + DataTableComponent, +} from '../../shared/ui/data-table/data-table.component'; +import { MatCardModule } from '@angular/material/card'; +import { StatusPipe } from '../../shared/pipes/status.pipe'; +import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { Router } from '@angular/router'; @Component({ selector: 'app-organizations', @@ -23,51 +38,81 @@ import type { MatDialogModule, MatIconModule, MatSnackBarModule, + DataTableComponent, + MatCardModule, + StatusPipe, + QueryParamPaginatorComponent, ], templateUrl: './organizations.component.html', styleUrl: './organizations.component.scss', standalone: true, }) export class OrganizationsComponent implements OnInit { - private readonly organizationService = inject(OrganizationManagementService); + private readonly router = inject(Router); private readonly dialog = inject(MatDialog); private readonly snackBar = inject(MatSnackBar); + private readonly organizationService = inject(OrganizationService); - protected organizations: OrganizationProfile[] = []; - protected total = 0; - protected page = 0; - protected readonly pageSize = 10; - protected isLoading = false; + organizationPage = input.required(); + organizationColumns: GenericColumn[] = + []; + + organizationStatusTmp = viewChild.required>( + 'organizationStatusTmp', + ); + organizationActionsTmp = viewChild.required>( + 'organizationActionsTmp', + ); ngOnInit(): void { - this.loadOrganizations(); - } - - protected loadOrganizations(page = this.page): void { - this.page = page; - this.isLoading = true; - this.organizationService - .getOrganizations(page, this.pageSize) - .pipe(finalize(() => (this.isLoading = false))) - .subscribe({ - next: (result) => { - this.organizations = result.items; - this.total = result.total; - }, - error: () => - this.showError('Organisationen konnten nicht geladen werden.'), - }); + this.organizationColumns = [ + { + id: 'name', + header: 'Name', + type: 'accessor', + accessorKey: 'name', + }, + { + id: 'other_inst_id', + header: 'Externe ID', + type: 'accessor', + accessorKey: 'other_inst_id', + }, + { + id: 'member_count', + header: 'Mitglieder', + type: 'accessor', + accessorKey: 'member_count', + }, + { + id: 'deleted', + header: 'Status', + type: 'accessor', + accessorKey: 'deleted', + cellTemplate: this.organizationStatusTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.organizationActionsTmp(), + }, + ]; } protected startCreate(): void { this.openDialog({ mode: 'create' }); } - protected startEdit(organization: OrganizationProfile): void { + protected startEdit( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { this.openDialog({ mode: 'edit', organization }); } - protected deleteOrganization(organization: OrganizationProfile): void { + protected deleteOrganization( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { if (organization.deleted) return; import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( @@ -88,27 +133,24 @@ export class OrganizationsComponent implements OnInit { ); } - private softDeleteOrganization(organization: OrganizationProfile): void { - this.organizationService.deleteOrganization(organization.id).subscribe({ + private softDeleteOrganization( + organization: InseOrganizationManagementModelOrganizationProfile, + ): void { + this.organizationService.deleteOrganisation(organization.id).subscribe({ next: () => { this.snackBar.open('Organisation wurde deaktiviert.', 'OK', { duration: 3000, }); - this.loadOrganizations(); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, error: () => this.showError('Organisation konnte nicht deaktiviert werden.'), }); } - protected get canPageBack(): boolean { - return this.page > 0; - } - - protected get canPageForward(): boolean { - return (this.page + 1) * this.pageSize < this.total; - } - private openDialog(data: OrganizationDialogData): void { import('./organization-dialog/organization-dialog.component').then( ({ OrganizationDialogComponent }) => { @@ -132,8 +174,8 @@ export class OrganizationsComponent implements OnInit { private save(result: OrganizationDialogResult): void { const request = result.mode === 'create' - ? this.organizationService.createOrganization(result.payload) - : this.organizationService.updateOrganization( + ? this.organizationService.createOrganisation(result.payload) + : this.organizationService.updateOrganisation( result.organizationId, result.payload, ); @@ -143,7 +185,10 @@ export class OrganizationsComponent implements OnInit { this.snackBar.open('Organisation wurde gespeichert.', 'OK', { duration: 3000, }); - this.loadOrganizations(0); + this.router.navigate([], { + queryParams: { page: 0 }, + queryParamsHandling: 'merge', + }); }, error: (error) => this.showError( diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.html b/webapp/src/app/modules/patent-detail/patent-detail.component.html new file mode 100644 index 00000000..ba19750e --- /dev/null +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.html @@ -0,0 +1,332 @@ +
+ + + @if (loading) { +
+ +

Patent wird geladen...

+
+ } @else if (notFound || !patent) { +
+ search_off +

Patent nicht gefunden

+

Das Patent konnte nicht geladen werden.

+ Zur Patentübersicht +
+ } @else { +
+
+
+ + {{ patent.source }} + + @if (patent.publication_year) { + {{ patent.publication_year }} + } + @if (stageLabel(); as stage) { + {{ stage }} + } +
+

{{ patent.title || patent.patent_id || 'Ohne Titel' }}

+

+ @if (patent.publication_date; as date) { + · {{ formatDate(date) }} + } +

+
+ @for (link of externalLinks(); track link.url; let first = $first) { + + {{ link.label }} + open_in_new + + } +
+
+ +
+
+ groups + {{ patent.inventors && patent.inventors.length }} + Erfinder +
+
+ business + {{ patent.assignees && patent.assignees.length }} + Anmelder +
+
+ category + {{ + (patent.ipc?.length ?? 0) + (patent.cpc?.length ?? 0) + }} + Klassifikationen +
+
+
+ +
+
+ @if (patent.abstract) { +
+
+ subject +

Abstract

+
+

{{ patent.abstract }}

+
+ } + +
+
+ engineering +

Erfinder

+ {{ patent.inventors && patent.inventors.length }} +
+
+ @for (inventor of patent.inventors; track inventor) { + {{ inventor }} + } @empty { +

Keine Angaben vorhanden.

+ } +
+
+ + @if (patent.assignees && patent.assignees.length > 0) { +
+
+ account_balance +

Anmelder

+ {{ patent.assignees.length }} +
+
+ @for (assignee of patent.assignees; track assignee) { +
+ {{ assignee }} +
+ } +
+
+ } + + @if (patent.ipc_descriptions && patent.ipc_descriptions.length > 0) { +
+
+ label +

Klassifikation (IPC)

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

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

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

Klassifikation (IPC)

+
+
+ @for (ipc of patent.ipc; track ipc) { + {{ ipc }} + } +
+
+ } + + @if (patent.cpc_descriptions && patent.cpc_descriptions.length > 0) { +
+
+ label +

Klassifikation (CPC)

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

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

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

Klassifikation (CPC)

+
+
+ @for (cpc of patent.cpc; track cpc) { + {{ cpc }} + } +
+
+ } +
+ + +
+ } +
diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.scss b/webapp/src/app/modules/patent-detail/patent-detail.component.scss new file mode 100644 index 00000000..6e9a4afc --- /dev/null +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.scss @@ -0,0 +1,462 @@ +:host { + display: block; + background: var(--sg-background); +} + +.detail-page { + max-width: 1500px; + margin: 0 auto; + padding: 26px 32px 56px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 7px; + margin-bottom: 22px; + padding: 0; + border: 0; + background: transparent; + color: var(--sg-text-muted); + font-size: 13px; + font-weight: 600; + text-decoration: none; + cursor: pointer; +} + +.back-link mat-icon { + width: 18px; + height: 18px; + font-size: 18px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1fr) 420px; + gap: 42px; + padding: 38px 42px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-lg); + background: + radial-gradient( + circle at 90% 10%, + rgba(200, 217, 255, 0.75), + transparent 35% + ), + linear-gradient(140deg, #fff 0%, #f8faff 100%); + box-shadow: var(--sg-shadow-sm); +} + +.eyebrow, +.tags, +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.eyebrow span { + padding: 5px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + background: rgba(255, 255, 255, 0.85); + color: var(--sg-text-muted); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +h1 { + max-width: 920px; + margin: 20px 0 13px; + font-size: clamp(27px, 3vw, 42px); + line-height: 1.13; +} + +.meta-line { + max-width: 900px; + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; + line-height: 1.7; +} + +.hero-actions { + margin-top: 26px; +} + +.hero-actions a { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 42px; + padding: 9px 16px; + border: 1px solid var(--sg-border-strong); + border-radius: var(--sg-radius-sm); + background: #fff; + color: var(--sg-text); + font-weight: 700; + text-decoration: none; +} + +.hero-actions a.primary-action { + border-color: var(--sg-primary); + background: var(--sg-primary); + color: #fff; +} + +.hero-actions mat-icon { + width: 17px; + height: 17px; + font-size: 17px; +} + +.metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + align-self: center; + overflow: hidden; + border: 1px solid rgba(199, 211, 232, 0.8); + border-radius: var(--sg-radius-md); + background: rgba(255, 255, 255, 0.8); +} + +.metrics div { + display: flex; + align-items: center; + flex-direction: column; + gap: 5px; + padding: 22px 10px; + text-align: center; +} + +.metrics div + div { + border-left: 1px solid var(--sg-border); +} + +.metrics mat-icon { + color: var(--sg-text-soft); +} + +.metrics strong { + color: var(--sg-text); + font-family: 'Montserrat', 'Open Sans', sans-serif; + font-size: 22px; +} + +.metrics span { + color: var(--sg-text-muted); + font-size: 11px; +} + +.content-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) 380px; + gap: 24px; + margin-top: 24px; +} + +main, +aside { + display: flex; + flex-direction: column; + gap: 24px; +} + +.card { + padding: 26px 28px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-md); + background: var(--sg-surface); + box-shadow: var(--sg-shadow-sm); +} + +.section-title { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 20px; +} + +.section-title mat-icon { + color: var(--sg-text-muted); +} + +.section-title h2 { + margin: 0; + font-size: 16px; +} + +.section-title span { + margin-left: auto; + color: var(--sg-text-muted); + font-size: 12px; +} + +.abstract-card p { + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.8; +} + +.tags span { + padding: 7px 10px; + border: 1px solid var(--sg-border); + border-radius: 999px; + color: var(--sg-text-muted); + font-size: 11px; +} + +.compact-list, +.link-list { + display: grid; + gap: 10px; +} + +.compact-list div { + display: flex; + align-items: flex-start; + flex-direction: column; + gap: 3px; + padding: 13px 0; + border-bottom: 1px solid var(--sg-border); +} + +.compact-list div:last-child { + border-bottom: 0; +} + +.compact-list strong { + font-size: 12px; +} + +dl { + margin: 0; +} + +dl div { + display: grid; + grid-template-columns: 115px minmax(0, 1fr); + gap: 12px; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); +} + +dl div:last-child { + border-bottom: 0; +} + +dt { + color: var(--sg-text-muted); + font-size: 12px; +} + +dd { + margin: 0; + overflow-wrap: anywhere; + color: var(--sg-text); + font-size: 12px; + font-weight: 600; + text-align: right; +} + +.link-list a { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 0; + border-bottom: 1px solid var(--sg-border); + color: var(--sg-text); + font-size: 12px; + font-weight: 700; + text-decoration: none; +} + +.link-list a:last-child { + border-bottom: 0; +} + +.link-list mat-icon { + width: 16px; + height: 16px; + color: var(--sg-text-muted); + font-size: 16px; +} + +.state { + display: grid; + place-items: center; + min-height: 380px; + color: var(--sg-text-muted); + text-align: center; +} + +.error-state mat-icon { + width: 46px; + height: 46px; + font-size: 46px; +} + +.empty { + color: var(--sg-text-muted); +} + +.source-badge { + display: inline-flex; + align-items: center; + padding: 4px 10px; + border-radius: 999px; + font-size: 11px; + font-weight: 700; + text-transform: uppercase; +} + +.source-badge--epo { + background: #e8f7ee; + color: #1f7a43; +} + +.source-badge--uspto { + background: #eef3ff; + color: #1f4fbf; +} + +.classification-cards { + display: grid; + gap: 12px; +} + +.classification-card { + padding: 16px; + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); +} + +.classification-card-section--ipc .classification-card { + background: #f4f8ff; +} + +.classification-card-section--cpc .classification-card { + background: #f3fbf5; +} + +.classification-card__header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + margin-bottom: 10px; +} + +.classification-card__codes { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.classification-code { + padding: 4px 8px; + border-radius: 6px; + background: #fff; + color: var(--sg-text); + font-size: 12px; + font-weight: 700; +} + +.classification-card__badges { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.classification-badge { + padding: 3px 8px; + border-radius: 999px; + font-size: 10px; + font-weight: 700; + text-transform: uppercase; +} + +.classification-badge--system { + background: #e8eef8; + color: #35507a; +} + +.classification-badge--level { + background: #fff; + color: var(--sg-text-muted); +} + +.classification-summary { + margin: 0 0 8px; + color: var(--sg-text); + font-size: 13px; + line-height: 1.6; +} + +.classification-toggle { + padding: 0; + border: 0; + background: transparent; + color: var(--sg-primary); + font-size: 12px; + font-weight: 700; + cursor: pointer; +} + +.classification-hierarchy { + margin: 12px 0 0; +} + +.classification-hierarchy__row { + display: grid; + grid-template-columns: 90px minmax(0, 1fr); + gap: 10px; + padding: 6px 0; + border-top: 1px solid rgba(0, 0, 0, 0.06); +} + +.classification-hierarchy__row dt { + color: var(--sg-text-muted); + font-size: 11px; +} + +.classification-hierarchy__row dd { + margin: 0; + color: var(--sg-text); + font-size: 12px; + text-align: left; +} + +@media (max-width: 1150px) { + .hero, + .content-grid { + grid-template-columns: 1fr; + } + + .metrics { + width: 100%; + } +} + +@media (max-width: 700px) { + .detail-page { + padding: 18px 16px 40px; + } + + .hero, + .card { + padding: 22px 20px; + } + + .metrics { + grid-template-columns: 1fr; + } + + .metrics div + div { + border-top: 1px solid var(--sg-border); + border-left: 0; + } +} diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.ts b/webapp/src/app/modules/patent-detail/patent-detail.component.ts new file mode 100644 index 00000000..5052d8db --- /dev/null +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.ts @@ -0,0 +1,139 @@ +import { Location } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { finalize } from 'rxjs'; + +import { PatentsService } from '../../api/api/patents.service'; +import { PatentEntry } from '../../api/model/patentEntry'; +import { + ClassificationCard, + ClassificationSystem, + formatPatentDate, + getClassificationCards, + getDescriptionPreview, + getPatentMetadataRows, + getPublicationStageLabel, + isLongDescription, + patentExternalLinks, +} from './patent-detail.utils'; + +@Component({ + selector: 'app-patent-detail', + imports: [ + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + RouterLink, + ], + templateUrl: './patent-detail.component.html', + styleUrl: './patent-detail.component.scss', +}) +export class PatentDetailComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly patentsService = inject(PatentsService); + private readonly location = inject(Location); + + patent: PatentEntry | null = null; + loading = true; + notFound = false; + + private expandedClassificationKeys = new Set(); + + ngOnInit(): void { + this.route.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const patentId = params.get('patentId'); + if (!patentId) { + this.loading = false; + this.notFound = true; + return; + } + + const title = + this.route.snapshot.queryParamMap.get('title') ?? undefined; + const prefix = + this.route.snapshot.queryParamMap.get('prefix') ?? undefined; + const fillingDate = + this.route.snapshot.queryParamMap.get('fillingDate') ?? undefined; + + this.loadPatent(patentId, title, prefix, fillingDate); + }); + } + + navigateBack(): void { + this.location.back(); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + metadataRows() { + return this.patent ? getPatentMetadataRows(this.patent) : []; + } + + stageLabel(): string | null { + return this.patent ? getPublicationStageLabel(this.patent) : null; + } + + externalLinks() { + return this.patent ? patentExternalLinks(this.patent) : []; + } + + classificationCards( + entries: PatentEntry['ipc_descriptions'], + system: ClassificationSystem, + ): ClassificationCard[] { + return getClassificationCards(entries, system); + } + + 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 isLongDescription(text); + } + + getDescriptionPreview(text: string | null): string { + return getDescriptionPreview(text); + } + + private loadPatent( + patentId: string, + title?: string, + prefix?: string, + fillingDate?: string, + ): void { + this.loading = true; + this.notFound = false; + this.patent = null; + this.expandedClassificationKeys.clear(); + + this.patentsService + .getPatentByIdOrTitle(patentId, prefix, title, fillingDate) + .pipe(finalize(() => (this.loading = false))) + .subscribe({ + next: (patent) => { + this.patent = patent; + }, + error: () => { + this.notFound = true; + }, + }); + } +} diff --git a/webapp/src/app/modules/patent-detail/patent-detail.utils.ts b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts new file mode 100644 index 00000000..e45957d9 --- /dev/null +++ b/webapp/src/app/modules/patent-detail/patent-detail.utils.ts @@ -0,0 +1,213 @@ +import { PatentEntry } from '../../api/model/patentEntry'; +import { IpcClassification } from '../../api/model/ipcClassification'; +export type ClassificationSystem = 'IPC' | 'CPC'; + +export interface ClassificationCard { + key: string; + symbols: string[]; + system: ClassificationSystem; + levelLabel: string; + primaryDescription: string | null; + hierarchy: { label: string; value: string }[]; +} + +export interface PatentMetadataRow { + label: string; + value: string; + variant?: 'source'; +} + +const DESCRIPTION_PREVIEW_LENGTH = 140; + +export function formatPatentDate(date: string | null | undefined): string { + if (!date) return '-'; + const normalized = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); + const parsed = new Date(normalized); + if (isNaN(parsed.getTime())) return date; + return new Intl.DateTimeFormat('de-DE').format(parsed); +} + +export function formatMetadataLabel(value: string): string { + return value + .replace(/_/g, ' ') + .toLowerCase() + .replace(/\b\w/g, (char) => char.toUpperCase()); +} + +export function getPublicationStageLabel(patent: PatentEntry): string | null { + return patent.kind ?? patent.application_type ?? null; +} + +export function getPatentMetadataRows( + patent: PatentEntry, +): PatentMetadataRow[] { + const rows: PatentMetadataRow[] = [ + { label: 'Quelle', value: patent.source, variant: 'source' }, + { label: 'Patent-Nr.', value: patent.patent_id }, + ]; + + if (patent.publication_date) { + rows.push({ + label: 'Veröffentlichungsdatum', + value: formatPatentDate(patent.publication_date), + }); + } + if (patent.application_number) { + rows.push({ label: 'Anmeldungsnummer', value: patent.application_number }); + } + if (patent.application_date) { + rows.push({ + label: 'Anmeldedatum', + value: formatPatentDate(patent.application_date), + }); + } + + const stageLabel = getPublicationStageLabel(patent); + if (stageLabel) { + rows.push({ + label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp', + value: patent.kind ? stageLabel : 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: formatMetadataLabel(patent.status) }); + } + + return rows; +} + +export function getClassificationCards( + entries: IpcClassification[] | undefined, + system: ClassificationSystem, +): ClassificationCard[] { + if (!entries?.length) return []; + + const merged = new Map(); + + for (const entry of entries) { + const card = 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()]; +} + +export function isLongDescription(text: string | null): boolean { + return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH; +} + +export function getDescriptionPreview(text: string | null): string { + if (!text) return ''; + if (text.length <= DESCRIPTION_PREVIEW_LENGTH) return text; + return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`; +} + +export function patentExternalLinks( + patent: PatentEntry, +): { label: string; url: string }[] { + const links: { label: string; url: string }[] = []; + const encodedId = encodeURIComponent(patent.patent_id); + + if (patent.source === 'EPO') { + links.push({ + label: 'Espacenet', + url: `https://worldwide.espacenet.com/patent/search?q=pn%3D${encodedId}`, + }); + } + if (patent.source === 'USPTO') { + links.push({ + label: 'Google Patents', + url: `https://patents.google.com/patent/${encodedId}`, + }); + } + + return links; +} + +function buildClassificationCard( + entry: IpcClassification, + system: ClassificationSystem, +): ClassificationCard { + const level = getClassificationLevel(entry); + const primaryDescription = extractDescriptionText(entry[level.field]); + + return { + key: `${system}-${entry.symbol}`, + symbols: [entry.symbol], + system, + levelLabel: level.label, + primaryDescription, + hierarchy: buildHierarchyRows(entry, primaryDescription), + }; +} + +function 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' }; +} + +function buildHierarchyRows( + entry: IpcClassification, + primaryDescription: string | null, +): { label: string; value: string }[] { + const rows: { label: string; value: string }[] = []; + const seen = new Set(); + + const addRow = (label: string, raw: string | null) => { + const value = 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 }); + }; + if (entry.section) addRow('Sektion', entry.section); + if (entry.class) addRow('Klasse', entry.class); + if (entry.subclass) addRow('Unterklasse', entry.subclass); + + return rows; +} + +function 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; + if (firstSentence !== firstSentence.toUpperCase()) return firstSentence; + return firstSentence.charAt(0) + firstSentence.slice(1).toLowerCase(); +} diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 2d27bcd0..92d02cec 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -26,14 +26,11 @@ USPTO -
- -
+ diff --git a/webapp/src/app/modules/patents/patents.component.scss b/webapp/src/app/modules/patents/patents.component.scss index c24868b8..feba9411 100644 --- a/webapp/src/app/modules/patents/patents.component.scss +++ b/webapp/src/app/modules/patents/patents.component.scss @@ -12,20 +12,6 @@ h1 { 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; @@ -37,6 +23,146 @@ h1 { display: flex; justify-content: space-between; align-items: center; + flex-wrap: wrap; + gap: 1rem; +} + +.year-filter { + width: min(285px, 100%); + padding: 8px 10px; + border: 1px solid #dbe5f6; + border-radius: 10px; + background: #fbfdff; + box-sizing: border-box; +} + +.year-filter-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 4px; +} + +.year-filter-label { + color: #07163d; + font-size: 12px; + font-weight: 700; +} + +.reset-range-button { + border: 0; + background: transparent; + color: #0057ff; + font-size: 11px; + cursor: pointer; + padding: 0; + font-family: inherit; + + &:disabled { + color: #9aa5bc; + cursor: default; + } +} + +.year-filter-values { + display: flex; + align-items: center; + justify-content: center; + gap: 7px; + margin-bottom: 5px; + color: #40506f; + font-size: 12px; + font-weight: 600; +} + +.year-filter-bounds { + display: flex; + justify-content: space-between; + margin-top: 1px; + color: #7c88a3; + font-size: 10px; +} + +.year-range-slider { + --range-start: 0%; + --range-end: 100%; + --accent: #0057ff; + + position: relative; + height: 22px; +} + +.range-track { + position: absolute; + top: 50%; + left: 0; + right: 0; + height: 5px; + transform: translateY(-50%); + border-radius: 999px; + background: linear-gradient( + to right, + #d8e2f4 0%, + #d8e2f4 var(--range-start), + var(--accent) var(--range-start), + var(--accent) var(--range-end), + #d8e2f4 var(--range-end), + #d8e2f4 100% + ); +} + +.range-input { + position: absolute; + inset: 0; + width: 100%; + height: 22px; + margin: 0; + appearance: none; + background: transparent; + pointer-events: none; + + &::-webkit-slider-runnable-track, + &::-moz-range-track { + height: 5px; + background: transparent; + border: none; + } + + &::-webkit-slider-thumb { + appearance: none; + width: 15px; + height: 15px; + margin-top: -5px; + border: 2px solid #ffffff; + border-radius: 50%; + background: #0057ff; + box-shadow: + 0 0 0 1px #9ab7ff, + 0 2px 6px rgba(0, 87, 255, 0.22); + cursor: pointer; + pointer-events: auto; + } + + &::-moz-range-thumb { + width: 15px; + height: 15px; + border: 2px solid #ffffff; + border-radius: 50%; + background: #0057ff; + box-shadow: + 0 0 0 1px #9ab7ff, + 0 2px 6px rgba(0, 87, 255, 0.22); + cursor: pointer; + pointer-events: auto; + } +} + +.range-input-start { + z-index: 2; +} +.range-input-end { + z-index: 3; } .state-message { diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index 3a0dd94b..e6af3264 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -15,6 +15,10 @@ import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; import { PatentsService } from '../../api/api/patents.service'; import { PatentEntry } from '../../api/model/patentEntry'; import { IpcClassification } from '../../api'; +import { + QueryParamSelectorComponent, + SelectorOption, +} from '../../shared/ui/query-param-selector/query-param-selector.component'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; type ClassificationSystem = 'IPC' | 'CPC'; @@ -44,6 +48,7 @@ const DESCRIPTION_PREVIEW_LENGTH = 140; MatProgressSpinnerModule, MatChipsModule, MatDividerModule, + QueryParamSelectorComponent, ], templateUrl: './patents.component.html', styleUrl: './patents.component.scss', @@ -71,6 +76,12 @@ export class PatentsComponent implements OnInit { private searchSubject = new Subject(); + sortingDirectionOptions: SelectorOption[] = [ + { value: '', display_name: '' }, + { value: 'asc', display_name: 'Aufsteigend' }, + { value: 'desc', display_name: 'Absteigend' }, + ]; + constructor() { this.searchSubject .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed()) diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 873c4475..920d0bee 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -7,226 +7,7 @@ } @else {
- @if (showDetail && selectedPatent) { -
- - -

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

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

Abstract

-

{{ selectedPatent.abstract }}

-
- } - -
-

Erfinder

-
    - @for (inventor of selectedPatent.inventors; track inventor) { -
  • {{ inventor }}
  • - } -
-
- - @if ( - selectedPatent.assignees && selectedPatent.assignees.length > 0 - ) { -
-

Anmelder

-
    - @for (assignee of selectedPatent.assignees; track assignee) { -
  • {{ assignee }}
  • - } -
-
- } - - @if ( - selectedPatent.ipc_descriptions && - selectedPatent.ipc_descriptions.length > 0 - ) { -
-

Klassifikation (IPC)

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

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

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

Klassifikation (IPC)

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

Klassifikation (CPC)

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

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

- @if (isLongDescription(card.primaryDescription)) { - - } - } - - @if (card.hierarchy.length > 0) { -
- @for (row of card.hierarchy; track row.label) { -
-
{{ row.label }}
-
{{ row.value }}
-
- } -
- } -
- } -
-
- } -
- } - -
+
- @if (selectedPatent && !showDetail) { + @if (selectedPatent) {

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

diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html index 8da21925..f5df4652 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html +++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.html @@ -5,7 +5,7 @@

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

- @for (ipr of patents; track ipr.title) { + @for (ipr of patents; track ipr.applicationIdentifier) {
@if (ipr.type === 'PATENT') { diff --git a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts index 1d8f46ac..248c91a4 100644 --- a/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts +++ b/webapp/src/app/modules/projects/eu-cordis-details/patents-cards/patents-cards.component.ts @@ -16,9 +16,11 @@ export class PatentsCardsComponent { @Input() headerTitle: string = 'IPRs'; private router = inject(Router); searchForPatent(patent: Fp7ProjectIPR): void { - this.router.navigate(['/patents'], { + this.router.navigate([`/patent/${patent.applicationIdentifier}`], { queryParams: { - search: patent.title, + prefix: patent.applicationPrefix, + title: patent.title, + fillingDate: patent.applicationDate, }, }); } diff --git a/webapp/src/app/modules/projects/projects.component.html b/webapp/src/app/modules/projects/projects.component.html index 706f34fb..b2bcbddf 100644 --- a/webapp/src/app/modules/projects/projects.component.html +++ b/webapp/src/app/modules/projects/projects.component.html @@ -28,11 +28,13 @@
+ queryParamKey="sort_by" + label="Sortieren nach" /> + queryParamKey="sorting_order" + label="Sortierreihenfolge" />
diff --git a/webapp/src/app/resolvers/account.resolver.ts b/webapp/src/app/resolvers/account.resolver.ts index 9a2b7936..13b005b4 100644 --- a/webapp/src/app/resolvers/account.resolver.ts +++ b/webapp/src/app/resolvers/account.resolver.ts @@ -1,8 +1,7 @@ import { ResolveFn } from '@angular/router'; -import { AccountProfile } from '../api'; +import { AccountProfile, AuthService } from '../api'; import { inject } from '@angular/core'; -import { AccountManagementService } from '../shared/services/account-management.service'; export const accountResolver: ResolveFn = (route, state) => { - return inject(AccountManagementService).getCurrentAccount(); + return inject(AuthService).getCurrentAccount(); }; diff --git a/webapp/src/app/resolvers/accounts-organizations.resolver.ts b/webapp/src/app/resolvers/accounts-organizations.resolver.ts new file mode 100644 index 00000000..8fb026c9 --- /dev/null +++ b/webapp/src/app/resolvers/accounts-organizations.resolver.ts @@ -0,0 +1,12 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { + AuthService, + InseAccountManagementModelOrganizationProfile, +} from '../api'; + +export const accountsOrganizationResolver: ResolveFn< + InseAccountManagementModelOrganizationProfile[] +> = (route, state) => { + return inject(AuthService).listAccountOrganizations(); +}; diff --git a/webapp/src/app/resolvers/accounts-page.resolver.ts b/webapp/src/app/resolvers/accounts-page.resolver.ts new file mode 100644 index 00000000..1d4be85d --- /dev/null +++ b/webapp/src/app/resolvers/accounts-page.resolver.ts @@ -0,0 +1,19 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { AccountPage, AuthService } from '../api'; + +export const accountsPageResolver: ResolveFn = (route, state) => { + const page = Number(route.queryParamMap.get('page') ?? '0'); + const size = Number(route.queryParamMap.get('size') ?? '10'); + const search = route.queryParamMap.get('search') || undefined; + const organizationId = + route.queryParamMap.get('organization_id') || undefined; + + return inject(AuthService).listAccounts( + page, + size, + undefined, + search, + organizationId, + ); +}; diff --git a/webapp/src/app/resolvers/organizations-organizations.resolver.ts b/webapp/src/app/resolvers/organizations-organizations.resolver.ts new file mode 100644 index 00000000..c1db1abd --- /dev/null +++ b/webapp/src/app/resolvers/organizations-organizations.resolver.ts @@ -0,0 +1,13 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { OrganizationPage, OrganizationService } from '../api'; + +export const organizationsOrganizationsResolver: ResolveFn = ( + route, + state, +) => { + const page = Number(route.queryParamMap.get('page') ?? '0'); + const size = Number(route.queryParamMap.get('size') ?? '10'); + + return inject(OrganizationService).getOrganisations(page, size); +}; diff --git a/webapp/src/app/shared/guards/account-viewer.guard.ts b/webapp/src/app/shared/guards/account-viewer.guard.ts new file mode 100644 index 00000000..9eeac48d --- /dev/null +++ b/webapp/src/app/shared/guards/account-viewer.guard.ts @@ -0,0 +1,41 @@ +import { effect, inject, Injector } from '@angular/core'; +import { CanActivateFn, Router } from '@angular/router'; +import { CredentialService } from '../services/credential.service'; + +export const accountViewerGuard: CanActivateFn = () => { + const credentialService = inject(CredentialService); + const router = inject(Router); + const injector = inject(Injector); + + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } + + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + const mayViewAccounts = + credentialService.isEffectiveSuperAdmin() || + credentialService.isEffectiveAdmin() || + credentialService.isEffectiveManager(); + + if (!mayViewAccounts) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); +}; diff --git a/webapp/src/app/shared/guards/admin.guard.ts b/webapp/src/app/shared/guards/admin.guard.ts index 55e18ca8..a8876ced 100644 --- a/webapp/src/app/shared/guards/admin.guard.ts +++ b/webapp/src/app/shared/guards/admin.guard.ts @@ -1,35 +1,36 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const adminGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - switchMap(() => { - if ( - !credentialService.isEffectiveSuperAdmin() && - !credentialService.isEffectiveAdmin() - ) { - void router.navigate(['/dashboard']); - return of(false); - } + ref.destroy(); - return of(true); - }), - catchError(() => of(false)), - ); - }), - ); + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + if (!credentialService.isEffectiveAdmin()) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/super-admin.guard.ts b/webapp/src/app/shared/guards/super-admin.guard.ts index b1936483..993f00a5 100644 --- a/webapp/src/app/shared/guards/super-admin.guard.ts +++ b/webapp/src/app/shared/guards/super-admin.guard.ts @@ -1,31 +1,36 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const superAdminGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - switchMap(() => { - if (!credentialService.isEffectiveSuperAdmin()) { - void router.navigate(['/dashboard']); - return of(false); - } - return of(true); - }), - catchError(() => of(false)), - ); - }), - ); + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + if (!credentialService.isEffectiveSuperAdmin()) { + void router.navigate(['/dashboard']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/guards/user.guard.ts b/webapp/src/app/shared/guards/user.guard.ts index 190780ae..7145e5ea 100644 --- a/webapp/src/app/shared/guards/user.guard.ts +++ b/webapp/src/app/shared/guards/user.guard.ts @@ -1,25 +1,30 @@ -import { inject } from '@angular/core'; +import { effect, inject, Injector } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; -import { catchError, filter, map, of, switchMap, take } from 'rxjs'; import { CredentialService } from '../services/credential.service'; export const userGuard: CanActivateFn = () => { const credentialService = inject(CredentialService); const router = inject(Router); + const injector = inject(Injector); - return credentialService.validating.pipe( - filter((validating) => !validating), - take(1), - switchMap(() => { - if (!credentialService.isAuthenticated.value) { - void router.navigate(['/login']); - return of(false); - } + return new Promise((resolve) => { + const ref = effect( + () => { + if (credentialService.isValidating()) { + return; + } - return credentialService.validateCurrentSession().pipe( - map(() => true), - catchError(() => of(false)), - ); - }), - ); + ref.destroy(); + + if (!credentialService.isAuthenticated()) { + void router.navigate(['/login']); + resolve(false); + return; + } + + resolve(true); + }, + { injector }, + ); + }); }; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 130e6c94..08113260 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -1,86 +1,104 @@ -import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; +import { + HttpErrorResponse, + HttpInterceptorFn, + HttpRequest, +} from '@angular/common/http'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; -import { MatSnackBar } from '@angular/material/snack-bar'; -import { catchError, switchMap, tap, throwError } from 'rxjs'; -import { CredentialService } from '../services/credential.service'; -import { UiFocusService } from '../services/ui-focus.service'; +import { catchError, switchMap, throwError } from 'rxjs'; +import { + CredentialService, + clearStoredAuthState, + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE, +} from '../services/credential.service'; -export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { - const url = req.url.split('?')[0]; - const uiFocusService = inject(UiFocusService); +const attachBearer = ( + req: HttpRequest, + token: string, +): HttpRequest => { + if (!token) { + return req; + } + return req.clone({ + headers: req.headers.set('Authorization', 'Bearer ' + token), + }); +}; - const isPublicAuthRequest = - req.method === 'POST' && - (url.endsWith('/api/auth/v2/request-otk') || - url.endsWith('/api/auth/v2/login') || - url.endsWith('/api/auth/v2/access') || - url.endsWith('/api/auth/v2/refresh')); - - if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) { - return next(req); +const handleAccessTokenError = ( + error: unknown, + req: HttpRequest, + next: Parameters[1], + credentialService: CredentialService, + router: Router, +) => { + if (!(error instanceof HttpErrorResponse) || error.status !== 401) { + return throwError(() => error); } - const credentialService = inject(CredentialService); - const router = inject(Router); - const snackBar = inject(MatSnackBar); - const tokenProvider = credentialService.getBearerToken(); - const isLogoutRequest = url.endsWith('/api/auth/v2/logout'); + if (!credentialService.getRawAccessToken()) { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError(() => error); + } - return tokenProvider.pipe( - switchMap((response) => { - if (response == undefined) { - credentialService.clearLocalAuthState(); - - snackBar.open( - 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/login']); - - return throwError( - () => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), - ); - } - - const authorizedRequest = req.clone({ - headers: req.headers.set('Authorization', 'Bearer ' + response), - }); - - return next(authorizedRequest).pipe( - catchError((error: HttpErrorResponse) => { - if (error.status === 401 && !isLogoutRequest) { - return credentialService.handleUnauthorized().pipe( - tap((result) => { - uiFocusService.blurActiveElement(); - - if (result === 'stopped-impersonating') { - snackBar.open( - 'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/accounts']); - } else if (result === 'logged-out') { - snackBar.open( - 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', - 'OK', - { duration: 7000 }, - ); - - void router.navigate(['/login']); - } - }), - switchMap(() => throwError(() => error)), - ); - } - - return throwError(() => error); - }), - ); + return credentialService.refreshAccessToken().pipe( + switchMap((accessToken) => next(attachBearer(req, accessToken.raw_token))), + catchError((refreshError) => { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError(() => refreshError); }), ); }; + +export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { + const router = inject(Router); + + const requiredType = req.context.get(REQUIRED_TOKEN_TYPE); + + if (requiredType === TOKEN_TYPE.NONE) { + return next(req); + } + + if (requiredType === TOKEN_TYPE.ID_TOKEN_COOKIE) { + return next(req.clone({ withCredentials: true })).pipe( + catchError((err) => { + if (err instanceof HttpErrorResponse && err.status === 401) { + clearStoredAuthState(); + router.navigate(['/login'], { replaceUrl: true }); + } + return throwError(() => err); + }), + ); + } + + if (requiredType === TOKEN_TYPE.REFRESH_TOKEN_COOKIE) { + return next(req.clone({ withCredentials: true })); + } + + const credentialService = inject(CredentialService); + + const rawAccessToken = credentialService.getRawAccessToken(); + + if (rawAccessToken && credentialService.accessTokenIsExpired()) { + return credentialService.refreshAccessToken().pipe( + switchMap((accessToken) => + next(attachBearer(req, accessToken.raw_token)), + ), + catchError(() => { + credentialService.logout(); + router.navigate(['/login'], { replaceUrl: true }); + return throwError( + () => new Error('Sitzung abgelaufen. Bitte erneut anmelden.'), + ); + }), + ); + } + + return next(rawAccessToken ? attachBearer(req, rawAccessToken) : req).pipe( + catchError((err) => + handleAccessTokenError(err, req, next, credentialService, router), + ), + ); +}; diff --git a/webapp/src/app/shared/pipes/status.pipe.ts b/webapp/src/app/shared/pipes/status.pipe.ts new file mode 100644 index 00000000..5ba35960 --- /dev/null +++ b/webapp/src/app/shared/pipes/status.pipe.ts @@ -0,0 +1,18 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({ + name: 'status', +}) +export class StatusPipe implements PipeTransform { + transform(value: string, ...args: unknown[]): string { + value = value?.toUpperCase() ?? ''; + switch (value) { + case 'ACTIVE': + return 'Aktiv'; + case 'INACTIVE': + return 'Inaktiv'; + default: + return value; + } + } +} diff --git a/webapp/src/app/shared/services/account-management.service.ts b/webapp/src/app/shared/services/account-management.service.ts deleted file mode 100644 index 2791c921..00000000 --- a/webapp/src/app/shared/services/account-management.service.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { HttpClient, HttpParams } from '@angular/common/http'; -import { Injectable, inject } from '@angular/core'; -import { Observable } from 'rxjs'; -import { Configuration } from '../../api'; - -export type AccountRole = 'SUPER_ADMIN' | 'ADMIN' | 'MANAGER' | 'USER'; - -export interface AccountProfile { - id: string; - email: string; - name: string; - role: AccountRole; - organization_id: string; - organization_name: string; - deleted: boolean; - is_current: boolean; - is_real_account: boolean; - is_impersonating: boolean; -} - -export interface AccountPage { - items: AccountProfile[]; - total: number; - page: number; - page_size: number; -} - -export interface OrganizationProfile { - id: string; - name: string; - openalex_institution_id?: string | null; -} - -export interface AccountPayload { - email?: string; - name?: string; - role?: AccountRole; - organization_id?: string; - password?: string; - deleted?: boolean; -} - -export interface CreateAccountPayload { - email: string; - name: string; - role: AccountRole; - organization_id: string; - password: string; -} - -@Injectable({ - providedIn: 'root', -}) -export class AccountManagementService { - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - - getCurrentAccount(): Observable { - return this.httpClient.get( - `${this.apiBasePath}/api/accounts/me`, - ); - } - - listAccounts(options: { - page: number; - pageSize: number; - search?: string; - organizationId?: string; - }): Observable { - let params = new HttpParams() - .set('page', options.page) - .set('page_size', options.pageSize); - - if (options.search) { - params = params.set('search', options.search); - } - - if (options.organizationId) { - params = params.set('organization_id', options.organizationId); - } - - return this.httpClient.get( - `${this.apiBasePath}/api/accounts`, - { - params, - }, - ); - } - - createAccount(payload: CreateAccountPayload): Observable { - return this.httpClient.post( - `${this.apiBasePath}/api/accounts`, - payload, - ); - } - - updateAccount( - accountId: string, - payload: AccountPayload, - ): Observable { - return this.httpClient.put( - `${this.apiBasePath}/api/accounts/${accountId}`, - payload, - ); - } - - deleteAccount(accountId: string): Observable { - return this.httpClient.delete( - `${this.apiBasePath}/api/accounts/${accountId}`, - ); - } - - listOrganizations(): Observable { - return this.httpClient.get( - `${this.apiBasePath}/api/accounts/organizations`, - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } -} diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index 8e72953f..e70311a2 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -1,55 +1,87 @@ -import { Injectable, computed, inject, signal } from '@angular/core'; -import { filter, take, map, catchError, finalize } from 'rxjs/operators'; +import { Injectable, computed, effect, inject, signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; import { - BehaviorSubject, + catchError, + finalize, + firstValueFrom, + map, Observable, of, + shareReplay, switchMap, tap, throwError, } from 'rxjs'; import { AccessResponse, - AccessToken, AuthService, - Configuration, - IdToken, - LoginResponse, AccountProfile, + OtkResponse, + IdTokenMetadata, + AccessToken, + LoginResponse, } from '../../api'; -import { HttpClient, HttpHeaders } from '@angular/common/http'; -type LogoutResult = 'logged-out' | 'stopped-impersonating'; -type UnauthorizedRecoveryResult = - | 'logged-out' - | 'stopped-impersonating' - | 'already-handling'; +import { Router } from '@angular/router'; +import { HttpContext, HttpContextToken } from '@angular/common/http'; + +export const TOKEN_TYPE = { + ACCESS_TOKEN: 'ACCESS_TOKEN', + ID_TOKEN_COOKIE: 'ID_TOKEN_COOKIE', + REFRESH_TOKEN_COOKIE: 'REFRESH_TOKEN_COOKIE', + NONE: 'NONE', +} as const; + +export type TokenContextType = (typeof TOKEN_TYPE)[keyof typeof TOKEN_TYPE]; + +export const REQUIRED_TOKEN_TYPE = new HttpContextToken( + () => TOKEN_TYPE.ACCESS_TOKEN, +); + +const STORAGE_KEY = 'auth_state'; + +export const clearStoredAuthState = (): void => { + localStorage.removeItem(STORAGE_KEY); +}; + +export interface StoredAuthState { + idTokenMetadata: IdTokenMetadata | null; + accessToken: AccessToken | null; +} + +const EXPIRY_SKEW_MS = 10 * 1000; // 10 seconds @Injectable({ providedIn: 'root', }) export class CredentialService { private readonly authService = inject(AuthService); - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - private handlingUnauthorized = false; - private static readonly KEY_GRANT = 'grant'; - - public readonly validating = new BehaviorSubject(false); - public readonly isAuthenticated = new BehaviorSubject(false); + public readonly isValidating = signal(false); + public readonly isAuthenticated = computed( + () => this.accessToken() !== undefined, + ); public readonly isEffectiveSuperAdmin = computed( () => this.accessToken()?.effective_role === 'SUPER_ADMIN', ); public readonly isEffectiveAdmin = computed( - () => this.accessToken()?.effective_role === 'ADMIN', + () => + this.accessToken()?.effective_role === 'ADMIN' || + this.isEffectiveSuperAdmin(), + ); + public readonly isEffectiveManager = computed( + () => this.accessToken()?.effective_role === 'MANAGER', ); public readonly effectiveOrganizationId = computed( () => this.accessToken()?.effective_organization_id, ); - public readonly login = new BehaviorSubject(''); - public readonly email = new BehaviorSubject(''); - public readonly organizationName = new BehaviorSubject(''); + public readonly login = computed( + () => this.accountProfile()?.name ?? this.accountProfile()?.email ?? '', + ); + public readonly email = computed(() => this.accountProfile()?.email ?? ''); + public readonly organizationName = computed( + () => this.accountProfile()?.organization_name ?? '', + ); public readonly realAccountId = computed( () => this.accessToken()?.real_account_id ?? '', @@ -61,292 +93,283 @@ export class CredentialService { () => this.realAccountId() !== this.effectiveAccountId(), ); - private readonly identityToken = signal(undefined); - private readonly accessToken = signal(undefined); + public readonly accessToken = signal(undefined); + + public readonly isActiveAccessToken = computed(() => { + const accessToken = this.accessToken(); + return ( + accessToken !== undefined && + new Date(accessToken.expires_at).getTime() >= Date.now() + ); + }); + + public readonly accountProfile = toSignal( + toObservable(this.accessToken).pipe( + switchMap((accessToken) => + accessToken + ? this.authService.getCurrentAccount() + : of(undefined), + ), + ), + { initialValue: undefined }, + ); + + private refreshInFlight$: Observable | null = null; private request = 0; - constructor() { - const data = localStorage.getItem(CredentialService.KEY_GRANT); - const id = data ? (JSON.parse(data) as AccessToken) : undefined; - if (id && new Date(id.expires_at).getTime() >= Date.now()) { - this.identityToken.set(id); - this.validating.next(true); - setTimeout(() => this.refreshAccessToken(id), 0); + constructor(private readonly router: Router) { + this.restoreAuthState(); + + effect(() => { + console.log('Access token changed:', this.accessToken()); + }); + + const storedAccessToken = this.getStoredAccessToken(); + if (storedAccessToken && this.isExpired(storedAccessToken)) { + this.refreshAccessToken().subscribe({ + error: (err) => { + console.error('Error refreshing access token on init:', err); + this.logout(); + this.router.navigate(['/login'], { replaceUrl: true }); + }, + }); } } - public validateCurrentSession(): Observable { - return this.loadCurrentProfile(); + private restoreAuthState(): void { + this.accessToken.set(this.getStoredAccessToken() ?? undefined); } - public requestOtk(email: string, password: string): Observable { - const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); - this.identityToken.set(undefined); + private readAuthState(): StoredAuthState { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) { + return { idTokenMetadata: null, accessToken: null }; + } + try { + return JSON.parse(raw) as StoredAuthState; + } catch { + return { idTokenMetadata: null, accessToken: null }; + } + } + + private writeAuthState(patch: Partial): void { + const next: StoredAuthState = { + ...this.readAuthState(), + ...patch, + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); + } + + private persistAccessToken(accessToken: AccessToken | null): void { + this.writeAuthState({ accessToken }); + this.accessToken.set(accessToken ?? undefined); + } + + private getStoredIdTokenMetadata(): IdTokenMetadata | null { + return this.readAuthState().idTokenMetadata; + } + + private getStoredAccessToken(): AccessToken | null { + return this.readAuthState().accessToken; + } + + private isExpired(token: { expires_at: string }): boolean { + return new Date(token.expires_at).getTime() < Date.now() + EXPIRY_SKEW_MS; + } + + public accessTokenIsExpired(): boolean { + const accessToken = this.getStoredAccessToken(); + return !accessToken || this.isExpired(accessToken); + } + + public logout() { + clearStoredAuthState(); this.accessToken.set(undefined); + this.refreshInFlight$ = null; + } - return this.authService - .requestOtk({ email: email.trim().toLowerCase(), password }) - .pipe( - map((response: { account_id?: string }) => { - if (this.request !== request) { - return ''; - } - - return response.account_id ?? ''; - }), - finalize(() => { - if (this.request === request) { - this.validating.next(false); - } - }), - ); + public requestOtk(email: string, password: string): Observable { + return this.authService.requestOtk( + { + email: email.trim(), + password: password.trim(), + }, + undefined, + undefined, + { context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE) }, + ); } public loginWithOtk( accountId: string, - email: string, emailCode: string, - ): Observable { - const request = ++this.request; - this.validating.next(true); - this.isAuthenticated.next(false); - + ): Observable { return this.authService - .login({ account_id: accountId, email_code: emailCode.trim() }) + .login( + { + account_id: accountId, + email_code: emailCode.trim(), + }, + undefined, + undefined, + { + context: new HttpContext().set(REQUIRED_TOKEN_TYPE, TOKEN_TYPE.NONE), + }, + ) .pipe( - switchMap((response: LoginResponse) => { - if (this.request != request) return of(undefined); - - const idToken = response.id_token; - - this.identityToken.set(idToken); - localStorage.setItem( - CredentialService.KEY_GRANT, - JSON.stringify(idToken), - ); - return this.getAccessGrantForIdentity(idToken, request); - }), + tap(({ id_token }) => + this.writeAuthState({ idTokenMetadata: id_token }), + ), ); } - public refreshAccessToken(identityToken: IdToken) { - const request = ++this.request; - this.validating.next(true); - this.accessToken.set(undefined); - this.getAccessGrantForIdentity(identityToken, request).subscribe({ - error: () => { - if (this.request != request) return; - this.clearLocalAuthState(); - }, - }); - } - - public impersonateAccount(accountId: string): Observable { - const idToken = this.identityToken(); - - if (!idToken) { - return throwError(() => new Error('No identity token available.')); - } - - const request = ++this.request; - this.validating.next(true); - this.accessToken.set(undefined); - return this.getAccessGrantForIdentity(idToken, request, accountId).pipe( - tap({ error: () => this.validating.next(false) }), - ); - } - - public stopImpersonating(): Observable { - const idToken = this.identityToken(); - - if (!idToken) { - return throwError(() => new Error('No identity token available.')); - } - - const request = ++this.request; - this.validating.next(true); - this.accessToken.set(undefined); - return this.getAccessGrantForIdentity(idToken, request).pipe( - tap({ error: () => this.validating.next(false) }), - ); - } - - public logoutAccount(): Observable { - const wasImpersonating = this.isImpersonating(); - + public requestAccess( + realAccountId: string, + effectiveAccountId?: string, + ): Observable { return this.authService - .logout('body', false, { transferCache: false }) + .getAccessToken( + { + real_account_id: realAccountId, + effective_account_id: effectiveAccountId ?? realAccountId, + }, + undefined, + 'body', + undefined, + { + context: new HttpContext().set( + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE.ID_TOKEN_COOKIE, + ), + }, + ) .pipe( - catchError((error) => { - console.error('Backend logout failed', error); - return of(null); - }), - switchMap(() => { - if (!wasImpersonating) { - this.clearLocalAuthState(); - return of('logged-out' as const); - } - - return this.stopImpersonating().pipe( - map(() => 'stopped-impersonating' as const), - catchError((error) => { - console.error('Stop impersonating after logout failed', error); - this.clearLocalAuthState(); - return of('logged-out' as const); - }), - ); + tap(({ access_token }) => { + this.persistAccessToken(access_token); }), ); } - public clearLocalAuthState(): void { - this.request += 1; - localStorage.removeItem(CredentialService.KEY_GRANT); - this.identityToken.set(undefined); - this.accessToken.set(undefined); - this.isAuthenticated.next(false); - this.validating.next(false); - this.login.next(''); - this.email.next(''); - this.organizationName.next(''); - } - - public handleUnauthorized(): Observable { - if (this.handlingUnauthorized) { - return of('already-handling' as const); - } - - this.handlingUnauthorized = true; - - const isImpersonating = this.isImpersonating(); - const identityToken = this.identityToken(); - - const recovery$ = - isImpersonating && identityToken - ? this.stopImpersonating().pipe( - map(() => 'stopped-impersonating' as const), - catchError((error) => { - console.error('Failed to stop impersonation after 401', error); - this.clearLocalAuthState(); - return of('logged-out' as const); - }), - ) - : of(null).pipe( - tap(() => this.clearLocalAuthState()), - map(() => 'logged-out' as const), - ); - - return recovery$.pipe( - finalize(() => { - this.handlingUnauthorized = false; - }), - ); - } - public changePassword( currentPassword: string, newPassword: string, ): Observable { - return this.httpClient - .post( - `${this.apiBasePath}/api/auth/v2/change-password`, - { - current_password: currentPassword, - new_password: newPassword, - }, - { withCredentials: true }, - ) + this.isValidating.set(true); + return this.authService + .changePassword({ + current_password: currentPassword, + new_password: newPassword, + }) .pipe( - tap(() => this.clearLocalAuthState()), - map(() => undefined), + tap(() => this.isValidating.set(false)), + catchError((err) => { + this.isValidating.set(false); + return throwError(() => err); + }), ); } + public refreshAccessToken(): Observable { + if (this.refreshInFlight$) { + return this.refreshInFlight$; + } + + this.refreshInFlight$ = this.authService + .refreshAccessToken(undefined, 'body', undefined, { + context: new HttpContext().set( + REQUIRED_TOKEN_TYPE, + TOKEN_TYPE.REFRESH_TOKEN_COOKIE, // 'REFRESH_TOKEN_COOKIE' and NOT 'REFRESH_COOKIE', + 30 Minutes debugging this shit, changed to types + ), + }) + .pipe( + tap((accessToken) => { + this.persistAccessToken(accessToken); + }), + catchError(() => this.reauthenticateViaIdToken()), + finalize(() => { + this.refreshInFlight$ = null; + }), + shareReplay(1), + ); + + return this.refreshInFlight$; + } + + reauthenticateViaIdToken(): Observable { + const idTokenMetadata = this.getStoredIdTokenMetadata(); + + if (!idTokenMetadata || this.isExpired(idTokenMetadata)) { + this.logout(); + return throwError( + () => new Error('No valid ID token metadata available.'), + ); + } + + return this.requestAccess( + idTokenMetadata.real_account_id, + idTokenMetadata.real_account_id, + ).pipe( + map(({ access_token }) => access_token), + catchError((err) => { + console.error('Error reauthenticating via ID token:', err); + this.logout(); + return throwError(() => err); + }), + ); + } + + public getRawAccessToken(): string | undefined { + return this.getStoredAccessToken()?.raw_token; + } + + public async impersonateAccount(effectiveAccountId: string): Promise { + const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id; + if (!realAccountId) { + throw new Error('No real account ID available.'); + } + + const request = ++this.request; + this.isValidating.set(true); + + try { + await firstValueFrom( + this.requestAccess(realAccountId, effectiveAccountId), + ); + } finally { + if (request === this.request) { + this.isValidating.set(false); + } + } + } + + public async stopImpersonating(): Promise { + this.isValidating.set(true); + + const realAccountId = this.getStoredIdTokenMetadata()?.real_account_id; + if (!realAccountId) { + throw new Error('No real account ID available.'); + } + + try { + await firstValueFrom(this.requestAccess(realAccountId, realAccountId)); + } finally { + this.isValidating.set(false); + } + } + + public async logoutAccount(): Promise { + try { + await firstValueFrom(this.authService.logout()); + } catch (err) { + console.error('Error logging out on the server:', err); + } finally { + this.logout(); + await this.router.navigate(['/login'], { replaceUrl: true }); + } + } + public registerAccount(_data: unknown): Observable { return throwError(() => new Error('Registration is temporarily disabled.')); } - - //review: arman (generated fix) - public getBearerToken(): Observable { - const accessToken = this.accessToken(); - const identityToken = this.identityToken(); - - // 1. If we have a valid access token, return it immediately and complete. - if ( - accessToken && - Date.now() < new Date(accessToken.expires_at).getTime() - ) { - return of(accessToken.raw_token); - } - - // 2. If we don't have a token, and we ARE NOT currently validating, trigger a refresh. - if (!this.validating.value) { - if (!identityToken) { - return of(undefined); // No identity token to refresh with. - } - this.refreshAccessToken(identityToken); - } - - // 3. Wait for the validation to finish, then return the resulting token. - return this.validating.pipe( - filter((isValidating) => !isValidating), // Wait until validating becomes false - take(1), // Take exactly 1 emission and then automatically complete() - map(() => this.accessToken()?.raw_token), - ); - } - - private getAccessGrantForIdentity( - idToken: IdToken, - request: number, - effectiveAccountId?: string, - ): Observable { - const realAccountId = idToken.real_account_id; - const headers = new HttpHeaders({ - Authorization: `Bearer ${idToken.raw_token}`, - }); - const payload = { - real_account_id: realAccountId, - effective_account_id: effectiveAccountId ?? realAccountId, - }; - - return this.httpClient - .post(`${this.apiBasePath}/api/auth/v2/access`, payload, { - headers, - withCredentials: true, - }) - .pipe( - tap((result: AccessResponse) => { - if (this.request != request) return; - - const accessToken = result.access_token; - - this.accessToken.set(accessToken); - this.isAuthenticated.next(true); - this.validating.next(false); - }), - map(() => undefined), - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } - - private loadCurrentProfile(): Observable { - return this.httpClient - .get(`${this.apiBasePath}/api/accounts/me`, { - withCredentials: true, - }) - .pipe( - tap((profile) => { - this.login.next(profile.name ?? profile.email ?? ''); - this.email.next(profile.email ?? ''); - this.organizationName.next(profile.organization_name ?? ''); - }), - map(() => undefined), - ); - } } diff --git a/webapp/src/app/shared/services/organization-management.service.ts b/webapp/src/app/shared/services/organization-management.service.ts deleted file mode 100644 index e022b4c9..00000000 --- a/webapp/src/app/shared/services/organization-management.service.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { HttpClient, HttpParams } from '@angular/common/http'; -import { Injectable, inject } from '@angular/core'; -import { Observable } from 'rxjs'; -import { Configuration } from '../../api'; - -export interface OrganizationProfile { - id: string; - name: string; - other_inst_id?: string | null; - deleted: boolean; - member_count: number; -} - -export interface OrganizationPage { - items: OrganizationProfile[]; - total: number; - page: number; - page_size: number; -} - -export interface CreateOrganizationPayload { - name: string; - other_inst_id?: string | null; -} - -export interface UpdateOrganizationPayload { - name?: string; - other_inst_id?: string | null; - deleted?: boolean; -} - -@Injectable({ providedIn: 'root' }) -export class OrganizationManagementService { - private readonly httpClient = inject(HttpClient); - private readonly apiConfiguration = inject(Configuration, { optional: true }); - - getOrganizations( - page: number, - pageSize: number, - ): Observable { - const params = new HttpParams() - .set('page', page) - .set('page_size', pageSize); - return this.httpClient.get( - `${this.apiBasePath}/api/organizations`, - { params }, - ); - } - - createOrganization( - payload: CreateOrganizationPayload, - ): Observable { - return this.httpClient.post( - `${this.apiBasePath}/api/organizations`, - payload, - ); - } - - updateOrganization( - organizationId: string, - payload: UpdateOrganizationPayload, - ): Observable { - return this.httpClient.put( - `${this.apiBasePath}/api/organizations/${organizationId}`, - payload, - ); - } - - deleteOrganization(organizationId: string): Observable { - return this.httpClient.delete( - `${this.apiBasePath}/api/organizations/${organizationId}`, - ); - } - - private get apiBasePath(): string { - return this.apiConfiguration?.basePath ?? ''; - } -} diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index f4ae841c..7be187a0 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -3,7 +3,7 @@ - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { } - @if (credentialService.isAuthenticated | async) { + @if (credentialService.isAuthenticated()) { @if (credentialService.isImpersonating()) {
switch_account diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 127f842d..abd2f2ec 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -102,22 +102,20 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.mediaQuery.removeEventListener('change', this.mediaQueryListener); } - logout() { - this.credentialService.logoutAccount().subscribe({ - next: (result) => { - if (result === 'stopped-impersonating') { - this.router.navigate(['/accounts']); - } else { - this.router.navigate(['/login']); - } - }, - }); + async logout() { + const isImpersonating = this.credentialService.isImpersonating(); + + if (isImpersonating) { + await this.credentialService.stopImpersonating(); + this.router.navigate(['/accounts']); + } else { + await this.credentialService.logoutAccount(); + } } - stopImpersonating(): void { - this.credentialService.stopImpersonating().subscribe({ - next: () => this.router.navigate(['/accounts']), - }); + async stopImpersonating(): Promise { + await this.credentialService.stopImpersonating(); + this.router.navigate(['/accounts']); } navigateBack() { diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.html b/webapp/src/app/shared/ui/app-menu/app-menu.component.html index b80e7271..5b913d11 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.html +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.html @@ -48,7 +48,11 @@ credentialService.isEffectiveSuperAdmin() || credentialService.isEffectiveAdmin()) && (!itemGroup.superAdminOnly || - credentialService.isEffectiveSuperAdmin()) + credentialService.isEffectiveSuperAdmin()) && + (!itemGroup.managerOrAdminOnly || + credentialService.isEffectiveSuperAdmin() || + credentialService.isEffectiveAdmin() || + credentialService.isEffectiveManager()) ) { @if (!collapsed()) { @@ -101,13 +105,13 @@ } @else { @@ -115,13 +119,11 @@ diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.scss b/webapp/src/app/shared/ui/app-menu/app-menu.component.scss index e071706f..eb3fb876 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.scss +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.scss @@ -1,5 +1,4 @@ @use '@angular/material' as mat; -@import '../../../../m3-theme.scss'; .sidebar { display: flex; diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 96f2bd12..f39ff565 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -19,6 +19,7 @@ type NavItem = { queryParams?: Record; adminOnly?: boolean; superAdminOnly?: boolean; + managerOrAdminOnly?: boolean; }; type NavItemGroup = { @@ -26,6 +27,7 @@ type NavItemGroup = { items: NavItem[]; adminOnly?: boolean; superAdminOnly?: boolean; + managerOrAdminOnly?: boolean; }; @Component({ @@ -68,7 +70,7 @@ export class AppMenuComponent { icon: 'groups', route: '/persons', queryParams: { - institutionName: this.credentialService.organizationName.value, + institutionName: this.credentialService.organizationName(), }, disabled: false, }, @@ -111,12 +113,21 @@ export class AppMenuComponent { route: '/patents', disabled: false, }, + { + label: 'Keywords', + icon: 'join_left', + route: '/keywords', + disabled: false, + queryParams: { + mode: 'url', + }, + }, { label: 'Accounts', icon: 'manage_accounts', route: '/accounts', disabled: false, - adminOnly: true, + managerOrAdminOnly: true, }, { label: 'Organisationen', @@ -130,15 +141,17 @@ export class AppMenuComponent { { label: 'Navigation', items: this.navItems.filter( - (item) => !item.adminOnly && !item.superAdminOnly, + (item) => + !item.adminOnly && !item.superAdminOnly && !item.managerOrAdminOnly, ), }, { label: 'Administration', items: this.navItems.filter( - (item) => item.adminOnly && !item.superAdminOnly, + (item) => + (item.adminOnly || item.managerOrAdminOnly) && !item.superAdminOnly, ), - adminOnly: true, + managerOrAdminOnly: true, }, { label: 'Super Administration', @@ -166,15 +179,7 @@ export class AppMenuComponent { }); dialogRef.componentInstance.confirmDelete.subscribe(() => { - this.credentialService.logoutAccount().subscribe({ - next: (result) => { - if (result === 'stopped-impersonating') { - this.router.navigate(['/accounts']); - } else { - this.router.navigate(['/login']); - } - }, - }); + void this.credentialService.logoutAccount(); }); } } diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html index 0f6dcd9b..2ce167fe 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html @@ -1,5 +1,12 @@ - + + @for (option of _options(); track $index) { + {{ option.display_name }} + } + + diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts index caa3f7bf..2b51fdd4 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.ts @@ -1,6 +1,7 @@ import { Component, computed, inject, input, output } from '@angular/core'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { FormsModule } from '@angular/forms'; +import { MatSelectChange, MatSelectModule } from '@angular/material/select'; import { ActivatedRoute, Router } from '@angular/router'; export type SelectorOption = { @@ -10,14 +11,30 @@ export type SelectorOption = { @Component({ selector: 'app-query-param-selector', - imports: [FormsModule], + imports: [FormsModule, MatSelectModule], templateUrl: './query-param-selector.component.html', styleUrl: './query-param-selector.component.scss', }) export class QueryParamSelectorComponent { options = input.required(); queryParamKey = input.required(); - handleSelectionChange = output(); + handleSelectionChange = output(); + allowEmptyValue = input(false); + label = input(''); + + _options = computed(() => { + const options = this.options(); + + if (!options) { + return []; + } + + if (this.allowEmptyValue()) { + return [{ value: '', display_name: '' }, ...options]; + } + + return options; + }); private readonly activatedRoute = inject(ActivatedRoute); private readonly router = inject(Router); @@ -33,8 +50,8 @@ export class QueryParamSelectorComponent { return params && key ? params[key] || '' : ''; }); - _handleSelectionChange(event: Event): void { - const newValue = (event.target as HTMLSelectElement).value; + _handleSelectionChange(event: MatSelectChange): void { + const newValue = event.value; this.router.navigate([], { queryParams: { [this.queryParamKey()]: newValue }, diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html new file mode 100644 index 00000000..e7a2f20f --- /dev/null +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html @@ -0,0 +1,59 @@ +
+ + {{ label() }} + + + @if (searchControl.value.trim()) { + + } + + @if (searchControl.value) { + + } + + + @if (loading()) { + + + Lade Themen... + + } + + @for (topic of topics(); track topic) { + {{ topic }} + } + + @if ( + !loading() && + searchControl.value.trim().length >= minCharacters() && + topics().length === 0 + ) { + Keine passenden Themen gefunden. + } + + +
diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss new file mode 100644 index 00000000..e8769993 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss @@ -0,0 +1,16 @@ +:host { + width: 100%; +} + +.topic-autocomplete { + width: 100%; +} + +mat-form-field { + width: 100%; +} + +.topic-field { + width: 100%; + min-width: 320px; +} diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts new file mode 100644 index 00000000..6b14edd7 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.ts @@ -0,0 +1,123 @@ +import { CommonModule } from '@angular/common'; +import { Component, DestroyRef, input, output, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { TopicsService } from '../../../api/api/topics.service'; +import { EventEmitter } from '@angular/core'; +import { + catchError, + debounceTime, + distinctUntilChanged, + finalize, + map, + of, + switchMap, +} from 'rxjs'; + +@Component({ + selector: 'app-topic-autocomplete', + standalone: true, + imports: [ + CommonModule, + ReactiveFormsModule, + MatAutocompleteModule, + MatButtonModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressSpinnerModule, + ], + templateUrl: './topic-autocomplete.component.html', + styleUrl: './topic-autocomplete.component.scss', +}) +export class TopicAutocompleteComponent { + readonly label = input('Thema'); + readonly placeholder = input('Thema suchen oder eintippen...'); + readonly minCharacters = input(2); + readonly limit = input(12); + + readonly topicSelected = output(); + + readonly searchControl = new FormControl('', { nonNullable: true }); + readonly topics = signal([]); + readonly loading = signal(false); + + constructor( + private readonly topicsService: TopicsService, + private readonly destroyRef: DestroyRef, + ) { + this.searchControl.valueChanges + .pipe( + debounceTime(250), + distinctUntilChanged(), + switchMap((query) => { + const normalizedQuery = query.trim(); + if (normalizedQuery.length < this.minCharacters()) { + this.loading.set(false); + return of([] as string[]); + } + + this.loading.set(true); + return this.topicsService + .autocompleteTopics( + normalizedQuery, + undefined, + undefined, + undefined, + this.limit(), + ) + .pipe( + map((response) => + Array.from( + new Set( + (response.results ?? []) + .map((topic) => topic.display_name?.trim() ?? '') + .filter((topic) => !!topic), + ), + ), + ), + catchError((error) => { + console.error( + 'Error fetching topic autocomplete options:', + error, + ); + return of([] as string[]); + }), + finalize(() => this.loading.set(false)), + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((topics) => { + this.topics.set(topics); + }); + } + + selectTopic(topic: string): void { + this.searchControl.setValue('', { emitEvent: false }); + this.topics.set([]); + this.topicSelected.emit(topic); + } + onKeydownTab(event: KeyboardEvent): void { + event.preventDefault(); + this.searchControl.setValue(this.topics()[0], { emitEvent: false }); + } + submitCurrentValue(): void { + const topic = this.searchControl.value.trim(); + if (!topic) return; + this.searchControl.setValue('', { emitEvent: false }); + this.topics.set([]); + this.topicSelected.emit(topic); + } + + clear(): void { + this.searchControl.setValue(''); + this.topics.set([]); + } +}