Compare commits
150
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f71a4b56c | ||
|
|
77c7eeef8b | ||
|
|
5b894d8927 | ||
|
|
b352e5288a | ||
|
|
7bbfe1761d | ||
|
|
09cb54109a | ||
|
|
010e1c7f21 | ||
|
|
d1802fa1f8 | ||
|
|
4d0a6db3c3 | ||
|
|
db604feb37 | ||
|
|
cd0e98ec5f | ||
|
|
42685ae44f | ||
|
|
9be024bb13 | ||
|
|
87b7e207e3 | ||
|
|
8eaa9c2420 | ||
|
|
87b02ed0a4 | ||
|
|
a6d30dd897 | ||
|
|
134055b8b9 | ||
|
|
be72d28bda | ||
|
|
2bfb877e77 | ||
|
|
48e33e7fe5 | ||
|
|
f469594c17 | ||
|
|
3e115619a6 | ||
|
|
13b2fb3350 | ||
|
|
d26ddb8cb4 | ||
|
|
a8e582cf23 | ||
|
|
940c050cd7 | ||
|
|
e470b65b5a | ||
|
|
383c77134a | ||
|
|
bb941361a1 | ||
|
|
5d22b201e9 | ||
|
|
1c6dbb540f | ||
|
|
cf9a5df4e9 | ||
|
|
213edf8a5f | ||
|
|
c277fcfece | ||
|
|
8efbbf1f1a | ||
|
|
9ad6d5cd8c | ||
|
|
77540e4002 | ||
|
|
fd3ceb54aa | ||
|
|
7baeab92c2 | ||
|
|
0c526be983 | ||
|
|
53f5440d01 | ||
|
|
e86a19f800 | ||
|
|
61fd920a9f | ||
|
|
7eed7e6614 | ||
|
|
e34e1fe3d5 | ||
|
|
2418821691 | ||
|
|
058c92227a | ||
|
|
bf38147acc | ||
|
|
3f23845c89 | ||
|
|
52e70a5b24 | ||
|
|
d502431102 | ||
|
|
3533b994d0 | ||
|
|
5d22f4831a | ||
|
|
8130192a44 | ||
|
|
bda7aff447 | ||
|
|
82421c1040 | ||
|
|
0723bb5c5b | ||
|
|
e4dbe07436 | ||
|
|
19c6574945 | ||
|
|
0b750d27e7 | ||
|
|
398ea7b56c | ||
|
|
0176eea873 | ||
|
|
b0e8c86743 | ||
|
|
03a2954c72 | ||
|
|
b9d382c78a | ||
|
|
78a8e5d919 | ||
|
|
f9f6a58ad5 | ||
|
|
5cc110174a | ||
|
|
c3ec93fba1 | ||
|
|
169b825195 | ||
|
|
0a3bf72e14 | ||
|
|
eb94fc5942 | ||
|
|
e868c4a47e | ||
|
|
1cf80ae074 | ||
|
|
c74d0b5b87 | ||
|
|
a69f014413 | ||
|
|
cabf819e94 | ||
|
|
c243088752 | ||
|
|
1dd032a66c | ||
|
|
9f03c92bc1 | ||
|
|
86bced4940 | ||
|
|
4461b26270 | ||
|
|
19fd2ac86d | ||
|
|
e9ba874103 | ||
|
|
dfb1413b05 | ||
|
|
b5d03c84c4 | ||
|
|
ef41c0ad96 | ||
|
|
a07fadc30e | ||
|
|
4bf351cf66 | ||
|
|
f55a37867c | ||
|
|
ae42bc46ed | ||
|
|
c38355c817 | ||
|
|
0c004f0cdf | ||
|
|
16c0b399c8 | ||
|
|
3867540a4c | ||
|
|
32cab01a8b | ||
|
|
2b606b8473 | ||
|
|
e0ac41da91 | ||
|
|
86bed62ac0 | ||
|
|
1eaf8f8c8f | ||
|
|
0c3db967b0 | ||
|
|
04eb0f0185 | ||
|
|
b2d965d604 | ||
|
|
0e80cc3fc3 | ||
|
|
92c4edfb4f | ||
|
|
79f2aa0263 | ||
|
|
5878edc4cd | ||
|
|
f4122263dd | ||
|
|
20faff13ec | ||
|
|
73315457a6 | ||
|
|
a464a95c4e | ||
|
|
2264582d1e | ||
|
|
2703f46575 | ||
|
|
e648ea1ec4 | ||
|
|
261f97eee0 | ||
|
|
f4b8d0884c | ||
|
|
1ddc5c42c5 | ||
|
|
47fb41105a | ||
|
|
4394ced772 | ||
|
|
15fc57da51 | ||
|
|
3c910fa0e4 | ||
|
|
8805ec9e57 | ||
|
|
7b4c459fd8 | ||
|
|
08824bd7ba | ||
|
|
1297f85124 | ||
|
|
c1cba4bd4c | ||
|
|
d43c406820 | ||
|
|
398df55f50 | ||
|
|
5888a71b36 | ||
|
|
c707064dfb | ||
|
|
8e56b59122 | ||
|
|
6fa5792e5e | ||
|
|
116492baca | ||
|
|
b1fee136ce | ||
|
|
95ce3a47fc | ||
|
|
195fd2d55b | ||
|
|
5d13b07c73 | ||
|
|
d8aca8ee3e | ||
|
|
495c7d34e5 | ||
|
|
39fdb23942 | ||
|
|
0d2c7f93be | ||
|
|
7c68a5cd71 | ||
|
|
b69fe4e15c | ||
|
|
873e4bbbec | ||
|
|
f2cf83f63b | ||
|
|
512356e106 | ||
|
|
309fecf008 | ||
|
|
29c954227f | ||
|
|
1f70f9fe2d |
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
|
||||
|
||||
return created_id
|
||||
|
||||
def update_entry(index: str, document_id: str, partial_doc: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
|
||||
|
||||
def get_entry(index: str, document_id: str) -> dict:
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
|
||||
"query": {"match_all": {}}
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
|
||||
def remove_field_all(index: str, field: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_update_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"exists": {"field": field}},
|
||||
"script": {
|
||||
"source": f"ctx._source.remove('{field}')",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
_client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
|
||||
return data.get("person", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
@@ -16,10 +16,12 @@ def sync_single_news(news_id, max_retries=3):
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||
authors = llm_client.extract_names(news_text)
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
"authors": authors,
|
||||
"keywords": keywords,
|
||||
}
|
||||
es_client.add_entry("aktuell_postproc", new_entry)
|
||||
return True
|
||||
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def update_keywords_single(postproc_entry, max_retries=3):
|
||||
doc_id = postproc_entry["_id"]
|
||||
news_id = postproc_entry["_source"]["news_id"]
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords})
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
||||
|
||||
@@ -47,6 +68,18 @@ def main():
|
||||
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--update-keywords",
|
||||
action="store_true",
|
||||
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--reset-keywords",
|
||||
action="store_true",
|
||||
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--stats",
|
||||
action="store_true",
|
||||
@@ -60,11 +93,22 @@ def main():
|
||||
help="Number of threads for --sync-delta (Default: 4).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.delete_all:
|
||||
es_client.delete_all_entries("aktuell_postproc")
|
||||
|
||||
if args.reset_keywords:
|
||||
result = es_client.remove_field_all("aktuell_postproc", "keywords")
|
||||
print(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
|
||||
|
||||
if args.sync_delta:
|
||||
start_time = time.time()
|
||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
@@ -96,23 +140,58 @@ def main():
|
||||
end_time = time.time()
|
||||
print(f"Sync DONE: {succeeded} entries synced.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
|
||||
if args.update_keywords:
|
||||
start_time = time.time()
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"])
|
||||
|
||||
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||
print(f"Number of entries without keywords: {len(pending)}")
|
||||
|
||||
if args.limit is not None:
|
||||
pending = pending[:args.limit]
|
||||
|
||||
total = len(pending)
|
||||
print(f"Processing {total} entries.")
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [executor.submit(update_keywords_single, entry) for entry in pending]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
print(f"Update keywords: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
print(f"Update keywords DONE: {succeeded} entries updated.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.stats:
|
||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors"])
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
|
||||
total_entries = len(postproc_entries)
|
||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||
irrelevant_count = total_entries - relevant_count
|
||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
||||
news_without_extracted_names = total_entries - news_with_extracted_names
|
||||
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
|
||||
news_without_keywords = total_entries - news_with_keywords
|
||||
|
||||
print(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||
print(f"Relevant entries: {relevant_count}")
|
||||
print(f"Irrelevant entries: {irrelevant_count}")
|
||||
print(f"Entries with extracted names: {news_with_extracted_names}")
|
||||
print(f"Entries without extracted names: {news_without_extracted_names}")
|
||||
print(f"Entries with keywords: {news_with_keywords}")
|
||||
print(f"Entries without keywords: {news_without_keywords}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because one or more lines are too long
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
@@ -55,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 (
|
||||
@@ -95,14 +95,14 @@ 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,
|
||||
@@ -157,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):
|
||||
@@ -207,7 +207,7 @@ 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(
|
||||
@@ -233,7 +233,7 @@ def list_organizations(
|
||||
|
||||
def update_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
access_token: AccessTokenMetadata,
|
||||
account_id: uuid.UUID,
|
||||
payload: UpdateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
@@ -307,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)
|
||||
|
||||
@@ -4,6 +4,7 @@ from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
@@ -15,9 +16,14 @@ 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 SecretPurpose(StrEnum):
|
||||
LOGIN_OTK = "LOGIN_OTK"
|
||||
PASSWORD_RESET = "PASSWORD_RESET"
|
||||
|
||||
|
||||
class Durable(SQLModel):
|
||||
@@ -106,6 +112,9 @@ class Account(Durable, table=True):
|
||||
|
||||
|
||||
class Secret(SQLModel, table=True):
|
||||
__table_args__ = (
|
||||
UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
|
||||
)
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
@@ -113,10 +122,16 @@ class Secret(SQLModel, table=True):
|
||||
)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id",
|
||||
unique=True, # Ensure that each account can have only one associated secret
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The unique identifier of the account associated with this secret.",
|
||||
)
|
||||
purpose: SecretPurpose = Field(
|
||||
default=SecretPurpose.LOGIN_OTK,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The purpose of the secret, such as login OTK or password reset.",
|
||||
)
|
||||
secret_value: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
@@ -127,39 +142,32 @@ class Secret(SQLModel, table=True):
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the secret will expire.",
|
||||
)
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
token_type: TokenType = Field(
|
||||
description="The type of the token (ID, Refresh, or Access).",
|
||||
)
|
||||
real_account_id: uuid.UUID = Field(
|
||||
request_count: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The number of password reset requests in the current rate-limit window.",
|
||||
)
|
||||
request_window_started_at: datetime | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The start timestamp of the current password reset request window.",
|
||||
)
|
||||
|
||||
|
||||
class BaseTokenData(BaseModel):
|
||||
real_account_id: uuid.UUID = Field(
|
||||
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,
|
||||
@@ -167,24 +175,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.",
|
||||
)
|
||||
|
||||
@@ -197,22 +204,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."
|
||||
)
|
||||
|
||||
@@ -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,10 +42,50 @@ 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)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/request-password-reset",
|
||||
summary="Request Password Reset",
|
||||
description="Request a one-time password reset link for the given email address.",
|
||||
operation_id="requestPasswordReset",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Password reset requested successfully."}
|
||||
},
|
||||
)
|
||||
async def request_password_reset(
|
||||
session: SessionDep,
|
||||
email: Annotated[str, Body(embed=True, description="User's email address")],
|
||||
):
|
||||
return auth_service.request_password_reset(session=session, email=email)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/reset-password",
|
||||
summary="Reset Password",
|
||||
description="Reset the user's password using a one-time password reset token.",
|
||||
operation_id="resetPassword",
|
||||
responses={status.HTTP_200_OK: {"description": "Password reset successfully."}},
|
||||
)
|
||||
async def reset_password(
|
||||
session: SessionDep,
|
||||
reset_token: Annotated[
|
||||
str, Body(description="Password reset token from the reset link")
|
||||
],
|
||||
new_password: Annotated[
|
||||
str,
|
||||
Body(description="New password", min_length=8, example="NewPassword123"),
|
||||
],
|
||||
):
|
||||
return auth_service.reset_password(
|
||||
session=session,
|
||||
reset_token=reset_token,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
summary="Login with One-Time Key",
|
||||
@@ -80,7 +122,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 +150,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 +170,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 +195,7 @@ async def change_password(
|
||||
Body(description="New password", min_length=8),
|
||||
],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
AccessTokenMetadata,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
|
||||
@@ -4,35 +4,42 @@ 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 sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.email_service import send_email
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
AccessTokenMetadata,
|
||||
Account,
|
||||
IdToken,
|
||||
IdTokenMetadata,
|
||||
LoginResponse,
|
||||
Organization,
|
||||
RefreshToken,
|
||||
OtkResponse,
|
||||
RefreshTokenMetadata,
|
||||
Secret,
|
||||
SecretPurpose,
|
||||
TokenType,
|
||||
UserRole,
|
||||
)
|
||||
from inse.config import get_settings
|
||||
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
|
||||
PASSWORD_RESET_EXPIRATION_MINUTES = 5 # 5 minutes
|
||||
PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES = 5 # 5 minutes
|
||||
PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
|
||||
|
||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||
@@ -41,8 +48,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,6 +165,31 @@ def _verify_password(password: str, password_hash: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _hash_reset_token(reset_token: str) -> str:
|
||||
"""Hashes a high-entropy password reset token for storage.
|
||||
|
||||
Args:
|
||||
reset_token (str): The raw reset token sent to the user.
|
||||
|
||||
Returns:
|
||||
str: SHA-256 hash of the reset token.
|
||||
"""
|
||||
return hashlib.sha256(reset_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _build_password_reset_link(reset_token: str) -> str:
|
||||
"""Builds the password reset link that will be sent to the user.
|
||||
|
||||
Args:
|
||||
reset_token (str): The raw reset token to include in the link.
|
||||
|
||||
Returns:
|
||||
str: The full password reset link.
|
||||
"""
|
||||
separator = "&" if "?" in settings.password_reset_url else "?"
|
||||
return f"{settings.password_reset_url}{separator}token={reset_token}"
|
||||
|
||||
|
||||
def request_otk(session: Session, email: str, password: str):
|
||||
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
|
||||
|
||||
@@ -180,11 +215,7 @@ def request_otk(session: Session, email: str, password: str):
|
||||
|
||||
logger.debug("OTK request for email %s: account found: %s", email, account)
|
||||
|
||||
if (
|
||||
account is None
|
||||
or account.deleted
|
||||
or account.id is None
|
||||
):
|
||||
if account is None or account.deleted or account.id is None:
|
||||
logger.warning("OTK request failed for email %s: account not found", email)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -210,7 +241,12 @@ def request_otk(session: Session, email: str, password: str):
|
||||
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
||||
print(otk_code)
|
||||
|
||||
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=OTK_EXPIRATION_MINUTES
|
||||
@@ -219,6 +255,7 @@ def request_otk(session: Session, email: str, password: str):
|
||||
if secret is None:
|
||||
secret = Secret(
|
||||
account_id=account.id,
|
||||
purpose=SecretPurpose.LOGIN_OTK,
|
||||
secret_value=otk_code,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
@@ -247,7 +284,211 @@ 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 request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||
"""Requests a one-time password reset link for the given email address.
|
||||
|
||||
For security reasons, this function always returns a successful response and
|
||||
does not reveal whether the email address belongs to an active account.
|
||||
"""
|
||||
email = email.lower().strip()
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
)
|
||||
).first()
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
logger.info("Password reset requested for unknown email %s", email)
|
||||
return {
|
||||
"status": "ok",
|
||||
"reset_link_created": False,
|
||||
"rate_limited": False,
|
||||
}
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
|
||||
if secret is not None:
|
||||
if secret.request_window_started_at is not None:
|
||||
window_started_at = secret.request_window_started_at
|
||||
if getattr(window_started_at, "tzinfo", None) is None:
|
||||
window_started_at = window_started_at.replace(
|
||||
tzinfo=datetime.timezone.utc
|
||||
)
|
||||
|
||||
window_ends_at = window_started_at + datetime.timedelta(
|
||||
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
|
||||
)
|
||||
|
||||
if window_ends_at > now:
|
||||
if secret.request_count >= PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW:
|
||||
retry_after_seconds = max(
|
||||
0,
|
||||
int((window_ends_at - now).total_seconds()),
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Password reset request rate-limited for account %s.",
|
||||
account.id,
|
||||
)
|
||||
return {
|
||||
"status": "ok",
|
||||
"reset_link_created": False,
|
||||
"rate_limited": True,
|
||||
"retry_after_seconds": retry_after_seconds,
|
||||
}
|
||||
else:
|
||||
secret.request_count = 0
|
||||
secret.request_window_started_at = now
|
||||
else:
|
||||
secret.request_count = 0
|
||||
secret.request_window_started_at = now
|
||||
|
||||
reset_token = secrets.token_urlsafe(32)
|
||||
reset_token_hash = _hash_reset_token(reset_token)
|
||||
|
||||
expires_at = now + datetime.timedelta(minutes=PASSWORD_RESET_EXPIRATION_MINUTES)
|
||||
|
||||
if secret is None:
|
||||
secret = Secret(
|
||||
account_id=account.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=reset_token_hash,
|
||||
expires_at=expires_at,
|
||||
request_count=1,
|
||||
request_window_started_at=now,
|
||||
)
|
||||
session.add(secret)
|
||||
else:
|
||||
secret.secret_value = reset_token_hash
|
||||
secret.expires_at = expires_at
|
||||
secret.request_count += 1
|
||||
|
||||
if secret.request_window_started_at is None:
|
||||
secret.request_window_started_at = now
|
||||
|
||||
session.commit()
|
||||
|
||||
reset_link = _build_password_reset_link(reset_token)
|
||||
|
||||
if settings.send_password_reset_email:
|
||||
try:
|
||||
send_email(
|
||||
recipient=account.email,
|
||||
subject="Reset your SmartGUIDE password",
|
||||
body=(
|
||||
"Use the following link to reset your SmartGUIDE password:\n"
|
||||
f"{reset_link}\n\n"
|
||||
f"This link expires in {PASSWORD_RESET_EXPIRATION_MINUTES} minutes."
|
||||
),
|
||||
smtp_server=settings.smtp_server,
|
||||
smtp_port=settings.smtp_port,
|
||||
sender=settings.smtp_sender,
|
||||
username=settings.smtp_username,
|
||||
password=settings.smtp_password,
|
||||
use_tls=settings.smtp_use_tls,
|
||||
)
|
||||
logger.info("Sent password reset email for account %s", account.id)
|
||||
except Exception:
|
||||
if settings.environment == "dev":
|
||||
logger.exception(
|
||||
"Failed to send password reset email for account %s. "
|
||||
"Falling back to console reset link.",
|
||||
account.id,
|
||||
)
|
||||
logger.info(
|
||||
"Password reset link for account %s: %s",
|
||||
account.id,
|
||||
reset_link,
|
||||
)
|
||||
else:
|
||||
raise
|
||||
elif settings.environment == "dev":
|
||||
logger.info("Password reset link for account %s: %s", account.id, reset_link)
|
||||
else:
|
||||
logger.info("Password reset token generated for account %s", account.id)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"reset_link_created": True,
|
||||
"rate_limited": False,
|
||||
}
|
||||
|
||||
|
||||
def reset_password(
|
||||
session: Session,
|
||||
reset_token: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
"""Resets an account password using a one-time password reset token.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account and secret.
|
||||
reset_token (str): The raw reset token from the password reset link.
|
||||
new_password (str): The new password to store for the account.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the reset token is invalid or expired.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: A status response.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
reset_token_hash = _hash_reset_token(reset_token.strip())
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
Secret.secret_value == reset_token_hash,
|
||||
)
|
||||
).first()
|
||||
|
||||
if secret is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired password reset token",
|
||||
)
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
|
||||
if secret_expires <= now:
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired password reset token",
|
||||
)
|
||||
|
||||
account = session.get(Account, secret.account_id)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired password reset token",
|
||||
)
|
||||
|
||||
account.password_hash = _hash_password(new_password)
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def login(
|
||||
@@ -273,6 +514,7 @@ def login(
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account_id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
Secret.secret_value == email_code,
|
||||
# Validating the code and ensuring it matches the account ID
|
||||
)
|
||||
@@ -331,9 +573,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:
|
||||
@@ -344,18 +586,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(
|
||||
@@ -367,15 +613,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:
|
||||
@@ -384,18 +628,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(
|
||||
@@ -406,8 +652,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)
|
||||
@@ -417,9 +661,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:
|
||||
@@ -430,30 +673,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -582,26 +819,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:
|
||||
@@ -616,16 +837,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)
|
||||
@@ -633,7 +853,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,
|
||||
@@ -643,77 +863,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:
|
||||
@@ -726,25 +965,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,
|
||||
@@ -752,7 +973,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -760,7 +981,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:
|
||||
@@ -775,34 +996,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:
|
||||
@@ -815,7 +1033,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
|
||||
@@ -826,7 +1044,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(
|
||||
@@ -834,16 +1051,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -930,18 +1145,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.
|
||||
@@ -953,19 +1207,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,
|
||||
@@ -974,23 +1238,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)
|
||||
@@ -1013,7 +1266,6 @@ def _verify_fp_token(
|
||||
)
|
||||
|
||||
return payload
|
||||
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -1055,7 +1307,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:
|
||||
@@ -1079,7 +1331,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]:
|
||||
|
||||
@@ -14,9 +14,11 @@ from inse.auth.model import (
|
||||
Account,
|
||||
Organization,
|
||||
Secret,
|
||||
IdToken,
|
||||
SecretPurpose,
|
||||
AccessToken,
|
||||
RefreshToken,
|
||||
IdTokenMetadata,
|
||||
AccessTokenMetadata,
|
||||
RefreshTokenMetadata,
|
||||
UserRole,
|
||||
)
|
||||
|
||||
@@ -61,6 +63,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,11 +95,14 @@ 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)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
@@ -93,9 +111,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 +129,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 +173,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
|
||||
|
||||
|
||||
@@ -233,6 +267,7 @@ def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_sess
|
||||
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)
|
||||
|
||||
@@ -250,7 +285,12 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
assert acc.id is not None
|
||||
|
||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.LOGIN_OTK,
|
||||
secret_value="000000",
|
||||
expires_at=expired_at,
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
@@ -268,24 +308,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,
|
||||
)
|
||||
|
||||
@@ -300,28 +336,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,
|
||||
)
|
||||
|
||||
@@ -336,25 +369,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,
|
||||
)
|
||||
|
||||
@@ -391,7 +420,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):
|
||||
@@ -406,14 +435,20 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret1 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert secret1 is not None
|
||||
first_value = secret1.secret_value
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret2 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
|
||||
assert secret2 is not None
|
||||
@@ -425,7 +460,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):
|
||||
@@ -440,13 +475,19 @@ def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||
post = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert post is None
|
||||
|
||||
@@ -461,7 +502,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,
|
||||
@@ -469,18 +510,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,
|
||||
)
|
||||
|
||||
@@ -495,34 +531,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,
|
||||
)
|
||||
|
||||
@@ -544,3 +572,180 @@ def test_get_account_epoch_not_found(in_memory_session):
|
||||
random_id = uuid.uuid4()
|
||||
with pytest.raises(Exception):
|
||||
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||
|
||||
|
||||
|
||||
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
|
||||
email = "reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
result = auth_service.request_password_reset(in_memory_session, email)
|
||||
assert result["status"] == "ok"
|
||||
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
|
||||
assert secret is not None
|
||||
assert secret.secret_value is not None
|
||||
assert secret.secret_value != ""
|
||||
assert secret.secret_value != password
|
||||
|
||||
|
||||
def test_request_password_reset_unknown_email_is_safe(
|
||||
in_memory_session, settings_backup, monkeypatch
|
||||
):
|
||||
sent_emails = []
|
||||
|
||||
def fake_send_email(**kwargs):
|
||||
sent_emails.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||
config_module.settings.send_password_reset_email = True
|
||||
|
||||
result = auth_service.request_password_reset(
|
||||
in_memory_session, "missing@example.com"
|
||||
)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert sent_emails == []
|
||||
|
||||
|
||||
def test_request_password_reset_sends_email(
|
||||
in_memory_session, settings_backup, monkeypatch
|
||||
):
|
||||
email = "mail-reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
sent_emails = []
|
||||
|
||||
def fake_send_email(**kwargs):
|
||||
sent_emails.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||
config_module.settings.send_password_reset_email = True
|
||||
config_module.settings.password_reset_url = "http://localhost/reset-password"
|
||||
|
||||
result = auth_service.request_password_reset(in_memory_session, email)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert len(sent_emails) == 1
|
||||
assert sent_emails[0]["recipient"] == email
|
||||
assert "token=" in sent_emails[0]["body"]
|
||||
|
||||
|
||||
def test_reset_password_changes_password_and_increments_epoch(in_memory_session):
|
||||
email = "do-reset@example.com"
|
||||
password = "oldpw123"
|
||||
new_password = "NewPassword123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
reset_token = "valid-reset-token"
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
old_epoch = acc.epoch
|
||||
|
||||
result = auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
in_memory_session.refresh(acc)
|
||||
assert auth_service._verify_password(new_password, acc.password_hash)
|
||||
assert acc.epoch == old_epoch + 1
|
||||
|
||||
deleted_secret = in_memory_session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
assert deleted_secret is None
|
||||
|
||||
|
||||
def test_reset_password_rejects_reused_token(in_memory_session):
|
||||
email = "reuse-reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
reset_token = "single-use-token"
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password="NewPassword123",
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password="AnotherPassword123",
|
||||
)
|
||||
|
||||
|
||||
def test_reset_password_rejects_invalid_token(in_memory_session):
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token="invalid-token",
|
||||
new_password="NewPassword123",
|
||||
)
|
||||
|
||||
|
||||
def test_reset_password_rejects_expired_token(in_memory_session):
|
||||
email = "expired-reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
reset_token = "expired-token"
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password="NewPassword123",
|
||||
)
|
||||
|
||||
deleted_secret = in_memory_session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
assert deleted_secret is None
|
||||
|
||||
@@ -70,6 +70,8 @@ class Settings(BaseSettings):
|
||||
skip_otk_validation: bool = True
|
||||
# SMTP / email config
|
||||
send_otk_email: bool = False
|
||||
send_password_reset_email: bool = True
|
||||
password_reset_url: str = "http://localhost:4200/inse-webapp/reset-password"
|
||||
smtp_server: str = "localhost"
|
||||
smtp_port: int = 25
|
||||
smtp_sender: str = "no-reply@smartguide.local"
|
||||
|
||||
@@ -23,6 +23,7 @@ def get_client() -> httpx.AsyncClient:
|
||||
global _client, _loop
|
||||
try:
|
||||
import asyncio
|
||||
|
||||
current_loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
current_loop = None
|
||||
@@ -45,7 +46,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
Returns:
|
||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||
"""
|
||||
|
||||
|
||||
if cluster == ESCluster.NES:
|
||||
if (
|
||||
not config.settings.elasticsearch_url
|
||||
@@ -54,7 +55,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||
)
|
||||
|
||||
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == ESCluster.INSE:
|
||||
if (
|
||||
@@ -108,8 +109,12 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
def _wrap_exception(e: Exception) -> Exception:
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
||||
return ElasticsearchNotFoundException(
|
||||
f"Elasticsearch resource not found: {e}"
|
||||
)
|
||||
return ElasticsearchException(
|
||||
f"Elasticsearch returned status {e.response.status_code}: {e}"
|
||||
)
|
||||
elif isinstance(e, httpx.RequestError):
|
||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||
@@ -211,7 +216,9 @@ async def search(
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
async def open_point_in_time(
|
||||
index: str, keep_alive: str = "1m", cluster: str = "nes"
|
||||
) -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
@@ -256,7 +263,7 @@ async def scan(
|
||||
cluster: str = "nes",
|
||||
) -> AsyncIterator[Dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
@@ -316,6 +323,9 @@ async def get(
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
if isinstance(index, ESIndex):
|
||||
cluster = _index_to_cluster(index) or cluster
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
@@ -2,7 +2,7 @@ from openai import OpenAI, APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
import asyncio
|
||||
def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
@@ -62,7 +62,7 @@ def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str,
|
||||
async def call_stream(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
emit, # EventCallback
|
||||
emit,
|
||||
model: str = None,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
@@ -98,15 +98,26 @@ async def call_stream(
|
||||
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})
|
||||
try:
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
finally:
|
||||
# Always release the underlying HTTP connection, whether we
|
||||
# finished normally, timed out, were cancelled, or emit()
|
||||
# failed because the client disconnected. This is what
|
||||
# actually tells the backend to stop generating.
|
||||
await stream.close()
|
||||
|
||||
except APIConnectionError as e:
|
||||
print(f"Connection error: {e}")
|
||||
return ""
|
||||
except asyncio.CancelledError:
|
||||
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
|
||||
# from the router)
|
||||
raise
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||
|
||||
@@ -126,141 +126,6 @@ async def _get_text_content(url: str) -> str:
|
||||
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,
|
||||
@@ -275,13 +140,17 @@ async def extract_keywords_stream_enriched(
|
||||
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())
|
||||
if text:
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
else:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
|
||||
raise RuntimeError(f"Failed to fetch content from {query}")
|
||||
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"
|
||||
@@ -290,15 +159,10 @@ async def extract_keywords_stream_enriched(
|
||||
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:
|
||||
@@ -306,29 +170,19 @@ async def extract_keywords_stream_enriched(
|
||||
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)
|
||||
@@ -338,7 +192,6 @@ async def extract_keywords_stream_enriched(
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
@@ -346,19 +199,18 @@ async def extract_keywords_stream_enriched(
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
start_idx = len(confirmed[level]) # Where we start appending
|
||||
start_idx = len(confirmed[level])
|
||||
|
||||
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
|
||||
break
|
||||
|
||||
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(
|
||||
@@ -374,7 +226,6 @@ async def extract_keywords_stream_enriched(
|
||||
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:
|
||||
@@ -384,6 +235,7 @@ async def extract_keywords_stream_enriched(
|
||||
await on_chunk(event)
|
||||
|
||||
# ---------- Call the LLM ----------
|
||||
keywords = ""
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
@@ -401,14 +253,24 @@ async def extract_keywords_stream_enriched(
|
||||
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
|
||||
|
||||
finally:
|
||||
if enrichment_tasks:
|
||||
done, pending = await asyncio.wait(enrichment_tasks, timeout=10)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
if pending:
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
|
||||
if not keywords:
|
||||
# Empty string covers: real empty completion, APIConnectionError,
|
||||
# and disconnect-during-emit (call_stream currently swallows all
|
||||
# three the same way). Treat as a failed extraction.
|
||||
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
||||
raise RuntimeError("LLM streaming call returned empty content")
|
||||
|
||||
# ---------- Finalize ----------
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
@@ -418,13 +280,8 @@ async def extract_keywords_stream_enriched(
|
||||
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:
|
||||
|
||||
@@ -35,13 +35,118 @@ class KeywordsPrompt(StrEnum):
|
||||
|
||||
---
|
||||
|
||||
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||
|
||||
The output must be strictly extractive and grounded in the input text.
|
||||
|
||||
## Mandatory Rules
|
||||
|
||||
1. Extract ONLY keywords, terms, entities, concepts, technologies, methods, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the input text.
|
||||
|
||||
2. Do NOT introduce, infer, generalize, expand, normalize, summarize, classify, enrich, or extrapolate concepts beyond what is directly present in the text.
|
||||
|
||||
3. Do NOT generate parent categories, broader domains, scientific disciplines, industries, or technology areas unless those exact terms appear in the input text.
|
||||
|
||||
Example:
|
||||
|
||||
Input contains:
|
||||
|
||||
"transformer-based machine learning framework"
|
||||
|
||||
Allowed:
|
||||
|
||||
* transformer-based machine learning framework
|
||||
* machine learning
|
||||
* transformer
|
||||
|
||||
Not allowed:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Deep Learning
|
||||
* Neural Networks
|
||||
|
||||
unless those exact terms appear in the text.
|
||||
|
||||
4. Do NOT generate synonyms, abbreviations, alternate phrasings, normalized forms, or related concepts that do not explicitly appear in the source text.
|
||||
|
||||
Example:
|
||||
|
||||
Input:
|
||||
|
||||
"large language models"
|
||||
|
||||
Allowed:
|
||||
|
||||
* large language models
|
||||
|
||||
Not allowed:
|
||||
|
||||
* LLMs
|
||||
* Generative AI
|
||||
* Artificial Intelligence
|
||||
|
||||
unless explicitly present.
|
||||
|
||||
5. Do NOT generate implied concepts.
|
||||
|
||||
Example:
|
||||
|
||||
Input:
|
||||
|
||||
"patient records"
|
||||
|
||||
Not allowed:
|
||||
|
||||
* Healthcare
|
||||
* Medical Informatics
|
||||
* Clinical Documentation
|
||||
|
||||
unless explicitly mentioned.
|
||||
|
||||
6. Every keyword must have direct textual evidence in the input.
|
||||
|
||||
7. If a keyword cannot be highlighted verbatim or as a contiguous phrase in the source text, it must NOT appear in the output.
|
||||
|
||||
8. Prefer exact surface forms from the text.
|
||||
|
||||
9. Preserve original capitalization when possible.
|
||||
|
||||
10. Do not invent keywords to satisfy target counts.
|
||||
|
||||
11. When insufficient keywords exist for a level, return fewer keywords.
|
||||
|
||||
12. Grounding accuracy is more important than completeness.
|
||||
|
||||
13. Any keyword not directly supported by the text is considered an extraction error.
|
||||
|
||||
## Hierarchy Assignment Rules
|
||||
|
||||
The hierarchy is only an organizational grouping.
|
||||
|
||||
Do NOT create broader concepts to populate broad_keywords.
|
||||
|
||||
If the source text contains only specific concepts, place those concepts into the most appropriate level while remaining faithful to the text.
|
||||
|
||||
Do not create abstraction layers that are not explicitly present in the document.
|
||||
|
||||
## Self-Validation Before Output
|
||||
|
||||
Before returning the final JSON, verify every keyword:
|
||||
|
||||
* Can this exact phrase be found in the input text?
|
||||
* Can a user highlight the phrase directly in the source text?
|
||||
|
||||
If the answer is NO, remove the keyword.
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## 1. broad_keywords
|
||||
|
||||
High-level domains, disciplines, industries, or technology areas.
|
||||
High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text.
|
||||
|
||||
Examples:
|
||||
Examples (only if explicitly mentioned):
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
@@ -50,15 +155,15 @@ class KeywordsPrompt(StrEnum):
|
||||
* Materials Science
|
||||
* Robotics
|
||||
|
||||
These should represent the major themes of the document.
|
||||
These should represent the major themes of the document when those themes are explicitly stated.
|
||||
|
||||
---
|
||||
|
||||
## 2. coarse_grained
|
||||
|
||||
Mid-level concepts, technologies, research areas, methods, or applications.
|
||||
Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text.
|
||||
|
||||
Examples:
|
||||
Examples (only if explicitly mentioned):
|
||||
|
||||
* Machine Learning
|
||||
* Drug Discovery
|
||||
@@ -73,9 +178,9 @@ class KeywordsPrompt(StrEnum):
|
||||
|
||||
## 3. fine_grained
|
||||
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text.
|
||||
|
||||
Examples:
|
||||
Examples (only if explicitly mentioned):
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
@@ -114,21 +219,56 @@ class KeywordsPrompt(StrEnum):
|
||||
|
||||
# Extraction Rules
|
||||
|
||||
* Extract only concepts explicitly mentioned or strongly implied.
|
||||
* Extract only concepts explicitly mentioned in the text.
|
||||
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||
* Every keyword must be directly traceable to text spans in the input.
|
||||
* 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.
|
||||
* If fewer valid keywords exist, return fewer.
|
||||
|
||||
---
|
||||
|
||||
# Output Schema
|
||||
|
||||
Return ONLY valid JSON.
|
||||
Return ONLY valid JSON using the following structure:
|
||||
|
||||
{
|
||||
"broad_keywords": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
],
|
||||
"coarse_grained": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
],
|
||||
"fine_grained": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Requirements:
|
||||
|
||||
* Return ONLY valid JSON.
|
||||
* Do not include explanations.
|
||||
* Do not include markdown.
|
||||
* Do not include comments.
|
||||
* Do not include reasoning.
|
||||
* Do not include any text outside the JSON object.
|
||||
* Every keyword must be directly supported by the input text.
|
||||
* Any keyword not explicitly present in the source text must be excluded.
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
---
|
||||
|
||||
# Example 1
|
||||
@@ -136,269 +276,277 @@ class KeywordsPrompt(StrEnum):
|
||||
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}]}
|
||||
|
||||
broad_keywords":[{"keyword":"Industrial manufacturing","relevance_score":0.94}],"coarse_grained":[{"keyword":"Machine learning","relevance_score":0.97},{"keyword":"Predictive maintenance","relevance_score":0.95},{"keyword":"Sensor fusion","relevance_score":0.89},{"keyword":"Anomaly detection","relevance_score":0.88},{"keyword":"Time-series forecasting","relevance_score":0.87},{"keyword":"Smart factories","relevance_score":0.85}],"fine_grained":[{"keyword":"Transformer-based machine learning framework","relevance_score":0.96}]}
|
||||
---
|
||||
|
||||
# Example 2
|
||||
|
||||
Input:
|
||||
|
||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||
|
||||
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}]}
|
||||
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.96}],"coarse_grained":[{"keyword":"Large language models","relevance_score":0.95},{"keyword":"Clinical decision-making","relevance_score":0.91},{"keyword":"Patient records","relevance_score":0.90}],"fine_grained":[{"keyword":"Retrieval-augmented generation","relevance_score":0.94}]}
|
||||
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.
|
||||
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 input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||
|
||||
The extracted text may contain:
|
||||
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
|
||||
* 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.
|
||||
Your first task is to identify the actual content and purpose of the webpage.
|
||||
|
||||
Ignore:
|
||||
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
|
||||
* 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:
|
||||
Focus only on the primary informational content of the webpage.
|
||||
|
||||
* Technologies
|
||||
* Scientific concepts
|
||||
* Research areas
|
||||
* Technical methods
|
||||
* Products
|
||||
* Applications
|
||||
* Industrial sectors
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Engineering disciplines
|
||||
* Innovation domains
|
||||
---
|
||||
|
||||
---
|
||||
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||
|
||||
# Step 1: Determine Page Type
|
||||
The output must be strictly extractive and grounded in the webpage text.
|
||||
|
||||
Determine which type of page is represented:
|
||||
## Mandatory Rules
|
||||
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
|
||||
|
||||
Use this classification internally only.
|
||||
2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text.
|
||||
|
||||
Do not include it in the output.
|
||||
3. Do NOT generate broader domains, scientific disciplines, industries, technology areas, research fields, or categories unless those exact terms appear in the webpage text.
|
||||
|
||||
---
|
||||
Example:
|
||||
|
||||
# Step 2: Extract Searchable Concepts
|
||||
Input:
|
||||
|
||||
Prioritize concepts that are useful for:
|
||||
"The platform uses large language models and retrieval-augmented generation."
|
||||
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
Allowed:
|
||||
|
||||
Prefer canonical scientific terminology over marketing language.
|
||||
* large language models
|
||||
* retrieval-augmented generation
|
||||
|
||||
Examples:
|
||||
Not allowed:
|
||||
|
||||
Prefer:
|
||||
* Artificial Intelligence
|
||||
* Generative AI
|
||||
* Natural Language Processing
|
||||
|
||||
* Large Language Models
|
||||
unless explicitly present.
|
||||
|
||||
Instead of:
|
||||
4. Do NOT generate synonyms.
|
||||
|
||||
* AI Assistant
|
||||
Example:
|
||||
|
||||
Prefer:
|
||||
Input:
|
||||
|
||||
* Smart Manufacturing
|
||||
"AI assistant"
|
||||
|
||||
Instead of:
|
||||
Allowed:
|
||||
|
||||
* Factory Optimization Solution
|
||||
* AI assistant
|
||||
|
||||
Prefer:
|
||||
Not allowed:
|
||||
|
||||
* Retrieval-Augmented Generation
|
||||
* large language models
|
||||
* conversational AI
|
||||
* generative AI
|
||||
|
||||
Instead of:
|
||||
unless those exact terms appear.
|
||||
|
||||
* Intelligent Knowledge Assistant
|
||||
5. Do NOT generate canonical scientific terminology when it does not appear in the source text.
|
||||
|
||||
Prefer:
|
||||
6. Do NOT rewrite marketing terms into technical terms.
|
||||
|
||||
* Predictive Maintenance
|
||||
7. Every keyword must have direct textual evidence in the webpage content.
|
||||
|
||||
Instead of:
|
||||
8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output.
|
||||
|
||||
* Equipment Performance Optimization
|
||||
9. Preserve original wording whenever possible.
|
||||
|
||||
---
|
||||
10. Do not invent keywords to satisfy target counts.
|
||||
|
||||
# Keyword Hierarchy
|
||||
11. When insufficient keywords exist, return fewer keywords.
|
||||
|
||||
## broad_keywords
|
||||
12. Grounding accuracy is more important than completeness.
|
||||
|
||||
High-level domains, industries, disciplines, or technology areas.
|
||||
13. Any keyword not directly supported by the webpage text is considered an extraction error.
|
||||
|
||||
Examples:
|
||||
---
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Manufacturing
|
||||
* Energy Storage
|
||||
* Biotechnology
|
||||
* Robotics
|
||||
# Step 1: Determine Page Type
|
||||
|
||||
---
|
||||
Determine internally whether the page is:
|
||||
|
||||
## coarse_grained
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
|
||||
Technologies, methods, research fields, and applications.
|
||||
Use this classification only to identify the relevant content and remove boilerplate.
|
||||
|
||||
Examples:
|
||||
Do NOT include the classification in the output.
|
||||
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Computer Vision
|
||||
* Clinical Decision Support
|
||||
---
|
||||
|
||||
---
|
||||
# Step 2: Extract Searchable Concepts
|
||||
|
||||
## fine_grained
|
||||
Extract concepts directly present in the page that are useful for:
|
||||
|
||||
Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
|
||||
Examples:
|
||||
The extracted concepts must remain faithful to the wording used in the webpage.
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* OPC UA
|
||||
* Retrieval-Augmented Generation
|
||||
* YOLOv8
|
||||
* Lithium Iron Phosphate
|
||||
Do NOT replace webpage terminology with your own preferred terminology.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
# Keyword Hierarchy
|
||||
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
## broad_keywords
|
||||
|
||||
Guidelines:
|
||||
High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage.
|
||||
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
Only use this level when such broad concepts are explicitly present.
|
||||
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
Examples:
|
||||
|
||||
---
|
||||
* Healthcare
|
||||
* Biotechnology
|
||||
* Manufacturing
|
||||
* Robotics
|
||||
* Financial Technology
|
||||
|
||||
# Additional Rules
|
||||
only if those exact concepts appear in the webpage.
|
||||
|
||||
* 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
|
||||
## coarse_grained
|
||||
|
||||
## Input
|
||||
Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage.
|
||||
|
||||
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.
|
||||
Examples:
|
||||
|
||||
## Output
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Clinical Decision Support
|
||||
|
||||
```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}]}```
|
||||
only if explicitly present.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Example 4 — Product Page
|
||||
## fine_grained
|
||||
|
||||
## Input
|
||||
Highly specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, protocols, model names, framework names, software packages, or specialized terminology explicitly present in the webpage.
|
||||
|
||||
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.
|
||||
Examples:
|
||||
|
||||
## Output
|
||||
* FastAPI
|
||||
* OpenAPI
|
||||
* Pydantic
|
||||
* CRISPR-Cas9
|
||||
* Retrieval-Augmented Generation
|
||||
* OPC UA
|
||||
|
||||
```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}]}```
|
||||
only if explicitly present.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Example 5 — Technical Documentation
|
||||
# Relevance Score
|
||||
|
||||
## Input
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
|
||||
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.
|
||||
Guidelines:
|
||||
|
||||
## Output
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
|
||||
```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}]}```
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
|
||||
---
|
||||
Rank keywords by importance.
|
||||
|
||||
# Example 6 — Company Website
|
||||
---
|
||||
|
||||
## Input
|
||||
# Extraction Rules
|
||||
|
||||
Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations.
|
||||
* Extract only concepts explicitly mentioned in the webpage text.
|
||||
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||
* Every keyword must be directly traceable to text spans in the webpage.
|
||||
* Prefer noun phrases.
|
||||
* Avoid complete sentences.
|
||||
* Avoid duplicates across hierarchy levels whenever possible.
|
||||
* Preserve original wording.
|
||||
* Rank keywords by importance.
|
||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||
* If fewer valid keywords exist, return fewer.
|
||||
|
||||
## 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}]}```
|
||||
# Self-Validation Before Output
|
||||
|
||||
---
|
||||
For every keyword, verify:
|
||||
|
||||
* Can this exact phrase be found in the webpage text?
|
||||
* Can a user highlight the phrase directly in the extracted content?
|
||||
|
||||
If the answer is NO, remove the keyword.
|
||||
|
||||
---
|
||||
|
||||
# Example — 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:
|
||||
|
||||
{"broad_keywords":[{"keyword":"Python web framework","relevance_score":0.95}],"coarse_grained":[{"keyword":"building APIs","relevance_score":0.93},{"keyword":"Data validation","relevance_score":0.90}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"Dependency Injection","relevance_score":0.91},{"keyword":"Asynchronous Request Handling","relevance_score":0.89},{"keyword":"Pydantic","relevance_score":0.88}]}
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
SIMPLE_TEXT_PROMPT = """
|
||||
|
||||
@@ -8,10 +8,13 @@ import asyncio
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||
from uvicorn.protocols.utils import ClientDisconnected
|
||||
|
||||
from . import logic
|
||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service",
|
||||
@@ -19,26 +22,35 @@ router = APIRouter(
|
||||
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()
|
||||
|
||||
disconnected = asyncio.Event()
|
||||
extraction_task: asyncio.Task | None = None
|
||||
|
||||
async def emit(event: dict):
|
||||
if disconnected.is_set():
|
||||
return
|
||||
try:
|
||||
await websocket.send_json(event)
|
||||
except (WebSocketDisconnect, ClientDisconnected):
|
||||
disconnected.set()
|
||||
|
||||
async def safe_send(payload: dict):
|
||||
if disconnected.is_set():
|
||||
return
|
||||
try:
|
||||
await websocket.send_json(payload)
|
||||
except (WebSocketDisconnect, ClientDisconnected):
|
||||
disconnected.set()
|
||||
|
||||
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
|
||||
request = KeywordsRequest(**raw)
|
||||
|
||||
extraction_task = asyncio.create_task(
|
||||
logic.extract_keywords_stream_enriched(
|
||||
@@ -48,60 +60,37 @@ async def extract_keywords_ws(websocket: WebSocket):
|
||||
emit=emit,
|
||||
)
|
||||
)
|
||||
disconnect_task = asyncio.create_task(watch_disconnect())
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
{extraction_task, disconnect_task},
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
result = await extraction_task
|
||||
|
||||
if disconnect_task in done:
|
||||
disconnected.set()
|
||||
await safe_send({
|
||||
"type": "completed",
|
||||
"result": result.model_dump(),
|
||||
})
|
||||
|
||||
except (WebSocketDisconnect, ClientDisconnected):
|
||||
disconnected.set()
|
||||
logger.info("Client disconnected from keyword extraction ws")
|
||||
print("Client disconnected from keyword extraction ws")
|
||||
|
||||
except Exception as e:
|
||||
disconnected.set()
|
||||
logger.exception("Error in keyword extraction ws")
|
||||
await safe_send({
|
||||
"type": "error",
|
||||
"message": str(e),
|
||||
})
|
||||
|
||||
finally:
|
||||
if extraction_task is not None and not extraction_task.done():
|
||||
extraction_task.cancel()
|
||||
try:
|
||||
await extraction_task
|
||||
except asyncio.CancelledError:
|
||||
except (asyncio.CancelledError, Exception):
|
||||
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",
|
||||
|
||||
@@ -24,7 +24,7 @@ from inse.exceptions import (
|
||||
)
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.router import router as university_ranking_router
|
||||
from inse.university_ranking.service import router as university_ranking_router
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
@@ -53,6 +53,8 @@ from inse.patents.service import (
|
||||
router as patents_service_router,
|
||||
)
|
||||
|
||||
from inse.works.purpose_router import router as works_purpose_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
### startup
|
||||
@@ -83,6 +85,7 @@ 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_purpose_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
@@ -100,6 +103,7 @@ app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
ttl=300, # 5 minutes expiration time
|
||||
@@ -116,6 +120,7 @@ app.add_middleware(
|
||||
|
||||
# exception handlers
|
||||
|
||||
|
||||
@app.exception_handler(NotFoundException)
|
||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||
@@ -124,13 +129,18 @@ async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
@app.exception_handler(ElasticsearchException)
|
||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
||||
return JSONResponse(
|
||||
status_code=502, content={"message": "Search service temporarily unavailable"}
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(MissingApiKeyError)
|
||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||
logger.error("Configuration error: %s", str(exc))
|
||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"message": str(exc) or "Search service is not configured"},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(UpstreamAPIException)
|
||||
|
||||
@@ -34,6 +34,10 @@ class ESIndex(StrEnum):
|
||||
OPENALEX_AUTHORS = "openalex-authors"
|
||||
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
||||
OPENALEX_PUBLICATIONS = "openalex-publications"
|
||||
OPENALEX_COUNTRIES = "openalex-countries"
|
||||
OPENALEX_CONTINENTS = "openalex-continents"
|
||||
OPENALEX_TOPICS = "openalex-topics"
|
||||
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
|
||||
Binary file not shown.
@@ -39,6 +39,7 @@ class Topic(BaseModel):
|
||||
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
|
||||
subfield: Optional[TopicSubfield] = None
|
||||
var_field: Optional[TopicField] = Field(default=None, alias="field")
|
||||
field: Optional[TopicField] = Field(default=None)
|
||||
domain: Optional[TopicDomain] = None
|
||||
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
|
||||
cited_by_count: Optional[StrictInt] = None
|
||||
|
||||
@@ -33,11 +33,12 @@ class WorkTopic(BaseModel):
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
display_name: Optional[StrictStr] = None
|
||||
description: Optional[StrictStr] = None
|
||||
score: Optional[Union[StrictFloat, StrictInt]] = None
|
||||
subfield: Optional[WorkTopicSubfield] = None
|
||||
var_field: Optional[WorkTopicField] = Field(default=None, alias="field")
|
||||
domain: Optional[WorkTopicDomain] = None
|
||||
__properties: ClassVar[List[str]] = ["id", "display_name", "score", "subfield", "field", "domain"]
|
||||
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "score", "subfield", "field", "domain"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
@@ -101,6 +102,7 @@ class WorkTopic(BaseModel):
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"display_name": obj.get("display_name"),
|
||||
"description": obj.get("description"),
|
||||
"score": obj.get("score"),
|
||||
"subfield": WorkTopicSubfield.from_dict(obj["subfield"]) if obj.get("subfield") is not None else None,
|
||||
"field": WorkTopicField.from_dict(obj["field"]) if obj.get("field") is not None else None,
|
||||
|
||||
@@ -12,7 +12,8 @@ from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
from ..topics.logic import vector_search_topics
|
||||
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
|
||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
TOPIC_MATCHES_PER_KEYWORD = 1
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
@@ -80,7 +86,14 @@ async def search_news(
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
exact_query = {
|
||||
"bool": {
|
||||
"must": [{"match": {"full_content": query_text}}],
|
||||
"must": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query_text,
|
||||
"fields": ["maintitle^2", "full_content"],
|
||||
}
|
||||
}
|
||||
],
|
||||
"filter": clauses,
|
||||
}
|
||||
}
|
||||
@@ -240,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
@@ -248,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
source.get("maintitle"),
|
||||
source.get("full_content"),
|
||||
)
|
||||
topics = await _match_topics_for_keywords(keywords)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
@@ -258,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
topics=topics,
|
||||
)
|
||||
|
||||
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
@@ -308,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
candidates = parsed if isinstance(parsed, list) else []
|
||||
if isinstance(parsed, list):
|
||||
candidates = parsed
|
||||
elif isinstance(parsed, dict):
|
||||
candidates = parsed.get("keywords", [])
|
||||
else:
|
||||
candidates = []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
@@ -343,6 +350,35 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list)
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
async def _match_topics_for_keywords(keywords: list) -> list:
|
||||
matched = []
|
||||
seen_ids = set()
|
||||
|
||||
for keyword in keywords:
|
||||
try:
|
||||
response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD)
|
||||
except Exception:
|
||||
logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.")
|
||||
continue
|
||||
|
||||
for topic in response.results or []:
|
||||
if not topic.id or topic.id in seen_ids:
|
||||
continue
|
||||
seen_ids.add(topic.id)
|
||||
matched.append(
|
||||
MatchedTopic(
|
||||
id=topic.id,
|
||||
display_name=topic.display_name,
|
||||
subfield_name=topic.subfield.display_name if topic.subfield else None,
|
||||
field_name=topic.var_field.display_name if topic.var_field else None,
|
||||
domain_name=topic.domain.display_name if topic.domain else None,
|
||||
source_keyword=keyword,
|
||||
)
|
||||
)
|
||||
|
||||
return matched
|
||||
|
||||
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
|
||||
person_id: Optional[str] = None
|
||||
|
||||
|
||||
class MatchedTopic(BaseModel):
|
||||
id: Optional[str] = None
|
||||
display_name: Optional[str] = None
|
||||
subfield_name: Optional[str] = None
|
||||
field_name: Optional[str] = None
|
||||
domain_name: Optional[str] = None
|
||||
source_keyword: Optional[str] = None
|
||||
|
||||
|
||||
class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
topics: List[str] = []
|
||||
keywords: List[str] = []
|
||||
topics: List[MatchedTopic] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
@@ -109,7 +109,7 @@ def _deactivate_organization_accounts(
|
||||
|
||||
def get_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
access_token: AccessTokenMetadata,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
@@ -145,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)
|
||||
@@ -164,7 +164,7 @@ def create_organization(
|
||||
|
||||
def update_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
access_token: AccessTokenMetadata,
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
@@ -191,7 +191,7 @@ def update_organization(
|
||||
|
||||
def delete_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
access_token: AccessTokenMetadata,
|
||||
organization_id: uuid.UUID,
|
||||
) -> None:
|
||||
_require_super_admin(access_token)
|
||||
|
||||
@@ -32,6 +32,7 @@ from inse.persons.model import (
|
||||
CustomAuthorsListResponse,
|
||||
CareerMetrics,
|
||||
)
|
||||
from inse.works.logic import enrich_topic_descriptions
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
@@ -728,6 +729,10 @@ async def advanced_search_persons(
|
||||
)
|
||||
results.append(custom_author)
|
||||
|
||||
await enrich_topic_descriptions(
|
||||
[topic for author in results for topic in author.topics or []]
|
||||
)
|
||||
|
||||
return CustomAuthorsListResponse(
|
||||
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
|
||||
)
|
||||
|
||||
@@ -12,3 +12,4 @@ class Tags(StrEnum):
|
||||
AUTH = "Auth"
|
||||
ACCOUNT = "Account"
|
||||
ORGANIZATION = "Organization"
|
||||
UNIVERSITY_RANKINGS = "University Rankings"
|
||||
|
||||
@@ -4,13 +4,12 @@
|
||||
Business logic for OpenAlex topics.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import asyncio
|
||||
from pydantic import ValidationError
|
||||
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
@@ -23,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import (
|
||||
AutocompleteResponseResultsInner,
|
||||
)
|
||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||
from inse.model import ESCluster
|
||||
from .search_client import OpenAlexTopicsClient
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from .search_client import TopicsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -40,15 +39,15 @@ async def list_topics(
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
client: TopicsSearchClient | None = None,
|
||||
) -> TopicsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
topics_client = client or TopicsSearchClient()
|
||||
|
||||
try:
|
||||
data = await openalex_client.list_topics(
|
||||
data = await topics_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
@@ -59,25 +58,24 @@ async def list_topics(
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex topics request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
except ValueError as exc:
|
||||
raise BadRequestException(str(exc)) from exc
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex topics Elasticsearch request failed.")
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
message="OpenAlex topics Elasticsearch request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
openalex_style_data = _elasticsearch_to_topics_response(
|
||||
data,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
group_by=group_by,
|
||||
)
|
||||
normalized_data = _normalize_topics_response(openalex_style_data)
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex topics response could not be parsed.")
|
||||
@@ -94,7 +92,7 @@ async def autocomplete_topics(
|
||||
field_id: str | None = None,
|
||||
subfield_id: str | None = None,
|
||||
limit: int = 10,
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
client: TopicsSearchClient | None = None,
|
||||
) -> AutocompleteResponse:
|
||||
filters = []
|
||||
if domain_id:
|
||||
@@ -153,6 +151,99 @@ async def autocomplete_topics(
|
||||
)
|
||||
|
||||
|
||||
def _elasticsearch_to_topics_response(
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
per_page: int,
|
||||
page: int | None,
|
||||
cursor: str | None,
|
||||
group_by: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Converts an Elasticsearch search response into the OpenAlex-style topics
|
||||
response expected by TopicsListResponse.
|
||||
|
||||
Elasticsearch response shape:
|
||||
|
||||
{
|
||||
"took": 12,
|
||||
"hits": {
|
||||
"total": {"value": 123},
|
||||
"hits": [
|
||||
{"_source": {...}, "sort": [...]}
|
||||
]
|
||||
},
|
||||
"aggregations": {...}
|
||||
}
|
||||
|
||||
OpenAlex-style response shape:
|
||||
|
||||
{
|
||||
"meta": {...},
|
||||
"results": [...],
|
||||
"group_by": [...]
|
||||
}
|
||||
"""
|
||||
hits_root = data.get("hits") or {}
|
||||
raw_hits = hits_root.get("hits") or []
|
||||
|
||||
total = hits_root.get("total")
|
||||
if isinstance(total, dict):
|
||||
count = total.get("value")
|
||||
else:
|
||||
count = total
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
for hit in raw_hits:
|
||||
if not isinstance(hit, dict):
|
||||
continue
|
||||
|
||||
source = hit.get("_source")
|
||||
if isinstance(source, dict):
|
||||
results.append(source)
|
||||
|
||||
groups = _extract_group_by_results(data) if group_by else []
|
||||
|
||||
meta = {
|
||||
"count": count,
|
||||
"db_response_time_ms": data.get("took"),
|
||||
"page": page if cursor is None else None,
|
||||
"per_page": per_page,
|
||||
"groups_count": len(groups) if group_by else None,
|
||||
"next_cursor": (data.get("meta") or {}).get("next_cursor"),
|
||||
"cost_usd": None,
|
||||
}
|
||||
|
||||
return {
|
||||
"meta": meta,
|
||||
"results": results,
|
||||
"group_by": groups,
|
||||
}
|
||||
|
||||
|
||||
def _extract_group_by_results(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
aggregations = data.get("aggregations") or {}
|
||||
group_by_agg = aggregations.get("group_by") or {}
|
||||
buckets = group_by_agg.get("buckets") or []
|
||||
|
||||
groups: list[dict[str, Any]] = []
|
||||
|
||||
for bucket in buckets:
|
||||
if not isinstance(bucket, dict):
|
||||
continue
|
||||
|
||||
key = bucket.get("key")
|
||||
groups.append(
|
||||
{
|
||||
"key": key,
|
||||
"key_display_name": bucket.get("key_as_string") or key,
|
||||
"count": bucket.get("doc_count"),
|
||||
}
|
||||
)
|
||||
|
||||
return groups
|
||||
|
||||
|
||||
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
normalized = deepcopy(data)
|
||||
|
||||
@@ -264,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None:
|
||||
return f"{text}T00:00:00Z"
|
||||
return text
|
||||
|
||||
|
||||
# Configuration for vector search similarity thresholds and boosts
|
||||
SIMILARITY_THRESHOLD = (
|
||||
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||
@@ -388,7 +478,7 @@ async def vector_search_topics(
|
||||
|
||||
try:
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||
@@ -458,7 +548,7 @@ async def vector_search_topics_batch(
|
||||
)
|
||||
tasks.append(
|
||||
elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -1,33 +1,200 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for OpenAlex topics.
|
||||
Elasticsearch search client for OpenAlex topics.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .. import config
|
||||
from inse.integrations.elasticsearch import search as elasticsearch_search
|
||||
|
||||
|
||||
class OpenAlexTopicsClient:
|
||||
class TopicsSearchClient:
|
||||
"""
|
||||
Search client for OpenAlex topics backed by Elasticsearch.
|
||||
|
||||
This replaces the old OpenAlex HTTP API client and uses the internal
|
||||
Elasticsearch wrapper instead.
|
||||
"""
|
||||
|
||||
DEFAULT_SEARCH_FIELDS = [
|
||||
"display_name^5",
|
||||
"description^3",
|
||||
"keywords",
|
||||
"domain.display_name^2",
|
||||
"field.display_name^2",
|
||||
"subfield.display_name^2",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
*,
|
||||
index: ESIndex | str | None = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
self.index = index or self._default_index()
|
||||
self.cluster = cluster
|
||||
|
||||
def list_topics_params(
|
||||
@staticmethod
|
||||
def _default_index() -> str:
|
||||
"""
|
||||
Resolve the OpenAlex topics index name.
|
||||
|
||||
Prefer a configured value if present, otherwise fall back to a sensible
|
||||
default string index name.
|
||||
"""
|
||||
return (
|
||||
ESIndex.OPENALEX_TOPICS.value
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _split_csv(value: str | None) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
return [part.strip() for part in value.split(",") if part.strip()]
|
||||
|
||||
@staticmethod
|
||||
def _encode_cursor(sort_values: list[Any]) -> str:
|
||||
raw = json.dumps(sort_values).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
@staticmethod
|
||||
def _decode_cursor(cursor: str | None) -> list[Any] | None:
|
||||
if not cursor or cursor == "*":
|
||||
return None
|
||||
|
||||
padding = "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(cursor + padding)
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
|
||||
@staticmethod
|
||||
def _parse_select(select: str | None) -> list[str] | None:
|
||||
fields = TopicsSearchClient._split_csv(select)
|
||||
return fields or None
|
||||
|
||||
@staticmethod
|
||||
def _parse_sort(sort: str | None) -> list[dict[str, Any]] | None:
|
||||
"""
|
||||
Parses OpenAlex-style sort syntax into Elasticsearch sort syntax.
|
||||
|
||||
Examples:
|
||||
"works_count:desc"
|
||||
"cited_by_count:desc,display_name:asc"
|
||||
"-works_count"
|
||||
"""
|
||||
parts = TopicsSearchClient._split_csv(sort)
|
||||
if not parts:
|
||||
return None
|
||||
|
||||
parsed: list[dict[str, Any]] = []
|
||||
|
||||
for part in parts:
|
||||
direction = "asc"
|
||||
field = part
|
||||
|
||||
if part.startswith("-"):
|
||||
direction = "desc"
|
||||
field = part[1:]
|
||||
elif ":" in part:
|
||||
field, direction = part.split(":", 1)
|
||||
field = field.strip()
|
||||
direction = direction.strip().lower()
|
||||
|
||||
if direction not in {"asc", "desc"}:
|
||||
direction = "asc"
|
||||
|
||||
if field in {"score", "_score", "relevance_score"}:
|
||||
parsed.append({"_score": {"order": direction}})
|
||||
else:
|
||||
parsed.append({field: {"order": direction, "missing": "_last"}})
|
||||
|
||||
return parsed
|
||||
|
||||
@staticmethod
|
||||
def _parse_filter_clause(expression: str) -> tuple[dict[str, Any] | None, bool]:
|
||||
"""
|
||||
Parses a single simple OpenAlex-style filter expression.
|
||||
|
||||
Supported examples:
|
||||
"works_count:>100"
|
||||
"works_count:>=100"
|
||||
"display_name:Physics"
|
||||
"ids.openalex:T123"
|
||||
"field.id:F1|F2"
|
||||
"is_active:true"
|
||||
"is_active:!true"
|
||||
|
||||
Returns:
|
||||
tuple[clause, is_negative]
|
||||
"""
|
||||
if ":" not in expression:
|
||||
return None, False
|
||||
|
||||
field, value = expression.split(":", 1)
|
||||
field = field.strip()
|
||||
value = value.strip()
|
||||
|
||||
if not field or not value:
|
||||
return None, False
|
||||
|
||||
is_negative = False
|
||||
if value.startswith("!"):
|
||||
is_negative = True
|
||||
value = value[1:].strip()
|
||||
|
||||
range_ops = {
|
||||
">=": "gte",
|
||||
"<=": "lte",
|
||||
">": "gt",
|
||||
"<": "lt",
|
||||
}
|
||||
|
||||
for prefix, op in range_ops.items():
|
||||
if value.startswith(prefix):
|
||||
range_value = value[len(prefix):].strip()
|
||||
return {"range": {field: {op: range_value}}}, is_negative
|
||||
|
||||
if "|" in value:
|
||||
values = [v.strip() for v in value.split("|") if v.strip()]
|
||||
return {"terms": {field: values}}, is_negative
|
||||
|
||||
lowered = value.lower()
|
||||
if lowered == "true":
|
||||
typed_value: Any = True
|
||||
elif lowered == "false":
|
||||
typed_value = False
|
||||
else:
|
||||
typed_value = value
|
||||
|
||||
return {"term": {field: typed_value}}, is_negative
|
||||
|
||||
@classmethod
|
||||
def _parse_filters(
|
||||
cls,
|
||||
filter: str | None,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
filter_clauses: list[dict[str, Any]] = []
|
||||
must_not_clauses: list[dict[str, Any]] = []
|
||||
|
||||
for expression in cls._split_csv(filter):
|
||||
clause, is_negative = cls._parse_filter_clause(expression)
|
||||
if clause is None:
|
||||
continue
|
||||
|
||||
if is_negative:
|
||||
must_not_clauses.append(clause)
|
||||
else:
|
||||
filter_clauses.append(clause)
|
||||
|
||||
return filter_clauses, must_not_clauses
|
||||
|
||||
def build_search_body(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -40,28 +207,118 @@ class OpenAlexTopicsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
"""
|
||||
Build the Elasticsearch search body from the previous OpenAlex-style API
|
||||
parameters.
|
||||
"""
|
||||
filter_clauses, must_not_clauses = self._parse_filters(filter)
|
||||
|
||||
must_clauses: list[dict[str, Any]] = []
|
||||
|
||||
if search:
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
must_clauses.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": search,
|
||||
"fields": self.DEFAULT_SEARCH_FIELDS,
|
||||
"type": "best_fields",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return params
|
||||
if must_clauses or filter_clauses or must_not_clauses:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": must_clauses or [{"match_all": {}}],
|
||||
"filter": filter_clauses,
|
||||
"must_not": must_not_clauses,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {"match_all": {}}
|
||||
|
||||
if sample is not None:
|
||||
query = {
|
||||
"function_score": {
|
||||
"query": query,
|
||||
"random_score": {},
|
||||
}
|
||||
}
|
||||
|
||||
size = sample if sample is not None else per_page
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"query": query,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
}
|
||||
|
||||
source = self._parse_select(select)
|
||||
if source is not None:
|
||||
body["_source"] = source
|
||||
|
||||
sort_clause = self._parse_sort(sort)
|
||||
if sort_clause is not None:
|
||||
body["sort"] = sort_clause
|
||||
|
||||
search_after = self._decode_cursor(cursor)
|
||||
if search_after is not None:
|
||||
body["search_after"] = search_after
|
||||
elif cursor is None and page is not None:
|
||||
body["from"] = max(page - 1, 0) * per_page
|
||||
|
||||
if group_by:
|
||||
body["size"] = 0
|
||||
body["aggs"] = {
|
||||
"group_by": {
|
||||
"terms": {
|
||||
"field": group_by,
|
||||
"size": per_page,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return body
|
||||
|
||||
async def search_topics(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
body = self.build_search_body(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
|
||||
result = await elasticsearch_search(
|
||||
index=self.index,
|
||||
body=body,
|
||||
cluster=self.cluster,
|
||||
)
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
last_sort = hits[-1].get("sort")
|
||||
if last_sort is not None:
|
||||
result.setdefault("meta", {})["next_cursor"] = self._encode_cursor(last_sort)
|
||||
|
||||
return result
|
||||
|
||||
async def list_topics(
|
||||
self,
|
||||
@@ -76,24 +333,17 @@ class OpenAlexTopicsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/topics",
|
||||
params=self.list_topics_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
"""
|
||||
Backwards-compatible alias for the old OpenAlex client method name.
|
||||
"""
|
||||
return await self.search_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
@@ -1,9 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -11,108 +9,144 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
class FakeTopicsSearchClient:
|
||||
def __init__(self, response: dict):
|
||||
self.response = response
|
||||
self.calls: list[dict] = []
|
||||
|
||||
async def list_topics(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||
client = FakeTopicsSearchClient(
|
||||
{
|
||||
"took": 12,
|
||||
"hits": {
|
||||
"total": {"value": 1, "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
"_id": "https://openalex.org/T12419",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": (
|
||||
"https://api.openalex.org/works?"
|
||||
"filter=topics.id:T12419"
|
||||
),
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_display_name": "Physical Sciences",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
"aggregations": {
|
||||
"group_by": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_as_string": "Physical Sciences",
|
||||
"doc_count": 1,
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_topics(search="machine learning", client=client)
|
||||
result = await logic.list_topics(
|
||||
search="machine learning",
|
||||
group_by="domain.id",
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert client.calls[0]["search"] == "machine learning"
|
||||
assert client.calls[0]["group_by"] == "domain.id"
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
|
||||
topic = result.results[0]
|
||||
assert topic.display_name == "Machine learning"
|
||||
assert topic.var_field.display_name == "Computer Science"
|
||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||
assert topic.domain.display_name == "Physical Sciences"
|
||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||
|
||||
assert result.group_by[0].key == "https://openalex.org/domains/4"
|
||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||
assert result.group_by[0].count == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
with pytest.raises(BadRequestException):
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
client = FakeTopicsSearchClient(
|
||||
{
|
||||
"took": "10",
|
||||
"hits": {
|
||||
"total": {"value": "1", "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
"_id": "123",
|
||||
"_source": {
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
},
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": "1"}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
"aggregations": {
|
||||
"group_by": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": True,
|
||||
"doc_count": "1",
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.list_topics(client=client)
|
||||
result = await logic.list_topics(group_by="domain.id", client=client)
|
||||
|
||||
topic = result.results[0]
|
||||
assert topic.id == "123"
|
||||
@@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_topics_returns_frontend_options():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert request.url.params["sort"] == "works_count:desc"
|
||||
assert request.url.params["per_page"] == "5"
|
||||
assert request.url.params["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
client = FakeTopicsSearchClient(
|
||||
{
|
||||
"took": 12,
|
||||
"hits": {
|
||||
"total": {"value": 1, "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
"_id": "https://openalex.org/T12419",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
}
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_topics(
|
||||
@@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options():
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert client.calls[0]["search"] == "machine learning"
|
||||
assert client.calls[0]["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert client.calls[0]["sort"] == "works_count:desc"
|
||||
assert client.calls[0]["per_page"] == 5
|
||||
assert client.calls[0]["page"] == 1
|
||||
assert client.calls[0]["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
assert len(result.results) == 1
|
||||
|
||||
option = result.results[0]
|
||||
assert option.id == "https://openalex.org/T12419"
|
||||
assert option.display_name == "Machine learning"
|
||||
@@ -190,4 +230,4 @@ async def test_autocomplete_topics_returns_frontend_options():
|
||||
assert option.works_count == 123
|
||||
assert option.cited_by_count == 456
|
||||
assert option.entity_type == "topic"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
@@ -1,7 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.topics.search_client import TopicsSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -9,10 +9,10 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_topics_params_include_openalex_query_parameters():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
def test_build_search_body_includes_openalex_query_parameters():
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
params = client.list_topics_params(
|
||||
body = client.build_search_body(
|
||||
search="machine learning",
|
||||
filter="domain.id:4,works_count:>1000",
|
||||
sort="works_count:desc",
|
||||
@@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters():
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert params == {
|
||||
"search": "machine learning",
|
||||
"filter": "domain.id:4,works_count:>1000",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "domain.id",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
assert body["query"] == {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": "machine learning",
|
||||
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||
"type": "best_fields",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
],
|
||||
"filter": [
|
||||
{"term": {"domain.id": "4"}},
|
||||
{"range": {"works_count": {"gt": "1000"}}},
|
||||
],
|
||||
"must_not": [],
|
||||
}
|
||||
}
|
||||
|
||||
assert body["_source"] == ["id", "display_name"]
|
||||
assert body["sort"] == [
|
||||
{"works_count": {"order": "desc", "missing": "_last"}}
|
||||
]
|
||||
|
||||
# group_by queries use aggregations and no regular hits
|
||||
assert body["size"] == 0
|
||||
assert body["from"] == 10
|
||||
assert body["track_total_hits"] is True
|
||||
assert body["aggs"] == {
|
||||
"group_by": {
|
||||
"terms": {
|
||||
"field": "domain.id",
|
||||
"size": 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_list_topics_params_prefers_cursor_over_page():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
def test_build_search_body_prefers_cursor_over_page():
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
params = client.list_topics_params(cursor="*", page=3)
|
||||
cursor = client._encode_cursor(["Machine learning", "https://openalex.org/T12419"])
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
body = client.build_search_body(
|
||||
cursor=cursor,
|
||||
page=3,
|
||||
per_page=25,
|
||||
)
|
||||
|
||||
assert body["search_after"] == [
|
||||
"Machine learning",
|
||||
"https://openalex.org/T12419",
|
||||
]
|
||||
assert "from" not in body
|
||||
|
||||
|
||||
def test_build_search_body_with_plain_cursor_star_does_not_use_page_offset():
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
body = client.build_search_body(
|
||||
cursor="*",
|
||||
page=3,
|
||||
per_page=25,
|
||||
)
|
||||
|
||||
assert "search_after" not in body
|
||||
assert "from" not in body
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/topics"
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
async def fake_elasticsearch_search(*, index, body, cluster):
|
||||
captured["index"] = index
|
||||
captured["body"] = body
|
||||
captured["cluster"] = cluster
|
||||
|
||||
return {
|
||||
"took": 3,
|
||||
"hits": {
|
||||
"total": {"value": 1, "relation": "eq"},
|
||||
"hits": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"_id": "https://openalex.org/T12419",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
},
|
||||
"sort": [1000, "https://openalex.org/T12419"],
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
monkeypatch.setattr(
|
||||
"inse.topics.search_client.elasticsearch_search",
|
||||
fake_elasticsearch_search,
|
||||
)
|
||||
|
||||
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||
|
||||
result = await client.list_topics(search="machine learning")
|
||||
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "Machine learning"
|
||||
assert captured["index"] == ESIndex.OPENALEX_TOPICS
|
||||
assert captured["cluster"] == ESCluster.NES
|
||||
|
||||
assert captured["body"]["query"]["bool"]["must"] == [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": "machine learning",
|
||||
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||
"type": "best_fields",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
]
|
||||
assert captured["body"]["size"] == 25
|
||||
assert captured["body"]["from"] == 0
|
||||
assert captured["body"]["track_total_hits"] is True
|
||||
|
||||
assert result["hits"]["total"]["value"] == 1
|
||||
assert result["hits"]["hits"][0]["_source"]["display_name"] == "Machine learning"
|
||||
assert result["meta"]["next_cursor"] is not None
|
||||
@@ -1,65 +1,228 @@
|
||||
import logging
|
||||
import datetime
|
||||
from typing import List, Dict, Any
|
||||
from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse
|
||||
from .model import UniversityTopicData, YearlyData, UniversityRanking, DashboardMetric, RankingResponse
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
START_YEAR = 2015
|
||||
END_YEAR = 2026
|
||||
START_YEAR = 2000
|
||||
END_YEAR = datetime.datetime.now().year - 1
|
||||
|
||||
async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
|
||||
async def resolve_topic(topic_query: str) -> Topic:
|
||||
"""Resolves a topic display name or ID using Elasticsearch with source whitelisting."""
|
||||
if topic_query.startswith("https://openalex.org/"):
|
||||
query = {"term": {"id": topic_query}}
|
||||
else:
|
||||
query = {"match_phrase": {"display_name": topic_query}}
|
||||
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query=query,
|
||||
size=1,
|
||||
source=["id", "display_name", "description", "works_count", "cited_by_count"],
|
||||
cluster="nes"
|
||||
)
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
return Topic.from_dict(hits[0]["_source"])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve topic in ES: %s", e)
|
||||
|
||||
return Topic(display_name=topic_query)
|
||||
|
||||
async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> RankingResponse:
|
||||
"""
|
||||
Fetches real data from Elasticsearch and computes metrics for the dashboard.
|
||||
"""
|
||||
topic_obj = await resolve_topic(topic_query)
|
||||
topic_name = topic_obj.display_name or topic_query
|
||||
|
||||
if topic_obj.id:
|
||||
topic_filter = {"term": {"topics.id.keyword": topic_obj.id}}
|
||||
else:
|
||||
topic_filter = {"match_phrase": {"topics.display_name": topic_name}}
|
||||
|
||||
query = {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match_phrase": {
|
||||
"topics.display_name": topic
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"geo.country_code": "DE"
|
||||
}
|
||||
}
|
||||
]
|
||||
"filter": [
|
||||
{"term": {"type": "education"}},
|
||||
{"term": {"geo.country_code": "DE"}},
|
||||
topic_filter
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Fetch top institutions for the topic by works_count
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=10,
|
||||
sort=[{"works_count": "desc"}],
|
||||
size=50,
|
||||
source=["id", "display_name", "topics"],
|
||||
cluster="nes"
|
||||
)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
timeseries: List[UniversityTopicData] = []
|
||||
candidates = []
|
||||
|
||||
for hit in hits:
|
||||
source = hit["_source"]
|
||||
# Map the counts_by_year from ES to our model
|
||||
# We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0
|
||||
es_counts = {c["year"]: c for c in source.get("counts_by_year", [])}
|
||||
inst_id = source.get("id")
|
||||
display_name = source.get("display_name", "Unknown")
|
||||
|
||||
# Extract topic-specific works count
|
||||
exact_topic_count = 0
|
||||
for t in source.get("topics", []):
|
||||
if t.get("display_name", "").lower() == topic_name.lower():
|
||||
exact_topic_count = t.get("count", 0)
|
||||
break
|
||||
|
||||
candidates.append({
|
||||
"id": inst_id,
|
||||
"display_name": display_name,
|
||||
"exact_topic_count": exact_topic_count
|
||||
})
|
||||
|
||||
# Sort in Python by exact topic count descending and take the top 10
|
||||
candidates.sort(key=lambda x: x["exact_topic_count"], reverse=True)
|
||||
top_10 = candidates[:10]
|
||||
|
||||
# Initialize timeseries map: inst_id -> year -> (publications, citations)
|
||||
years_range = list(range(START_YEAR, END_YEAR + 1))
|
||||
accumulated_data = {
|
||||
inst["id"]: {yr: (0, 0) for yr in years_range}
|
||||
for inst in top_10
|
||||
}
|
||||
|
||||
if top_10:
|
||||
# Build filter map for the single-pass aggregation query
|
||||
filters_map = {}
|
||||
for inst in top_10:
|
||||
inst_id = inst["id"]
|
||||
filters_map[inst_id] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.institutions.id": inst_id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Topic filter clause (using topic ID if resolved, otherwise matching display name keyword)
|
||||
topic_id = topic_obj.id
|
||||
if topic_id:
|
||||
topic_clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"term": {"topics.id": topic_id}}}},
|
||||
{"term": {"primary_topic.id": topic_id}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
else:
|
||||
topic_clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": topic_name}}}},
|
||||
{"match_phrase": {"primary_topic.display_name": topic_name}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
|
||||
# Construct single-pass ES query on openalex-works in Filter Context
|
||||
works_query = {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"range": {
|
||||
"publication_year": {
|
||||
"gte": START_YEAR,
|
||||
"lte": END_YEAR
|
||||
}
|
||||
}
|
||||
},
|
||||
topic_clause,
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": [inst["id"] for inst in top_10]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
aggregations = {
|
||||
"institutions_agg": {
|
||||
"filters": {
|
||||
"filters": filters_map
|
||||
},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years_range) * 2
|
||||
},
|
||||
"aggs": {
|
||||
"citations_sum": {
|
||||
"sum": {
|
||||
"field": "cited_by_count"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
works_res = await elasticsearch.search(
|
||||
index="openalex-works*",
|
||||
query=works_query,
|
||||
body={"aggs": aggregations},
|
||||
size=0,
|
||||
|
||||
cluster="nes"
|
||||
)
|
||||
|
||||
inst_buckets = works_res.get("aggregations", {}).get("institutions_agg", {}).get("buckets", {})
|
||||
for inst_id, inst_bucket in inst_buckets.items():
|
||||
year_buckets = inst_bucket.get("by_year", {}).get("buckets", [])
|
||||
for yr_bucket in year_buckets:
|
||||
yr = int(yr_bucket.get("key"))
|
||||
pubs = int(yr_bucket.get("doc_count", 0))
|
||||
cits = int(yr_bucket.get("citations_sum", {}).get("value", 0))
|
||||
if yr in years_range:
|
||||
accumulated_data[inst_id][yr] = (pubs, cits)
|
||||
except Exception as e:
|
||||
logger.error("Error executing ranking aggregations on openalex-works: %s", e)
|
||||
|
||||
# Map the accumulated results back into the timeseries response model
|
||||
timeseries: List[UniversityTopicData] = []
|
||||
inst_name_map = {inst["id"]: inst["display_name"] for inst in top_10}
|
||||
|
||||
for inst_id, year_dict in accumulated_data.items():
|
||||
yearly_data = []
|
||||
for year in range(START_YEAR, END_YEAR + 1):
|
||||
count_item = es_counts.get(year, {})
|
||||
for yr in years_range:
|
||||
pubs, cits = year_dict[yr]
|
||||
yearly_data.append(YearlyData(
|
||||
year=year,
|
||||
publications=count_item.get("works_count", 0),
|
||||
citations=count_item.get("cited_by_count", 0)
|
||||
year=yr,
|
||||
publications=pubs,
|
||||
citations=cits
|
||||
))
|
||||
|
||||
|
||||
timeseries.append(UniversityTopicData(
|
||||
university=source.get("display_name", "Unknown"),
|
||||
topic=topic,
|
||||
university=inst_name_map[inst_id],
|
||||
topic=topic_obj,
|
||||
yearly_data=yearly_data
|
||||
))
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Literal
|
||||
from typing import List, Literal, Dict, Optional
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology']
|
||||
DashboardMetric = Literal['publications', 'citations']
|
||||
|
||||
class YearlyData(BaseModel):
|
||||
@@ -11,7 +11,7 @@ class YearlyData(BaseModel):
|
||||
|
||||
class UniversityTopicData(BaseModel):
|
||||
university: str
|
||||
topic: ResearchTopic
|
||||
topic: Topic
|
||||
yearly_data: List[YearlyData]
|
||||
|
||||
class UniversityRanking(BaseModel):
|
||||
@@ -27,4 +27,37 @@ class RankingResponse(BaseModel):
|
||||
# Raw timeseries data for the ECharts line race
|
||||
timeseries: List[UniversityTopicData]
|
||||
# Computed metrics for the ranking table
|
||||
rankings: List[UniversityRanking]
|
||||
rankings: List[UniversityRanking]
|
||||
|
||||
# Trend Analysis Models
|
||||
class TopicYearlyData(BaseModel):
|
||||
year: int
|
||||
raw: int
|
||||
normalized: float
|
||||
cumulative: float
|
||||
institutions_count: int
|
||||
|
||||
class TrendSeries(BaseModel):
|
||||
entity_id: str
|
||||
entity_name: str
|
||||
entity_type: Literal['institution', 'country', 'region']
|
||||
country_code: Optional[str] = None
|
||||
# Map topic display name to its yearly data
|
||||
topic_data: Dict[str, List[TopicYearlyData]]
|
||||
|
||||
class TrendResponse(BaseModel):
|
||||
series: List[TrendSeries]
|
||||
years: List[int]
|
||||
location_mappings: Optional[Dict[str, List[str]]] = None
|
||||
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
|
||||
class TopInstitutionItem(DehydratedInstitution):
|
||||
works_count: Optional[int] = None
|
||||
exact_topic_count: Optional[int] = None
|
||||
|
||||
class AutocompleteLocationItem(BaseModel):
|
||||
id: str
|
||||
display_name: str
|
||||
code: str
|
||||
type: Literal['country', 'continent']
|
||||
@@ -1,23 +0,0 @@
|
||||
from fastapi import APIRouter, Query
|
||||
from . import service
|
||||
from .model import RankingResponse, ResearchTopic, DashboardMetric
|
||||
from inse.tags import Tags
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service/university-rankings",
|
||||
tags=[Tags.INSTITUTIONS]
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=RankingResponse,
|
||||
summary="Returns data for the University Ranking Dashboard."
|
||||
)
|
||||
async def get_rankings(
|
||||
topic: ResearchTopic = Query(
|
||||
...,
|
||||
description="Research topic (e.g., 'Artificial Intelligence')"
|
||||
),
|
||||
metric: DashboardMetric = Query("publications", description="Metric to rank by")
|
||||
):
|
||||
return await service.get_university_dashboard_data(topic, metric)
|
||||
@@ -1,6 +1,80 @@
|
||||
from . import logic
|
||||
from .model import RankingResponse, ResearchTopic, DashboardMetric
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
|
||||
"""Orchestrates data retrieval and computation for the dashboard."""
|
||||
return await logic.get_ranking_data(topic, metric)
|
||||
from inse.tags import Tags
|
||||
from . import logic, trend_logic
|
||||
from .model import (
|
||||
RankingResponse,
|
||||
DashboardMetric,
|
||||
TrendResponse,
|
||||
TopInstitutionItem,
|
||||
AutocompleteLocationItem
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service/university-rankings",
|
||||
tags=[Tags.UNIVERSITY_RANKINGS]
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=RankingResponse,
|
||||
summary="Returns data for the University Ranking Dashboard."
|
||||
)
|
||||
async def get_rankings(
|
||||
topic: str = Query(
|
||||
...,
|
||||
description="Research topic display name or OpenAlex ID (e.g., 'Artificial Intelligence')"
|
||||
),
|
||||
metric: DashboardMetric = Query("publications", description="Metric to rank by")
|
||||
):
|
||||
return await logic.get_ranking_data(topic, metric)
|
||||
|
||||
@router.get(
|
||||
"/trend",
|
||||
response_model=TrendResponse,
|
||||
summary="Returns timeseries publication data for compared institutions, countries and regions."
|
||||
)
|
||||
async def get_trend(
|
||||
topics: List[str] = Query(..., description="List of topics to analyze"),
|
||||
institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"),
|
||||
countries: Optional[List[str]] = Query(None, description="List of country codes"),
|
||||
regions: Optional[List[str]] = Query(None, description="List of region identifiers")
|
||||
):
|
||||
return await trend_logic.get_trend_data(
|
||||
topics=topics,
|
||||
institutions=institutions,
|
||||
countries=countries,
|
||||
regions=regions
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/top-institutions",
|
||||
response_model=List[TopInstitutionItem],
|
||||
summary="Returns top institutions filtered by country/region and sorted by topic-level publications count."
|
||||
)
|
||||
async def get_top_institutions(
|
||||
topic: str = Query(..., description="Research topic"),
|
||||
region: Optional[str] = Query(None, description="Region identifier (e.g. EU)"),
|
||||
country: Optional[str] = Query(None, description="Country code (e.g. DE)"),
|
||||
limit: int = Query(10, description="Max suggestions to return")
|
||||
):
|
||||
return await trend_logic.get_top_institutions_by_region(
|
||||
topic=topic,
|
||||
region=region,
|
||||
country=country,
|
||||
limit=limit
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/autocomplete-locations",
|
||||
response_model=List[AutocompleteLocationItem],
|
||||
summary="Returns country and continent options for autocomplete inputs."
|
||||
)
|
||||
async def get_autocomplete_locations(
|
||||
query: str = Query(..., description="Query text to search for countries/continents")
|
||||
):
|
||||
return await trend_logic.autocomplete_locations(query)
|
||||
@@ -0,0 +1,656 @@
|
||||
import logging
|
||||
import uuid
|
||||
import datetime
|
||||
from typing import List, Dict, Any, Optional
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
|
||||
from sqlmodel import Session
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.auth.model import AccessToken, Organization
|
||||
from .model import (
|
||||
TrendResponse,
|
||||
TrendSeries,
|
||||
TopicYearlyData,
|
||||
TopInstitutionItem,
|
||||
AutocompleteLocationItem
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default fallback institution: University of Duisburg-Essen
|
||||
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
||||
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
||||
|
||||
async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]:
|
||||
stripped = query.strip()
|
||||
if not stripped:
|
||||
return []
|
||||
|
||||
import asyncio
|
||||
|
||||
# Query countries index (Idea: Instead of wildcard: use alternative names?)
|
||||
country_query = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"case_insensitive": True
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"country_code": {
|
||||
"query": stripped.upper(),
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
|
||||
# Query continents index
|
||||
continent_query = {
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"case_insensitive": True
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
countries_res, continents_res = await asyncio.gather(
|
||||
elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_COUNTRIES),
|
||||
query=country_query,
|
||||
size=10,
|
||||
source=["id", "display_name", "country_code", "wikidata_id"],
|
||||
cluster="nes"
|
||||
),
|
||||
elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||
query=continent_query,
|
||||
size=5,
|
||||
source=["id", "display_name", "wikidata_id"],
|
||||
cluster="nes"
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Failed to autocomplete locations in ES: %s", e)
|
||||
return []
|
||||
|
||||
results = []
|
||||
|
||||
# Process continents
|
||||
for hit in continents_res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
code_val = source.get("wikidata_id") or source["id"].split("/")[-1]
|
||||
results.append(AutocompleteLocationItem(
|
||||
id=code_val,
|
||||
display_name=source["display_name"],
|
||||
code=code_val,
|
||||
type="continent"
|
||||
))
|
||||
|
||||
# Process countries
|
||||
for hit in countries_res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
results.append(AutocompleteLocationItem(
|
||||
id=source["country_code"],
|
||||
display_name=source["display_name"],
|
||||
code=source["country_code"],
|
||||
type="country"
|
||||
))
|
||||
|
||||
return results
|
||||
|
||||
|
||||
|
||||
async def get_top_institutions_by_region(
|
||||
topic: str,
|
||||
region: Optional[str] = None,
|
||||
country: Optional[str] = None,
|
||||
limit: int = 10
|
||||
) -> List[TopInstitutionItem]:
|
||||
"""
|
||||
Search top educational institutions by region or country based on publication counts
|
||||
for the specific topic, using a two-step Python-based sorting approach.
|
||||
"""
|
||||
country_codes = []
|
||||
if country:
|
||||
country_codes = [country.upper()]
|
||||
elif region:
|
||||
try:
|
||||
# Query openalex-continents index to resolve continent country codes dynamically
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||
query={
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"wikidata_id.keyword": region}},
|
||||
{"term": {"id": f"https://openalex.org/continents/{region}"}}
|
||||
]
|
||||
}
|
||||
},
|
||||
size=1,
|
||||
source=["countries"],
|
||||
cluster="nes"
|
||||
)
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
source = hits[0]["_source"]
|
||||
country_codes = [
|
||||
c["id"].split("/")[-1].upper() for c in source.get("countries", [])
|
||||
]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve continent countries in get_top_institutions_by_region: %s", e)
|
||||
|
||||
# Resolve the topic to get the exact ID/display name
|
||||
topic_filter = {"match_phrase": {"topics.display_name": topic}}
|
||||
try:
|
||||
topic_res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"match_phrase": {"display_name": topic}},
|
||||
size=1,
|
||||
source=["id", "display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
hits = topic_res.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
source = hits[0]["_source"]
|
||||
topic_id = source["id"]
|
||||
topic_filter = {"term": {"topics.id.keyword": topic_id}}
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve topic in get_top_institutions_by_region: %s", e)
|
||||
|
||||
# Query openalex-institutions for educational entities matching country and topic
|
||||
must_clauses: List[Dict[str, Any]] = [
|
||||
{"term": {"type": "education"}},
|
||||
topic_filter
|
||||
]
|
||||
|
||||
if country_codes:
|
||||
must_clauses.append({"terms": {"geo.country_code": country_codes}})
|
||||
|
||||
query = {"bool": {"filter": must_clauses}}
|
||||
|
||||
# Fetch top 50 by overall works count to cover a good pool of institutions
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||
query=query,
|
||||
size=50,
|
||||
source=["id", "display_name", "country_code", "works_count", "topics"],
|
||||
sort=[{"works_count": "desc"}],
|
||||
cluster="nes"
|
||||
)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
candidates = []
|
||||
|
||||
for hit in hits:
|
||||
source = hit["_source"]
|
||||
inst_id = source.get("id")
|
||||
display_name = source.get("display_name", "Unknown")
|
||||
country_code = source.get("country_code")
|
||||
works_count = source.get("works_count")
|
||||
|
||||
# Extract exact count for the selected topic
|
||||
exact_topic_count = 0
|
||||
for t in source.get("topics", []):
|
||||
if t.get("display_name", "").lower() == topic.lower():
|
||||
exact_topic_count = t.get("count", 0)
|
||||
break
|
||||
|
||||
candidates.append(TopInstitutionItem(
|
||||
id=inst_id,
|
||||
display_name=display_name,
|
||||
country_code=country_code,
|
||||
works_count=works_count,
|
||||
exact_topic_count=exact_topic_count
|
||||
))
|
||||
|
||||
# Sort candidates by exact_topic_count descending
|
||||
candidates.sort(key=lambda x: x.exact_topic_count or 0, reverse=True)
|
||||
|
||||
return candidates[:limit]
|
||||
|
||||
async def get_trend_data(
|
||||
topics: List[str],
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None
|
||||
) -> TrendResponse:
|
||||
"""
|
||||
Traverses the openalex-works index to retrieve yearly contributions of selected/top
|
||||
institutions, countries, and regions across multiple topics.
|
||||
"""
|
||||
if not topics:
|
||||
return TrendResponse(series=[], years=[])
|
||||
|
||||
import asyncio
|
||||
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
# Resolve primary institution (default University of Duisburg-Essen for everyone)
|
||||
primary_inst_id = DEFAULT_INSTITUTION_ID
|
||||
primary_inst_name = DEFAULT_INSTITUTION_NAME
|
||||
|
||||
# Initialize institutions list and ensure primary is included
|
||||
query_institutions = []
|
||||
if institutions:
|
||||
query_institutions = [i.strip() for i in institutions]
|
||||
if primary_inst_id not in query_institutions:
|
||||
query_institutions.insert(0, primary_inst_id)
|
||||
|
||||
# Prepare lists of countries and regions dynamically
|
||||
query_countries = countries or []
|
||||
query_regions = regions or []
|
||||
|
||||
clean_countries = [c.strip().upper() for c in query_countries]
|
||||
clean_regions = [r.strip() for r in query_regions]
|
||||
ids_to_resolve = list(set(query_institutions))
|
||||
|
||||
# Define concurrent metadata lookups
|
||||
async def fetch_institutions():
|
||||
names = {primary_inst_id: primary_inst_name}
|
||||
codes = {}
|
||||
if not ids_to_resolve:
|
||||
return names, codes
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||
query={"terms": {"id": ids_to_resolve}},
|
||||
size=len(ids_to_resolve),
|
||||
source=["id", "display_name", "country_code"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
names[source["id"]] = source.get("display_name", source["id"])
|
||||
codes[source["id"]] = source.get("country_code", "")
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve institution details from ES: %s", e)
|
||||
return names, codes
|
||||
|
||||
async def fetch_countries():
|
||||
names = {}
|
||||
if not clean_countries:
|
||||
return names
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_COUNTRIES),
|
||||
query={"terms": {"country_code": clean_countries}},
|
||||
size=len(clean_countries),
|
||||
source=["country_code", "display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
names[source["country_code"]] = source["display_name"]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve country names from ES: %s", e)
|
||||
return names
|
||||
|
||||
async def fetch_continents():
|
||||
names = {}
|
||||
ccodes = {}
|
||||
if not clean_regions:
|
||||
return names, ccodes
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||
query={
|
||||
"bool": {
|
||||
"should": [
|
||||
{"terms": {"wikidata_id.keyword": clean_regions}},
|
||||
{"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}}
|
||||
]
|
||||
}
|
||||
},
|
||||
size=len(clean_regions),
|
||||
source=["id", "display_name", "wikidata_id", "countries"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
c_code = source.get("wikidata_id") or source["id"].split("/")[-1]
|
||||
names[c_code] = source["display_name"]
|
||||
ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve continent names from ES: %s", e)
|
||||
return names, ccodes
|
||||
|
||||
async def fetch_topics():
|
||||
t_ids = {}
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}},
|
||||
size=len(topics) * 2,
|
||||
source=["id", "display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
for t in topics:
|
||||
if t.lower() in source["display_name"].lower():
|
||||
t_ids[t] = source["id"]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve topic IDs from ES: %s", e)
|
||||
return t_ids
|
||||
|
||||
# Execute all 4 queries concurrently
|
||||
(
|
||||
(resolved_names, resolved_country_codes),
|
||||
resolved_country_names,
|
||||
(resolved_continent_names, continent_country_codes),
|
||||
resolved_topic_ids
|
||||
) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics())
|
||||
|
||||
location_mappings = continent_country_codes.copy()
|
||||
|
||||
# Map of filters inside our Elasticsearch aggregation
|
||||
filters_map: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
# 1. Institution Filters
|
||||
for inst_id in query_institutions:
|
||||
filters_map[f"inst_{inst_id}"] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.institutions.id": inst_id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 2. Country Filters
|
||||
for cc in clean_countries:
|
||||
filters_map[f"country_{cc}"] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.institutions.country_code": cc
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 3. Continent/Region Filters
|
||||
for r_code, member_ccs in continent_country_codes.items():
|
||||
if member_ccs:
|
||||
filters_map[f"region_{r_code}"] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.country_code": member_ccs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# If no entities specified, return empty
|
||||
if not filters_map:
|
||||
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
|
||||
|
||||
# We will accumulate results in a nested structure: entity_key -> topic -> year -> (count, inst_count)
|
||||
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = {
|
||||
key: {t: {yr: (0, 1) for yr in years_range} for t in topics}
|
||||
for key in filters_map
|
||||
}
|
||||
|
||||
# Build topic matching clauses and filters
|
||||
topic_clauses = []
|
||||
topic_filters = {}
|
||||
for t in topics:
|
||||
tid = resolved_topic_ids.get(t)
|
||||
if tid:
|
||||
clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}},
|
||||
{"term": {"primary_topic.id": tid}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
else:
|
||||
clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}},
|
||||
{"match_phrase": {"primary_topic.display_name": t}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
topic_clauses.append(clause)
|
||||
topic_filters[t] = clause
|
||||
|
||||
# Build query-level entity filters to optimize search performance
|
||||
entity_should_clauses = []
|
||||
if query_institutions:
|
||||
entity_should_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": query_institutions
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
if clean_countries:
|
||||
entity_should_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.country_code": clean_countries
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
all_continent_countries = []
|
||||
for member_ccs in continent_country_codes.values():
|
||||
all_continent_countries.extend(member_ccs)
|
||||
if all_continent_countries:
|
||||
entity_should_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.country_code": list(set(all_continent_countries))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
# Construct the single-pass Elasticsearch query
|
||||
filter_clauses = [
|
||||
{
|
||||
"range": {
|
||||
"publication_year": {
|
||||
"gte": start_year,
|
||||
"lte": end_year
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"bool": {
|
||||
"should": topic_clauses,
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
if entity_should_clauses:
|
||||
filter_clauses.append({
|
||||
"bool": {
|
||||
"should": entity_should_clauses,
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
})
|
||||
|
||||
query = {
|
||||
"bool": {
|
||||
"filter": filter_clauses
|
||||
}
|
||||
}
|
||||
|
||||
# Build two-layer nested aggregations (topics -> entities -> publication_year)
|
||||
aggregations = {
|
||||
"topics_agg": {
|
||||
"filters": {
|
||||
"filters": topic_filters
|
||||
},
|
||||
"aggs": {
|
||||
"entities_agg": {
|
||||
"filters": {
|
||||
"filters": filters_map
|
||||
},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years_range) * 2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=f"{str(ESIndex.OPENALEX_WORKS)}*",
|
||||
query=query,
|
||||
body={"aggs": aggregations},
|
||||
size=0,
|
||||
cluster="nes"
|
||||
)
|
||||
|
||||
topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {})
|
||||
for t_name, t_bucket in topics_buckets.items():
|
||||
entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {})
|
||||
for entity_key, e_bucket in entities_buckets.items():
|
||||
year_buckets = e_bucket.get("by_year", {}).get("buckets", [])
|
||||
for yr_bucket in year_buckets:
|
||||
yr = int(yr_bucket.get("key"))
|
||||
count = int(yr_bucket.get("doc_count", 0))
|
||||
inst_count = 1
|
||||
if yr in years_range:
|
||||
accumulated_data[entity_key][t_name][yr] = (count, inst_count)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Error executing single-pass Elasticsearch query: %s", e)
|
||||
|
||||
# Construct lists of raw counts and S-Curves for all series to normalize in parallel
|
||||
series_keys = []
|
||||
raw_lists = []
|
||||
cumsum_lists = []
|
||||
inst_counts_map = {}
|
||||
|
||||
for entity_key, topic_dict in accumulated_data.items():
|
||||
for topic, year_dict in topic_dict.items():
|
||||
raw_counts = []
|
||||
inst_counts = []
|
||||
for yr in years_range:
|
||||
count, inst_count = year_dict[yr]
|
||||
raw_counts.append(count)
|
||||
inst_counts.append(inst_count)
|
||||
|
||||
cumulative_counts = list(np.cumsum(raw_counts))
|
||||
|
||||
series_keys.append((entity_key, topic))
|
||||
raw_lists.append(raw_counts)
|
||||
cumsum_lists.append(cumulative_counts)
|
||||
inst_counts_map[(entity_key, topic)] = inst_counts
|
||||
|
||||
normalized_lookup = {}
|
||||
if raw_lists:
|
||||
# Construct matrices of shape (n_years, n_series)
|
||||
raw_matrix = np.array(raw_lists, dtype=float).T
|
||||
cumsum_matrix = np.array(cumsum_lists, dtype=float).T
|
||||
|
||||
# Batch normalize columns in parallel using MinMaxScaler
|
||||
scaler_raw = MinMaxScaler()
|
||||
normalized_matrix = scaler_raw.fit_transform(raw_matrix)
|
||||
|
||||
scaler_cumsum = MinMaxScaler()
|
||||
normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix)
|
||||
|
||||
# Transpose back to lists of shape (n_series, n_years)
|
||||
normalized_lists = normalized_matrix.T.tolist()
|
||||
normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist()
|
||||
|
||||
for idx, (entity_key, topic) in enumerate(series_keys):
|
||||
normalized_lookup[(entity_key, topic)] = {
|
||||
"normalized": normalized_lists[idx],
|
||||
"cumulative": normalized_cumsum_lists[idx]
|
||||
}
|
||||
|
||||
# Process and build TrendSeries list
|
||||
series_list: List[TrendSeries] = []
|
||||
|
||||
for entity_key, topic_dict in accumulated_data.items():
|
||||
# Resolve details for this entity
|
||||
if entity_key.startswith("inst_"):
|
||||
entity_id = entity_key[len("inst_"):]
|
||||
entity_name = resolved_names.get(entity_id, entity_id)
|
||||
entity_type = "institution"
|
||||
elif entity_key.startswith("country_"):
|
||||
entity_id = entity_key[len("country_"):]
|
||||
entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}")
|
||||
entity_type = "country"
|
||||
elif entity_key.startswith("region_"):
|
||||
entity_id = entity_key[len("region_"):]
|
||||
entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}")
|
||||
entity_type = "region"
|
||||
else:
|
||||
continue
|
||||
|
||||
topic_data_map: Dict[str, List[TopicYearlyData]] = {}
|
||||
|
||||
for topic, year_dict in topic_dict.items():
|
||||
yearly_data_items: List[TopicYearlyData] = []
|
||||
|
||||
lookup = normalized_lookup.get((entity_key, topic), {})
|
||||
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||
inst_counts = inst_counts_map.get((entity_key, topic), [1] * len(years_range))
|
||||
|
||||
for idx, yr in enumerate(years_range):
|
||||
count, _ = year_dict[yr]
|
||||
yearly_data_items.append(TopicYearlyData(
|
||||
year=yr,
|
||||
raw=count,
|
||||
normalized=norm_vals[idx],
|
||||
cumulative=cum_vals[idx],
|
||||
institutions_count=inst_counts[idx]
|
||||
))
|
||||
|
||||
topic_data_map[topic] = yearly_data_items
|
||||
|
||||
series_list.append(TrendSeries(
|
||||
entity_id=entity_id,
|
||||
entity_name=entity_name,
|
||||
entity_type=entity_type,
|
||||
country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None,
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)
|
||||
|
||||
@@ -55,6 +55,7 @@ async def get_author_works(
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
sort: str = "year",
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> WorkPage:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
@@ -68,9 +69,11 @@ async def get_author_works(
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
sort=sort,
|
||||
)
|
||||
|
||||
elements, total = _parse_full_work_search_response(data)
|
||||
await _enrich_work_topic_descriptions(elements)
|
||||
offset = (page - 1) * size
|
||||
last_page = offset + len(elements) >= total
|
||||
|
||||
@@ -166,6 +169,15 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
"primary_topics": {
|
||||
"terms": {"field": "primary_topic.id", "size": 1000},
|
||||
},
|
||||
"all_topics": {
|
||||
"nested": {"path": "topics"},
|
||||
"aggs": {
|
||||
"topic_ids": {
|
||||
"terms": {"field": "topics.id", "size": 1000},
|
||||
"aggs": {"works": {"reverse_nested": {}}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -180,10 +192,25 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
aggregations = response.get("aggregations", {})
|
||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||
topic_buckets = (
|
||||
aggregations.get("all_topics", {}).get("topic_ids", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
broad_counts = {
|
||||
bucket["key"]: bucket.get("works", {}).get("doc_count", bucket["doc_count"])
|
||||
for bucket in topic_buckets
|
||||
}
|
||||
|
||||
|
||||
counts = []
|
||||
for bucket in buckets:
|
||||
counts.append({"id": bucket["key"], "count": bucket["doc_count"]})
|
||||
topic_id = bucket["key"]
|
||||
counts.append(
|
||||
{
|
||||
"id": topic_id,
|
||||
"count": max(broad_counts.get(topic_id, 0), bucket["doc_count"]),
|
||||
}
|
||||
)
|
||||
|
||||
return counts
|
||||
|
||||
@@ -202,9 +229,44 @@ async def get_work(
|
||||
elements, _ = _parse_full_work_search_response(response_by_title)
|
||||
if not elements:
|
||||
return None
|
||||
await _enrich_work_topic_descriptions(elements[:1])
|
||||
return elements[0]
|
||||
|
||||
|
||||
async def enrich_topic_descriptions(topics: List) -> None:
|
||||
"""Batch-fill missing descriptions on dehydrated topics.
|
||||
|
||||
OpenAlex work and author documents carry dehydrated topics without a
|
||||
description, so we batch-load the details from the openalex-topics index.
|
||||
"""
|
||||
pending = [topic for topic in topics if topic.id and not topic.description]
|
||||
|
||||
if not pending:
|
||||
return
|
||||
|
||||
details = await _get_topic_details(list({topic.id for topic in pending}))
|
||||
|
||||
if not details:
|
||||
return
|
||||
|
||||
for topic in pending:
|
||||
info = details.get(topic.id)
|
||||
if info:
|
||||
topic.description = info.get("description")
|
||||
|
||||
|
||||
async def _enrich_work_topic_descriptions(works: List[Work]) -> None:
|
||||
topics = []
|
||||
|
||||
for work in works:
|
||||
topics.extend(work.topics or [])
|
||||
|
||||
if work.primary_topic:
|
||||
topics.append(work.primary_topic)
|
||||
|
||||
await enrich_topic_descriptions(topics)
|
||||
|
||||
|
||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
if not topic_ids:
|
||||
return {}
|
||||
@@ -869,6 +931,7 @@ async def _search_author_works_data(
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
sort: str = "year",
|
||||
) -> dict:
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
@@ -879,6 +942,7 @@ async def _search_author_works_data(
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
sort=sort,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
Pydantic models for publication works.
|
||||
"""
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
|
||||
@@ -41,3 +42,35 @@ class WorkPage(BaseModel):
|
||||
class WorkList(BaseModel):
|
||||
elements: List[Work] = Field(default_factory=list, description="All works.")
|
||||
total: int = Field(default=0, description="The total number of works.")
|
||||
|
||||
|
||||
class WorkPurpose(StrEnum):
|
||||
"""Represents the purpose of a work. Either a foundation work or an application work."""
|
||||
|
||||
FOUNDATION = "Foundation"
|
||||
APPLICATION = "Application"
|
||||
|
||||
|
||||
class SpecificWorkPurpose(BaseModel):
|
||||
"""Represents the purpose of a specific work, including its ID, purpose, and optional reasoning."""
|
||||
|
||||
raw_oa_work_id: str = Field(description="The raw OpenAlex work id.")
|
||||
publication_year: Optional[int] = Field(
|
||||
default=None, description="The publication year of the work."
|
||||
)
|
||||
purpose: WorkPurpose = Field(description="The purpose of the work.")
|
||||
reasoning: Optional[str] = Field(
|
||||
default=None, description="The reasoning behind the purpose determination."
|
||||
)
|
||||
|
||||
|
||||
class AuthorWorkPurposes(BaseModel):
|
||||
"""Represents the purposes of an author, including their ID and a list of specific work purposes."""
|
||||
|
||||
raw_oa_author_id: str = Field(description="The raw OpenAlex author id.")
|
||||
total: int = Field(
|
||||
default=0, description="The total number of works for the author."
|
||||
)
|
||||
purposes: List[SpecificWorkPurpose] = Field(
|
||||
default_factory=list, description="The list of specific work purposes."
|
||||
)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Path
|
||||
|
||||
from inse.tags import Tags
|
||||
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose
|
||||
|
||||
from inse.works import purpose_service
|
||||
|
||||
WORKS_PREFIX = "/api/purpose"
|
||||
|
||||
router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_work_id}/purpose",
|
||||
operation_id="getWorkPurpose",
|
||||
summary="Returns the purpose of a work based on its ID.",
|
||||
)
|
||||
async def get_work_purpose(
|
||||
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
|
||||
) -> SpecificWorkPurpose:
|
||||
return await purpose_service.get_work_purpose(raw_oa_work_id)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_author_id}/purposes",
|
||||
operation_id="getAuthorWorkPurposes",
|
||||
summary="Returns the purposes of an author based on their ID.",
|
||||
)
|
||||
async def get_author_work_purposes(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
|
||||
) -> AuthorWorkPurposes:
|
||||
return await purpose_service.get_author_work_purposes(raw_oa_author_id)
|
||||
@@ -0,0 +1,101 @@
|
||||
import logging
|
||||
import random
|
||||
from typing import List
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
|
||||
raw_oa_work_id = raw_oa_work_id.strip().upper()
|
||||
|
||||
response = await elasticsearch.get(
|
||||
index=ESIndex.OPENALEX_WORKS,
|
||||
doc_id=raw_oa_work_id,
|
||||
source=["title", "abstract"],
|
||||
)
|
||||
|
||||
logger.debug(f"Elasticsearch response for work id {raw_oa_work_id}: {response}")
|
||||
|
||||
source = response.get("_source", {})
|
||||
if not source:
|
||||
raise NotFoundException(f"Work with id {raw_oa_work_id} not found.")
|
||||
|
||||
logger.debug(f"Found work source for id {raw_oa_work_id}: {source}")
|
||||
|
||||
return SpecificWorkPurpose(
|
||||
raw_oa_work_id=raw_oa_work_id,
|
||||
publication_year=source.get("publication_year"),
|
||||
purpose=WorkPurpose.FOUNDATION, # TODO: Replace with actual purpose determination logic
|
||||
reasoning="This is a placeholder reasoning for the purpose determination.",
|
||||
)
|
||||
|
||||
|
||||
async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
|
||||
raw_oa_author_id = raw_oa_author_id.strip().upper()
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_WORKS,
|
||||
source=["id", "publication_year"],
|
||||
query={
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
size=10000,
|
||||
)
|
||||
|
||||
logger.debug(f"Elasticsearch response for author id {raw_oa_author_id}: {response}")
|
||||
|
||||
purposes: List[SpecificWorkPurpose] = []
|
||||
|
||||
# TODO: implement actual retrieval of previously determined purposes for the author's works
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
work_id = source.get("id")
|
||||
publication_year = source.get("publication_year")
|
||||
if work_id:
|
||||
# TODO: Remove random based purpose assignment
|
||||
if random.choice([True, False]):
|
||||
purpose = SpecificWorkPurpose(
|
||||
raw_oa_work_id=work_id,
|
||||
publication_year=publication_year,
|
||||
purpose=WorkPurpose.FOUNDATION,
|
||||
reasoning=f"Placeholder reasoning for work {work_id}.",
|
||||
)
|
||||
else:
|
||||
purpose = SpecificWorkPurpose(
|
||||
raw_oa_work_id=work_id,
|
||||
publication_year=publication_year,
|
||||
purpose=WorkPurpose.APPLICATION,
|
||||
reasoning=f"Placeholder reasoning for work {work_id}.",
|
||||
)
|
||||
|
||||
purposes.append(purpose)
|
||||
else:
|
||||
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
|
||||
|
||||
return AuthorWorkPurposes(
|
||||
raw_oa_author_id=raw_oa_author_id, total=total_hits, purposes=purposes
|
||||
)
|
||||
@@ -35,6 +35,7 @@ class OpenAlexWorksSearchClient:
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
sort: str = "year",
|
||||
) -> dict[str, Any]:
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
filters = self._work_filters(
|
||||
@@ -73,19 +74,27 @@ class OpenAlexWorksSearchClient:
|
||||
},
|
||||
},
|
||||
})
|
||||
if sort == "citations":
|
||||
sort_clauses = [
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
]
|
||||
else:
|
||||
sort_clauses = [
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
]
|
||||
return {
|
||||
"from": (page - 1) * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": must_clauses,
|
||||
"filter": filters,
|
||||
},
|
||||
},
|
||||
"sort": [
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
"sort": sort_clauses,
|
||||
}
|
||||
|
||||
def _work_filters(
|
||||
@@ -129,6 +138,7 @@ class OpenAlexWorksSearchClient:
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
sort: str = "year",
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
@@ -142,6 +152,7 @@ class OpenAlexWorksSearchClient:
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
sort=sort,
|
||||
)
|
||||
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
REST API for publication works.
|
||||
"""
|
||||
|
||||
from typing import Annotated, Optional
|
||||
from typing import Annotated, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Path
|
||||
@@ -54,6 +54,10 @@ async def get_author_works(
|
||||
list[str] | None,
|
||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||
] = None,
|
||||
sort: Annotated[
|
||||
Literal["year", "citations"],
|
||||
Query(description="Sort order: by publication year or by citation count."),
|
||||
] = "year",
|
||||
):
|
||||
return await logic.get_author_works(
|
||||
author_id,
|
||||
@@ -64,6 +68,7 @@ async def get_author_works(
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
sort=sort,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,28 @@ def test_author_works_query_searches_authorship_author_id():
|
||||
assert query["query"]["bool"]["filter"] == []
|
||||
|
||||
|
||||
def test_author_works_query_sorts_by_year_by_default():
|
||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||
|
||||
query = client.author_works_query("A5023888391", page=1, size=20)
|
||||
|
||||
assert query["sort"] == [
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
]
|
||||
|
||||
|
||||
def test_author_works_query_sorts_by_citations():
|
||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||
|
||||
query = client.author_works_query("A5023888391", page=1, size=20, sort="citations")
|
||||
|
||||
assert query["sort"] == [
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
]
|
||||
|
||||
|
||||
def test_author_works_query_adds_publication_filters():
|
||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||
|
||||
|
||||
@@ -1195,6 +1195,11 @@ Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-works/_mapping
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
@@ -19,4 +19,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ api/personNetwork.service.ts
|
||||
api/persons.service.ts
|
||||
api/projects.service.ts
|
||||
api/topics.service.ts
|
||||
api/universityRankings.service.ts
|
||||
api/works.service.ts
|
||||
configuration.ts
|
||||
encoder.ts
|
||||
@@ -35,9 +36,11 @@ model/authorNetworkNode.ts
|
||||
model/authorParsedLongestName.ts
|
||||
model/authorPositionCount.ts
|
||||
model/authorSummaryStats.ts
|
||||
model/authorWorkPurposes.ts
|
||||
model/authorsFilterProperties.ts
|
||||
model/authorsListResponse.ts
|
||||
model/authorship.ts
|
||||
model/autocompleteLocationItem.ts
|
||||
model/autocompleteResponse.ts
|
||||
model/autocompleteResponseMeta.ts
|
||||
model/autocompleteResponseResultsInner.ts
|
||||
@@ -46,6 +49,8 @@ model/bodyChangePassword.ts
|
||||
model/bodyGetAccessToken.ts
|
||||
model/bodyLogin.ts
|
||||
model/bodyRequestOtk.ts
|
||||
model/bodyRequestPasswordReset.ts
|
||||
model/bodyResetPassword.ts
|
||||
model/bundProject.ts
|
||||
model/bundProjectDetails.ts
|
||||
model/bundProjectPage.ts
|
||||
@@ -113,7 +118,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
|
||||
@@ -138,6 +143,7 @@ model/loginResponse.ts
|
||||
model/longitude.ts
|
||||
model/matchedAuthor.ts
|
||||
model/matchedOfficer.ts
|
||||
model/matchedTopic.ts
|
||||
model/mentionedPerson.ts
|
||||
model/meta.ts
|
||||
model/model2YrMeanCitedness.ts
|
||||
@@ -149,6 +155,7 @@ model/openAccess.ts
|
||||
model/orgPatentEntry.ts
|
||||
model/orgPatentsResponse.ts
|
||||
model/organizationPage.ts
|
||||
model/otkResponse.ts
|
||||
model/patentEntry.ts
|
||||
model/patentsByAuthorResponse.ts
|
||||
model/patentsByInstitutionResponse.ts
|
||||
@@ -160,20 +167,24 @@ model/publicationDetailByFunder.ts
|
||||
model/publicationIdsByAuthorPosition.ts
|
||||
model/publicationsByAuthorResponse.ts
|
||||
model/rankingResponse.ts
|
||||
model/refreshToken.ts
|
||||
model/score.ts
|
||||
model/sortDirection.ts
|
||||
model/specificWorkPurpose.ts
|
||||
model/tokenType.ts
|
||||
model/topInstitutionItem.ts
|
||||
model/topic.ts
|
||||
model/topicCount.ts
|
||||
model/topicDomain.ts
|
||||
model/topicField.ts
|
||||
model/topicIds.ts
|
||||
model/topicSubfield.ts
|
||||
model/topicYearlyData.ts
|
||||
model/topics.ts
|
||||
model/topicsByTime.ts
|
||||
model/topicsByYear.ts
|
||||
model/topicsListResponse.ts
|
||||
model/trendResponse.ts
|
||||
model/trendSeries.ts
|
||||
model/universityRanking.ts
|
||||
model/universityTopicData.ts
|
||||
model/updateAccountRequest.ts
|
||||
@@ -193,6 +204,7 @@ model/workKeyword.ts
|
||||
model/workMeshInner.ts
|
||||
model/workNetworkNode.ts
|
||||
model/workPage.ts
|
||||
model/workPurpose.ts
|
||||
model/workSustainableDevelopmentGoalsInner.ts
|
||||
model/workTopic.ts
|
||||
model/workTopicDomain.ts
|
||||
|
||||
@@ -24,21 +24,8 @@ export * from './projects.service';
|
||||
import { ProjectsService } from './projects.service';
|
||||
export * from './topics.service';
|
||||
import { TopicsService } from './topics.service';
|
||||
export * from './universityRankings.service';
|
||||
import { UniversityRankingsService } from './universityRankings.service';
|
||||
export * from './works.service';
|
||||
import { WorksService } from './works.service';
|
||||
export const APIS = [
|
||||
AuthService,
|
||||
CompanyConnectionsService,
|
||||
FundingService,
|
||||
INSEServiceService,
|
||||
InstitutionsService,
|
||||
KeywordsService,
|
||||
NewsService,
|
||||
OrganizationService,
|
||||
PatentsService,
|
||||
PersonNetworkService,
|
||||
PersonsService,
|
||||
ProjectsService,
|
||||
TopicsService,
|
||||
WorksService,
|
||||
];
|
||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService];
|
||||
|
||||
@@ -33,6 +33,10 @@ import { BodyLogin } from '../model/bodyLogin';
|
||||
// @ts-ignore
|
||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||
// @ts-ignore
|
||||
import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset';
|
||||
// @ts-ignore
|
||||
import { BodyResetPassword } from '../model/bodyResetPassword';
|
||||
// @ts-ignore
|
||||
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
@@ -41,6 +45,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
|
||||
@@ -64,13 +70,14 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyChangePassword === null || bodyChangePassword === undefined) {
|
||||
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
|
||||
}
|
||||
@@ -132,13 +139,14 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (createAccountRequest === null || createAccountRequest === undefined) {
|
||||
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
|
||||
}
|
||||
@@ -200,13 +208,14 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (accountId === null || accountId === undefined) {
|
||||
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
|
||||
}
|
||||
@@ -259,22 +268,20 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
||||
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
||||
}
|
||||
|
||||
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'
|
||||
]);
|
||||
@@ -326,13 +333,14 @@ 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(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
@@ -431,13 +439,14 @@ 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(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
|
||||
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
|
||||
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||
public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
@@ -490,13 +499,14 @@ 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.
|
||||
*/
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
@@ -624,13 +634,14 @@ 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(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
@@ -679,19 +690,17 @@ 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(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
|
||||
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
|
||||
public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||
public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||
public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
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'
|
||||
]);
|
||||
@@ -738,9 +747,9 @@ export class AuthService extends BaseService {
|
||||
* @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 requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OtkResponse>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OtkResponse>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OtkResponse>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||
@@ -782,7 +791,7 @@ export class AuthService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/auth/v2/request-otk`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<OtkResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyRequestOtk,
|
||||
@@ -796,18 +805,151 @@ export class AuthService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request Password Reset
|
||||
* Request a one-time password reset link for the given email address.
|
||||
* @endpoint post /api/auth/v2/request-password-reset
|
||||
* @param bodyRequestPasswordReset
|
||||
* @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 requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyRequestPasswordReset === null || bodyRequestPasswordReset === undefined) {
|
||||
throw new Error('Required parameter bodyRequestPasswordReset was null or undefined when calling requestPasswordReset.');
|
||||
}
|
||||
|
||||
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/auth/v2/request-password-reset`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyRequestPasswordReset,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset Password
|
||||
* Reset the user\'s password using a one-time password reset token.
|
||||
* @endpoint post /api/auth/v2/reset-password
|
||||
* @param bodyResetPassword
|
||||
* @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 resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public resetPassword(bodyResetPassword: BodyResetPassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyResetPassword === null || bodyResetPassword === undefined) {
|
||||
throw new Error('Required parameter bodyResetPassword was null or undefined when calling resetPassword.');
|
||||
}
|
||||
|
||||
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/auth/v2/reset-password`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyResetPassword,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Account
|
||||
* @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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (accountId === null || accountId === undefined) {
|
||||
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,355 +9,205 @@
|
||||
*/
|
||||
/* 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';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class INSEServiceService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the topic hierarchy cache.
|
||||
* @endpoint get /api/inse-service/topics/cache
|
||||
* @param pageSize Page size for each search page.
|
||||
* @param saveJson Persist cache JSON to data folder.
|
||||
* @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 buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<object>;
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<object>>;
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<object>>;
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageSize,
|
||||
'page_size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>saveJson,
|
||||
'save_json',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Builds the topic hierarchy cache.
|
||||
* @endpoint get /api/inse-service/topics/cache
|
||||
* @param pageSize Page size for each search page.
|
||||
* @param saveJson Persist cache JSON to data folder.
|
||||
* @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 buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>saveJson, 'save_json');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/cache`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts topic hierarchy occurrences from cache.
|
||||
* @endpoint get /api/inse-service/topics/count
|
||||
* @param topic Topic names (repeat parameter).
|
||||
* @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 countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<object>;
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<object>>;
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<object>>;
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter topic was null or undefined when calling countTopicHierarchy.',
|
||||
);
|
||||
}
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
if (topic) {
|
||||
topic.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'topic',
|
||||
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/topics/cache`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
/**
|
||||
* Counts topic hierarchy occurrences from cache.
|
||||
* @endpoint get /api/inse-service/topics/count
|
||||
* @param topic Topic names (repeat parameter).
|
||||
* @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 countTopicHierarchy(topic: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
|
||||
public countTopicHierarchy(topic: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
|
||||
public countTopicHierarchy(topic: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
|
||||
public countTopicHierarchy(topic: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (topic) {
|
||||
topic.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'topic');
|
||||
})
|
||||
}
|
||||
|
||||
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/topics/count`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
|
||||
* @endpoint get /api/inse-service/topics/hierarchy
|
||||
* @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 getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
|
||||
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
|
||||
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
|
||||
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
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';
|
||||
}
|
||||
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/topics/hierarchy`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/count`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
|
||||
* @endpoint get /api/inse-service/topics/hierarchy
|
||||
* @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 getTopicHierarchy(
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<object>;
|
||||
public getTopicHierarchy(
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<object>>;
|
||||
public getTopicHierarchy(
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<object>>;
|
||||
public getTopicHierarchy(
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
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/topics/hierarchy`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,8 +26,6 @@ import { Institution } from '../model/institution';
|
||||
import { InstitutionPage } from '../model/institutionPage';
|
||||
// @ts-ignore
|
||||
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
||||
// @ts-ignore
|
||||
import { RankingResponse } from '../model/rankingResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
@@ -170,69 +168,6 @@ export class InstitutionsService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns data for the University Ranking Dashboard.
|
||||
* @endpoint get /api/inse-service/university-rankings
|
||||
* @param topic Research topic (e.g., \'Artificial Intelligence\')
|
||||
* @param metric Metric to rank by
|
||||
* @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 getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
|
||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
|
||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
|
||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>topic, 'topic');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>metric, 'metric');
|
||||
|
||||
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/university-rankings`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of OpenAlex institutions.
|
||||
* @endpoint get /api/inse-service/institutions
|
||||
|
||||
@@ -47,13 +47,14 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
|
||||
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
|
||||
}
|
||||
@@ -115,13 +116,14 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
|
||||
}
|
||||
@@ -175,13 +177,14 @@ 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.
|
||||
*/
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
@@ -240,13 +243,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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* 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';
|
||||
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 { AllPatentsResponse } from '../model/allPatentsResponse';
|
||||
@@ -36,657 +30,338 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
||||
import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class PatentsService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all patents with pagination and search.
|
||||
* @endpoint get /api/inse-service/patents
|
||||
* @param page
|
||||
* @param size
|
||||
* @param search
|
||||
* @param source
|
||||
* @param sortBy
|
||||
* @param sortDirection
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<AllPatentsResponse>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<AllPatentsResponse>>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<AllPatentsResponse>>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>size,
|
||||
'size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>search,
|
||||
'search',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>source,
|
||||
'source',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>sortBy,
|
||||
'sort_by',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>sortDirection,
|
||||
'sort_direction',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Get all patents with pagination and search.
|
||||
* @endpoint get /api/inse-service/patents
|
||||
* @param page
|
||||
* @param size
|
||||
* @param search
|
||||
* @param source
|
||||
* @param sortBy
|
||||
* @param sortDirection
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AllPatentsResponse>;
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AllPatentsResponse>>;
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AllPatentsResponse>>;
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>size, 'size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>search, 'search');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>source, 'source');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortBy, 'sort_by');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortDirection, 'sort_direction');
|
||||
|
||||
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 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/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AllPatentsResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AllPatentsResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
/**
|
||||
* 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<OrgPatentsResponse>;
|
||||
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<HttpResponse<OrgPatentsResponse>>;
|
||||
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<HttpEvent<OrgPatentsResponse>>;
|
||||
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<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error('Required parameter id was null or undefined when calling getOrgPatentsByInstitution.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<OrgPatentsResponse>;
|
||||
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<HttpResponse<OrgPatentsResponse>>;
|
||||
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<HttpEvent<OrgPatentsResponse>>;
|
||||
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<any> {
|
||||
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,
|
||||
<any>matchType, 'match_type');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>size, 'size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>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<OrgPatentsResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>matchType,
|
||||
'match_type',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>size,
|
||||
'size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>source,
|
||||
'source',
|
||||
);
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (identifier === null || identifier === undefined) {
|
||||
throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>prefix, 'prefix');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>title, 'title');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>fillingDate, 'filling_date');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
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/patents/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentEntry>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Get patents matched to an author by name.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
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';
|
||||
}
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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<OrgPatentsResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
/**
|
||||
* 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<PatentsByInstitutionResponse>;
|
||||
public getPatentsByInstitution(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByInstitutionResponse>>;
|
||||
public getPatentsByInstitution(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByInstitutionResponse>>;
|
||||
public getPatentsByInstitution(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error('Required parameter id was null or undefined when calling getPatentsByInstitution.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PatentEntry>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (identifier === null || identifier === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
|
||||
);
|
||||
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<PatentsByInstitutionResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>prefix,
|
||||
'prefix',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>title,
|
||||
'title',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>fillingDate,
|
||||
'filling_date',
|
||||
);
|
||||
|
||||
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/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentEntry>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get patents matched to an author by name.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PatentsByAuthorResponse>;
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByAuthorResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<PatentsByInstitutionResponse>;
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentsByInstitutionResponse>>;
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentsByInstitutionResponse>>;
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
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<PatentsByInstitutionResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* 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 { AutocompleteLocationItem } from '../model/autocompleteLocationItem';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { RankingResponse } from '../model/rankingResponse';
|
||||
// @ts-ignore
|
||||
import { TopInstitutionItem } from '../model/topInstitutionItem';
|
||||
// @ts-ignore
|
||||
import { TrendResponse } from '../model/trendResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class UniversityRankingsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns country and continent options for autocomplete inputs.
|
||||
* @endpoint get /api/inse-service/university-rankings/autocomplete-locations
|
||||
* @param query Query text to search for countries/continents
|
||||
* @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 getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AutocompleteLocationItem>>;
|
||||
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AutocompleteLocationItem>>>;
|
||||
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AutocompleteLocationItem>>>;
|
||||
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (query === null || query === undefined) {
|
||||
throw new Error('Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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/university-rankings/autocomplete-locations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<AutocompleteLocationItem>>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns data for the University Ranking Dashboard.
|
||||
* @endpoint get /api/inse-service/university-rankings
|
||||
* @param topic Research topic display name or OpenAlex ID (e.g., \'Artificial Intelligence\')
|
||||
* @param metric Metric to rank by
|
||||
* @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 getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
|
||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
|
||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
|
||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>topic, 'topic');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>metric, 'metric');
|
||||
|
||||
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/university-rankings`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns top institutions filtered by country/region and sorted by topic-level publications count.
|
||||
* @endpoint get /api/inse-service/university-rankings/top-institutions
|
||||
* @param topic Research topic
|
||||
* @param region Region identifier (e.g. EU)
|
||||
* @param country Country code (e.g. DE)
|
||||
* @param limit Max suggestions to return
|
||||
* @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 getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<TopInstitutionItem>>;
|
||||
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<TopInstitutionItem>>>;
|
||||
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<TopInstitutionItem>>>;
|
||||
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error('Required parameter topic was null or undefined when calling getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>topic, 'topic');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>region, 'region');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>country, 'country');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>limit, 'limit');
|
||||
|
||||
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/university-rankings/top-institutions`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<TopInstitutionItem>>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns timeseries publication data for compared institutions, countries and regions.
|
||||
* @endpoint get /api/inse-service/university-rankings/trend
|
||||
* @param topics List of topics to analyze
|
||||
* @param institutions List of OpenAlex Institution IDs
|
||||
* @param countries List of country codes
|
||||
* @param regions List of region identifiers
|
||||
* @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 getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TrendResponse>;
|
||||
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TrendResponse>>;
|
||||
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TrendResponse>>;
|
||||
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (topics === null || topics === undefined) {
|
||||
throw new Error('Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (topics) {
|
||||
topics.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'topics');
|
||||
})
|
||||
}
|
||||
if (institutions) {
|
||||
institutions.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'institutions');
|
||||
})
|
||||
}
|
||||
if (countries) {
|
||||
countries.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'countries');
|
||||
})
|
||||
}
|
||||
if (regions) {
|
||||
regions.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'regions');
|
||||
})
|
||||
}
|
||||
|
||||
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/university-rankings/trend`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<TrendResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+171
-197
@@ -1,219 +1,193 @@
|
||||
import {
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpParameterCodec,
|
||||
} from '@angular/common/http';
|
||||
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
|
||||
import { Param } from './param';
|
||||
|
||||
export interface ConfigurationParameters {
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: { [key: string]: string };
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Override the default method for encoding path parameters in various
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam?: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials?: { [key: string]: string | (() => string | undefined) };
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: {[ key: string ]: string};
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Override the default method for encoding path parameters in various
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam?: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials?: {[ key: string ]: string | (() => string | undefined)};
|
||||
}
|
||||
|
||||
export class Configuration {
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: { [key: string]: string };
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Encoding of various path parameter
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials: { [key: string]: string | (() => string | undefined) };
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: {[ key: string ]: string};
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Encoding of various path parameter
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials: {[ key: string ]: string | (() => string | undefined)};
|
||||
|
||||
constructor({
|
||||
accessToken,
|
||||
apiKeys,
|
||||
basePath,
|
||||
credentials,
|
||||
encodeParam,
|
||||
encoder,
|
||||
password,
|
||||
username,
|
||||
withCredentials,
|
||||
}: ConfigurationParameters = {}) {
|
||||
if (apiKeys) {
|
||||
this.apiKeys = apiKeys;
|
||||
}
|
||||
if (username !== undefined) {
|
||||
this.username = username;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
this.password = password;
|
||||
}
|
||||
if (accessToken !== undefined) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
if (basePath !== undefined) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
if (withCredentials !== undefined) {
|
||||
this.withCredentials = withCredentials;
|
||||
}
|
||||
if (encoder) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
this.encodeParam =
|
||||
encodeParam ?? ((param) => this.defaultEncodeParam(param));
|
||||
this.credentials = credentials ?? {};
|
||||
constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) {
|
||||
if (apiKeys) {
|
||||
this.apiKeys = apiKeys;
|
||||
}
|
||||
if (username !== undefined) {
|
||||
this.username = username;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
this.password = password;
|
||||
}
|
||||
if (accessToken !== undefined) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
if (basePath !== undefined) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
if (withCredentials !== undefined) {
|
||||
this.withCredentials = withCredentials;
|
||||
}
|
||||
if (encoder) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param));
|
||||
this.credentials = credentials ?? {};
|
||||
|
||||
// init default HTTPBearer credential
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? this.accessToken()
|
||||
: this.accessToken;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the correct content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param contentTypes - the array of content types that are available for selection
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderContentType(contentTypes: string[]): string | undefined {
|
||||
if (contentTypes.length === 0) {
|
||||
return undefined;
|
||||
// init default HTTPBearer credential
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? this.accessToken()
|
||||
: this.accessToken;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return contentTypes[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
/**
|
||||
* Select the correct content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param contentTypes - the array of content types that are available for selection
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderContentType (contentTypes: string[]): string | undefined {
|
||||
if (contentTypes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the correct accept content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param accepts - the array of content types that are available for selection.
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderAccept(accepts: string[]): string | undefined {
|
||||
if (accepts.length === 0) {
|
||||
return undefined;
|
||||
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return contentTypes[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
const type = accepts.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return accepts[0];
|
||||
/**
|
||||
* Select the correct accept content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param accepts - the array of content types that are available for selection.
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderAccept(accepts: string[]): string | undefined {
|
||||
if (accepts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const type = accepts.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return accepts[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp(
|
||||
'^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$',
|
||||
'i',
|
||||
);
|
||||
return (
|
||||
mime !== null &&
|
||||
(jsonMime.test(mime) ||
|
||||
mime.toLowerCase() === 'application/json-patch+json')
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
|
||||
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
|
||||
}
|
||||
|
||||
public lookupCredential(key: string): string | undefined {
|
||||
const value = this.credentials[key];
|
||||
return typeof value === 'function' ? value() : value;
|
||||
}
|
||||
public lookupCredential(key: string): string | undefined {
|
||||
const value = this.credentials[key];
|
||||
return typeof value === 'function'
|
||||
? value()
|
||||
: value;
|
||||
}
|
||||
|
||||
public addCredentialToHeaders(
|
||||
credentialKey: string,
|
||||
headerName: string,
|
||||
headers: HttpHeaders,
|
||||
prefix?: string,
|
||||
): HttpHeaders {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
|
||||
}
|
||||
public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value
|
||||
? headers.set(headerName, (prefix ?? '') + value)
|
||||
: headers;
|
||||
}
|
||||
|
||||
public addCredentialToQuery(
|
||||
credentialKey: string,
|
||||
paramName: string,
|
||||
query: HttpParams,
|
||||
): HttpParams {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value ? query.set(paramName, value) : query;
|
||||
}
|
||||
public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value
|
||||
? query.set(paramName, value)
|
||||
: query;
|
||||
}
|
||||
|
||||
private defaultEncodeParam(param: Param): string {
|
||||
// This implementation exists as fallback for missing configuration
|
||||
// and for backwards compatibility to older typescript-angular generator versions.
|
||||
// It only works for the 'simple' parameter style.
|
||||
// Date-handling only works for the 'date-time' format.
|
||||
// All other styles and Date-formats are probably handled incorrectly.
|
||||
//
|
||||
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
|
||||
private defaultEncodeParam(param: Param): string {
|
||||
// This implementation exists as fallback for missing configuration
|
||||
// and for backwards compatibility to older typescript-angular generator versions.
|
||||
// It only works for the 'simple' parameter style.
|
||||
// Date-handling only works for the 'date-time' format.
|
||||
// All other styles and Date-formats are probably handled incorrectly.
|
||||
//
|
||||
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
|
||||
|
||||
const value =
|
||||
param.dataFormat === 'date-time' && param.value instanceof Date
|
||||
? (param.value as Date).toISOString()
|
||||
: param.value;
|
||||
const value = param.dataFormat === 'date-time' && param.value instanceof Date
|
||||
? (param.value as Date).toISOString()
|
||||
: param.value;
|
||||
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { RefreshToken } from './refreshToken';
|
||||
import { AccessToken } from './accessToken';
|
||||
|
||||
|
||||
@@ -16,9 +15,5 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,10 +12,6 @@ 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.
|
||||
*/
|
||||
@@ -29,13 +25,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.
|
||||
*/
|
||||
@@ -48,6 +44,10 @@ 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 {
|
||||
}
|
||||
|
||||
@@ -26,3 +26,4 @@ export interface AccountProfile {
|
||||
export namespace AccountProfile {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { SpecificWorkPurpose } from './specificWorkPurpose';
|
||||
|
||||
|
||||
/**
|
||||
* Represents the purposes of an author, including their ID and a list of specific work purposes.
|
||||
*/
|
||||
export interface AuthorWorkPurposes {
|
||||
/**
|
||||
* The raw OpenAlex author id.
|
||||
*/
|
||||
raw_oa_author_id: string;
|
||||
/**
|
||||
* The total number of works for the author.
|
||||
*/
|
||||
total?: number;
|
||||
/**
|
||||
* The list of specific work purposes.
|
||||
*/
|
||||
purposes?: Array<SpecificWorkPurpose>;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export interface AutocompleteLocationItem {
|
||||
id: string;
|
||||
display_name: string;
|
||||
code: string;
|
||||
type: AutocompleteLocationItem.TypeEnum;
|
||||
}
|
||||
export namespace AutocompleteLocationItem {
|
||||
export const TypeEnum = {
|
||||
Country: 'country',
|
||||
Continent: 'continent'
|
||||
} as const;
|
||||
export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
export interface BodyRequestOtk {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* User\'s password
|
||||
*/
|
||||
password: string;
|
||||
|
||||
export interface BodyRequestOtk {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* User\'s password
|
||||
*/
|
||||
password: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 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 BodyRequestPasswordReset {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyResetPassword {
|
||||
/**
|
||||
* Password reset token from the reset link
|
||||
*/
|
||||
reset_token: string;
|
||||
/**
|
||||
* New password
|
||||
*/
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
@@ -1,14 +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 CreateOrganizationRequest {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -10,17 +10,19 @@
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,11 +10,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.
|
||||
*/
|
||||
@@ -28,15 +24,11 @@ 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 {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +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.
|
||||
*/
|
||||
|
||||
export interface InseAccountManagementModelOrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
openalex_institution_id?: string | null;
|
||||
|
||||
export interface InseAccountManagementModelOrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
openalex_institution_id?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +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.
|
||||
*/
|
||||
|
||||
export interface InseOrganizationManagementModelOrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted: boolean;
|
||||
member_count: number;
|
||||
|
||||
export interface InseOrganizationManagementModelOrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted: boolean;
|
||||
member_count: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,7 +9,9 @@
|
||||
*/
|
||||
import { Topic } from './topic';
|
||||
|
||||
export interface KeywordTopicMatch {
|
||||
keyword: string;
|
||||
topic?: Topic | null;
|
||||
|
||||
export interface KeywordTopicMatch {
|
||||
keyword: string;
|
||||
topic?: Topic | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
/**
|
||||
* 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<string>;
|
||||
|
||||
export interface KeywordsTopicsRequest {
|
||||
/**
|
||||
* List of keywords/sentences to query by similarity.
|
||||
*/
|
||||
keywords: Array<string>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,9 +9,11 @@
|
||||
*/
|
||||
import { KeywordTopicMatch } from './keywordTopicMatch';
|
||||
|
||||
export interface KeywordsTopicsResponse {
|
||||
/**
|
||||
* Top matching topics for each keyword in the requested list.
|
||||
*/
|
||||
results: Array<KeywordTopicMatch>;
|
||||
|
||||
export interface KeywordsTopicsResponse {
|
||||
/**
|
||||
* Top matching topics for each keyword in the requested list.
|
||||
*/
|
||||
results: Array<KeywordTopicMatch>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +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 { IdToken } from './idToken';
|
||||
import { IdTokenMetadata } from './idTokenMetadata';
|
||||
|
||||
export interface LoginResponse {
|
||||
/**
|
||||
* The ID token issued upon successful login.
|
||||
*/
|
||||
id_token: IdToken;
|
||||
|
||||
export interface LoginResponse {
|
||||
/**
|
||||
* The ID token issued upon successful login.
|
||||
*/
|
||||
id_token: IdTokenMetadata;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +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 MatchedAuthor {
|
||||
openalex_author_id: string;
|
||||
author_name: string;
|
||||
|
||||
export interface MatchedAuthor {
|
||||
openalex_author_id: string;
|
||||
author_name: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 MatchedTopic {
|
||||
id?: string | null;
|
||||
display_name?: string | null;
|
||||
subfield_name?: string | null;
|
||||
field_name?: string | null;
|
||||
domain_name?: string | null;
|
||||
source_keyword?: string | null;
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ export * from './authorNetworkNode';
|
||||
export * from './authorParsedLongestName';
|
||||
export * from './authorPositionCount';
|
||||
export * from './authorSummaryStats';
|
||||
export * from './authorWorkPurposes';
|
||||
export * from './authorsFilterProperties';
|
||||
export * from './authorsListResponse';
|
||||
export * from './authorship';
|
||||
export * from './autocompleteLocationItem';
|
||||
export * from './autocompleteResponse';
|
||||
export * from './autocompleteResponseMeta';
|
||||
export * from './autocompleteResponseResultsInner';
|
||||
@@ -22,6 +24,8 @@ export * from './bodyChangePassword';
|
||||
export * from './bodyGetAccessToken';
|
||||
export * from './bodyLogin';
|
||||
export * from './bodyRequestOtk';
|
||||
export * from './bodyRequestPasswordReset';
|
||||
export * from './bodyResetPassword';
|
||||
export * from './bundProject';
|
||||
export * from './bundProjectDetails';
|
||||
export * from './bundProjectPage';
|
||||
@@ -89,7 +93,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';
|
||||
@@ -114,6 +118,7 @@ export * from './loginResponse';
|
||||
export * from './longitude';
|
||||
export * from './matchedAuthor';
|
||||
export * from './matchedOfficer';
|
||||
export * from './matchedTopic';
|
||||
export * from './mentionedPerson';
|
||||
export * from './meta';
|
||||
export * from './model2YrMeanCitedness';
|
||||
@@ -124,6 +129,7 @@ export * from './openAccess';
|
||||
export * from './orgPatentEntry';
|
||||
export * from './orgPatentsResponse';
|
||||
export * from './organizationPage';
|
||||
export * from './otkResponse';
|
||||
export * from './patentEntry';
|
||||
export * from './patentsByAuthorResponse';
|
||||
export * from './patentsByInstitutionResponse';
|
||||
@@ -135,20 +141,24 @@ export * from './publicationDetailByFunder';
|
||||
export * from './publicationIdsByAuthorPosition';
|
||||
export * from './publicationsByAuthorResponse';
|
||||
export * from './rankingResponse';
|
||||
export * from './refreshToken';
|
||||
export * from './score';
|
||||
export * from './sortDirection';
|
||||
export * from './specificWorkPurpose';
|
||||
export * from './tokenType';
|
||||
export * from './topInstitutionItem';
|
||||
export * from './topic';
|
||||
export * from './topicCount';
|
||||
export * from './topicDomain';
|
||||
export * from './topicField';
|
||||
export * from './topicIds';
|
||||
export * from './topicSubfield';
|
||||
export * from './topicYearlyData';
|
||||
export * from './topics';
|
||||
export * from './topicsByTime';
|
||||
export * from './topicsByYear';
|
||||
export * from './topicsListResponse';
|
||||
export * from './trendResponse';
|
||||
export * from './trendSeries';
|
||||
export * from './universityRanking';
|
||||
export * from './universityTopicData';
|
||||
export * from './updateAccountRequest';
|
||||
@@ -168,6 +178,7 @@ export * from './workKeyword';
|
||||
export * from './workMeshInner';
|
||||
export * from './workNetworkNode';
|
||||
export * from './workPage';
|
||||
export * from './workPurpose';
|
||||
export * from './workSustainableDevelopmentGoalsInner';
|
||||
export * from './workTopic';
|
||||
export * from './workTopicDomain';
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { MatchedTopic } from './matchedTopic';
|
||||
import { MentionedPerson } from './mentionedPerson';
|
||||
|
||||
|
||||
@@ -21,7 +22,7 @@ export interface NewsArticleDetail {
|
||||
related?: boolean | null;
|
||||
full_content?: string | null;
|
||||
authors?: Array<MentionedPerson>;
|
||||
topics?: Array<string>;
|
||||
keywords?: Array<string>;
|
||||
topics?: Array<MatchedTopic>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,55 +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 {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 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 { WorkPurpose } from './workPurpose';
|
||||
|
||||
|
||||
/**
|
||||
* Represents the purpose of a specific work, including its ID, purpose, and optional reasoning.
|
||||
*/
|
||||
export interface SpecificWorkPurpose {
|
||||
/**
|
||||
* The raw OpenAlex work id.
|
||||
*/
|
||||
raw_oa_work_id: string;
|
||||
publication_year?: number | null;
|
||||
/**
|
||||
* The purpose of the work.
|
||||
*/
|
||||
purpose: WorkPurpose;
|
||||
reasoning?: string | null;
|
||||
}
|
||||
export namespace SpecificWorkPurpose {
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
|
||||
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];
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface TopInstitutionItem {
|
||||
id?: string | null;
|
||||
display_name?: string | null;
|
||||
ror?: string | null;
|
||||
country_code?: string | null;
|
||||
type?: string | null;
|
||||
lineage?: Array<string> | null;
|
||||
works_count?: number | null;
|
||||
exact_topic_count?: number | null;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export interface TopicYearlyData {
|
||||
year: number;
|
||||
raw: number;
|
||||
normalized: number;
|
||||
cumulative: number;
|
||||
institutions_count: number;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 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 { TrendSeries } from './trendSeries';
|
||||
|
||||
|
||||
export interface TrendResponse {
|
||||
series: Array<TrendSeries>;
|
||||
years: Array<number>;
|
||||
location_mappings?: { [key: string]: Array<string>; } | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 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 { TopicYearlyData } from './topicYearlyData';
|
||||
|
||||
|
||||
export interface TrendSeries {
|
||||
entity_id: string;
|
||||
entity_name: string;
|
||||
entity_type: TrendSeries.EntityTypeEnum;
|
||||
country_code?: string | null;
|
||||
topic_data: { [key: string]: Array<TopicYearlyData>; };
|
||||
}
|
||||
export namespace TrendSeries {
|
||||
export const EntityTypeEnum = {
|
||||
Institution: 'institution',
|
||||
Country: 'country',
|
||||
Region: 'region'
|
||||
} as const;
|
||||
export type EntityTypeEnum = typeof EntityTypeEnum[keyof typeof EntityTypeEnum];
|
||||
}
|
||||
|
||||
|
||||
@@ -8,21 +8,12 @@
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { YearlyData } from './yearlyData';
|
||||
import { Topic } from './topic';
|
||||
|
||||
|
||||
export interface UniversityTopicData {
|
||||
university: string;
|
||||
topic: UniversityTopicData.TopicEnum;
|
||||
topic: Topic;
|
||||
yearly_data: Array<YearlyData>;
|
||||
}
|
||||
export namespace UniversityTopicData {
|
||||
export const TopicEnum = {
|
||||
ArtificialIntelligence: 'Artificial Intelligence',
|
||||
QuantumComputing: 'Quantum Computing',
|
||||
RenewableEnergy: 'Renewable Energy',
|
||||
Biotechnology: 'Biotechnology'
|
||||
} as const;
|
||||
export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum];
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -23,3 +23,4 @@ export interface UpdateAccountRequest {
|
||||
export namespace UpdateAccountRequest {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +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.
|
||||
*/
|
||||
|
||||
export interface UpdateOrganizationRequest {
|
||||
name?: string | null;
|
||||
other_inst_id?: string | null;
|
||||
deleted?: boolean | null;
|
||||
|
||||
export interface UpdateOrganizationRequest {
|
||||
name?: string | null;
|
||||
other_inst_id?: string | null;
|
||||
deleted?: boolean | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Represents the purpose of a work. Either a foundation work or an application work.
|
||||
*/
|
||||
export const WorkPurpose = {
|
||||
Foundation: 'Foundation',
|
||||
Application: 'Application'
|
||||
} as const;
|
||||
export type WorkPurpose = typeof WorkPurpose[keyof typeof WorkPurpose];
|
||||
|
||||
@@ -19,6 +19,7 @@ import { WorkTopicField } from './workTopicField';
|
||||
export interface WorkTopic {
|
||||
id?: string | null;
|
||||
display_name?: string | null;
|
||||
description?: string | null;
|
||||
score?: Score | null;
|
||||
subfield?: WorkTopicSubfield | null;
|
||||
field?: WorkTopicField | null;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { userGuard } from './shared/guards/user.guard';
|
||||
import { superAdminGuard } from './shared/guards/super-admin.guard';
|
||||
import { guestOnlyGuard } from './shared/guards/guest-only.guard';
|
||||
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
|
||||
import { personListResolver } from './resolvers/person-list.resolver';
|
||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||
import { personResolver } from './resolvers/person.resolver';
|
||||
import { personNewsResolver } from './resolvers/person-news.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';
|
||||
@@ -20,7 +21,15 @@ 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';
|
||||
import { KeywordsToPersonsResultsComponent } from './modules/keywords-search/search-results/persons-results/persons-results.component';
|
||||
import { KeywordsToProjectsResultsComponent } from './modules/keywords-search/search-results/projects-results/projects-results.component';
|
||||
import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/search-results/patents-results/patents-results.component';
|
||||
import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component';
|
||||
import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component';
|
||||
import { authorWorkPurposesResolver } from './resolvers/author-work-purposes.resolver';
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
@@ -35,10 +44,19 @@ export const routes: Routes = [
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'register',
|
||||
path: 'forgot-password',
|
||||
canActivate: [guestOnlyGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/app-register/app-register.component').then(
|
||||
(mod) => mod.AppRegisterComponent,
|
||||
import('./modules/forgot-password/forgot-password.component').then(
|
||||
(mod) => mod.ForgotPasswordComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'reset-password',
|
||||
canActivate: [guestOnlyGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/reset-password/reset-password.component').then(
|
||||
(mod) => mod.ResetPasswordComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -90,6 +108,21 @@ export const routes: Routes = [
|
||||
(mod) => mod.KeywordsSearchComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'keywords/search-results',
|
||||
loadComponent: () =>
|
||||
import('./modules/keywords-search/search-results/search-results.component').then(
|
||||
(mod) => mod.KeywordsSearchResultsComponent,
|
||||
),
|
||||
children: [
|
||||
{ path: '', pathMatch: 'full', redirectTo: 'persons' },
|
||||
{ path: 'persons', component: KeywordsToPersonsResultsComponent },
|
||||
{ path: 'projects', component: KeywordsToProjectsResultsComponent },
|
||||
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
|
||||
{ path: 'works', component: KeywordsToWorksResultsComponent },
|
||||
{ path: 'news', component: KeywordsToNewsResultsComponent },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
canActivate: [userGuard],
|
||||
@@ -114,6 +147,11 @@ export const routes: Routes = [
|
||||
import('./modules/accounts/accounts.component').then(
|
||||
(mod) => mod.AccountsComponent,
|
||||
),
|
||||
resolve: {
|
||||
accountPage: accountsPageResolver,
|
||||
organizations: accountsOrganizationResolver,
|
||||
},
|
||||
runGuardsAndResolvers: 'always',
|
||||
},
|
||||
{
|
||||
path: 'organizations',
|
||||
@@ -122,7 +160,12 @@ export const routes: Routes = [
|
||||
import('./modules/organizations/organizations.component').then(
|
||||
(mod) => mod.OrganizationsComponent,
|
||||
),
|
||||
resolve: {
|
||||
organizationPage: organizationsOrganizationsResolver,
|
||||
},
|
||||
runGuardsAndResolvers: 'always',
|
||||
},
|
||||
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
@@ -226,6 +269,9 @@ export const routes: Routes = [
|
||||
import('./modules/person-publications/person-publications.component').then(
|
||||
(mod) => mod.PersonPublicationsComponent,
|
||||
),
|
||||
resolve: {
|
||||
authorWorkPurposes: authorWorkPurposesResolver,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'network',
|
||||
@@ -258,6 +304,23 @@ export const routes: Routes = [
|
||||
(mod) => mod.PersonFundingComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
loadComponent: () =>
|
||||
import('./modules/person-news/person-news.component').then(
|
||||
(mod) => mod.PersonNewsComponent,
|
||||
),
|
||||
resolve: {
|
||||
newsPage: personNewsResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'pageSize', 'sortOrder', 'query'];
|
||||
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'patents',
|
||||
loadComponent: () =>
|
||||
@@ -371,6 +434,20 @@ export const routes: Routes = [
|
||||
(mod) => mod.PatentsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news-detail/news-detail.component').then(
|
||||
(mod) => mod.NewsDetailComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'error',
|
||||
loadComponent: () =>
|
||||
|
||||
@@ -35,6 +35,7 @@ export class SkTextDirective implements OnChanges {
|
||||
// measure natural width before blanking text
|
||||
const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60);
|
||||
const height = 20;
|
||||
this.renderer.addClass(el, 'sk-text-loading');
|
||||
this.renderer.setStyle(el, 'color', 'transparent');
|
||||
this.renderer.setStyle(
|
||||
el,
|
||||
@@ -47,10 +48,17 @@ export class SkTextDirective implements OnChanges {
|
||||
this.renderer.setStyle(el, 'min-width', `${width}px`);
|
||||
this.renderer.setStyle(el, 'max-height', `${height}px`);
|
||||
this.renderer.setStyle(el, 'display', 'inline-block');
|
||||
this.renderer.setStyle(el, 'overflow', 'hidden');
|
||||
this.renderer.setStyle(el, 'pointer-events', 'none');
|
||||
|
||||
Array.from(el.children).forEach((child) => {
|
||||
this.renderer.setStyle(child, 'visibility', 'hidden');
|
||||
});
|
||||
}
|
||||
|
||||
private hideSkeleton() {
|
||||
const el: HTMLElement = this.el.nativeElement;
|
||||
this.renderer.removeClass(el, 'sk-text-loading');
|
||||
this.renderer.removeStyle(el, 'color');
|
||||
this.renderer.removeStyle(el, 'background');
|
||||
this.renderer.removeStyle(el, 'background-size');
|
||||
@@ -59,5 +67,11 @@ export class SkTextDirective implements OnChanges {
|
||||
this.renderer.removeStyle(el, 'min-width');
|
||||
this.renderer.removeStyle(el, 'max-height');
|
||||
this.renderer.removeStyle(el, 'display');
|
||||
this.renderer.removeStyle(el, 'overflow');
|
||||
this.renderer.removeStyle(el, 'pointer-events');
|
||||
|
||||
Array.from(el.children).forEach((child) => {
|
||||
this.renderer.removeStyle(child, 'visibility');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,13 @@
|
||||
[formField]="changePasswordForm.showPasswords"
|
||||
>Passwörter anzeigen</mat-slide-toggle
|
||||
>
|
||||
<button mat-raised-button color="primary" type="submit">
|
||||
<button
|
||||
mat-raised-button
|
||||
color="primary"
|
||||
type="submit"
|
||||
[disabled]="
|
||||
changePasswordForm().invalid() || changePasswordForm().submitting()
|
||||
">
|
||||
Passwort ändern
|
||||
</button>
|
||||
</form>
|
||||
|
||||
@@ -28,6 +28,7 @@ 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';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
interface ChangePasswordForm {
|
||||
oldPassword: string;
|
||||
@@ -62,6 +63,7 @@ export class AccountComponent {
|
||||
|
||||
private readonly _credentialService = inject(CredentialService);
|
||||
private readonly _snackBar = inject(MatSnackBar);
|
||||
private readonly _router = inject(Router);
|
||||
|
||||
roles: UserRole[] = [];
|
||||
|
||||
@@ -143,20 +145,36 @@ export class AccountComponent {
|
||||
const newPassword = field.newPassword().value().trim();
|
||||
|
||||
if (!oldPassword || !newPassword) {
|
||||
return;
|
||||
return {} as any;
|
||||
}
|
||||
this._credentialService
|
||||
.changePassword(oldPassword, newPassword)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this._credentialService.refreshAccessToken().subscribe({
|
||||
next: () => {
|
||||
this._router.navigate(['/dashboard']);
|
||||
},
|
||||
error: (error) => {
|
||||
this._snackBar.open(
|
||||
'Fehler beim Aktualisieren des Zugriffstokens. Bitte melden Sie sich erneut an.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
},
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Error changing password:', error);
|
||||
this._snackBar.open(
|
||||
'Das alte Passwort ist nicht korrekt. Bitte versuchen Sie es erneut.',
|
||||
'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
|
||||
'OK',
|
||||
{ duration: 7000 },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return {} as any;
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -46,11 +46,7 @@
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>
|
||||
{{
|
||||
data.mode === 'create'
|
||||
? 'Initiales Passwort'
|
||||
: 'Neues Passwort'
|
||||
}}
|
||||
{{ data.mode === 'create' ? 'Initiales Passwort' : 'Neues Passwort' }}
|
||||
</mat-label>
|
||||
<input matInput type="password" formControlName="password" />
|
||||
@if (form.controls.password.hasError('required')) {
|
||||
|
||||
@@ -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<string>(this.data.account?.name ?? '', [
|
||||
Validators.required,
|
||||
]),
|
||||
role: new FormControl<AccountRole>(this.data.account?.role ?? 'USER', [
|
||||
role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
|
||||
Validators.required,
|
||||
]),
|
||||
organizationId: new FormControl<string>(
|
||||
@@ -148,6 +164,6 @@ export class AccountDialogComponent {
|
||||
}
|
||||
|
||||
protected close(): void {
|
||||
this.dialogRef.close(undefined);
|
||||
this.dialogRef.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,189 +23,73 @@
|
||||
}
|
||||
</header>
|
||||
|
||||
<form class="filters" [formGroup]="filterForm" (ngSubmit)="applyFilters()">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Name oder E-Mail</mat-label>
|
||||
<input matInput formControlName="search" />
|
||||
</mat-form-field>
|
||||
|
||||
@if (credentialService.isEffectiveSuperAdmin()) {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Organisation</mat-label>
|
||||
<mat-select formControlName="organizationId">
|
||||
<mat-option value="">Alle Organisationen</mat-option>
|
||||
@for (organization of organizations; track organization.id) {
|
||||
<mat-option [value]="organization.id">
|
||||
{{ organization.name }}
|
||||
</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
|
||||
<div class="filter-actions">
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="submit"
|
||||
matTooltip="Accounts mit den gewählten Filtern suchen">
|
||||
<mat-icon>search</mat-icon>
|
||||
Suchen
|
||||
</button>
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
matTooltip="Alle Suchfilter zurücksetzen"
|
||||
(click)="resetFilters()">
|
||||
Zurücksetzen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section class="table-panel">
|
||||
<div class="table-header">
|
||||
<strong>{{ total }} Accounts</strong>
|
||||
@if (isLoading) {
|
||||
<span>Wird geladen...</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>E-Mail</th>
|
||||
<th>Organisation</th>
|
||||
<th>Rolle</th>
|
||||
<th>Status</th>
|
||||
@if (!isReadOnly) {
|
||||
<th>Aktionen</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (account of accounts; track account.id) {
|
||||
<tr
|
||||
[class.deleted]="account.deleted"
|
||||
[class.deactivated]="!account.activated">
|
||||
<td>
|
||||
@if (isReadOnly) {
|
||||
{{ account.name }}
|
||||
} @else {
|
||||
<button
|
||||
class="link-button"
|
||||
type="button"
|
||||
[matTooltip]="'Account „' + account.name + '“ bearbeiten'"
|
||||
(click)="startEdit(account)">
|
||||
{{ account.name }}
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
<td>{{ account.email }}</td>
|
||||
<td>{{ account.organization_name }}</td>
|
||||
<td>
|
||||
<span class="role">{{ account.role | role }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
class="status"
|
||||
[class.status--deleted]="account.deleted"
|
||||
[class.status--deactivated]="
|
||||
!account.deleted && !account.activated
|
||||
">
|
||||
{{
|
||||
account.deleted
|
||||
? 'deleted'
|
||||
: account.activated
|
||||
? 'active'
|
||||
: 'inactive'
|
||||
}}
|
||||
</span>
|
||||
</td>
|
||||
@if (!isReadOnly) {
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
matTooltip="Account bearbeiten"
|
||||
(click)="startEdit(account)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Impersonate"
|
||||
matTooltip="Als dieser Account anmelden"
|
||||
[disabled]="!canImpersonate(account)"
|
||||
(click)="impersonate(account)">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
</button>
|
||||
@if (credentialService.isEffectiveSuperAdmin()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
[attr.aria-label]="
|
||||
account.activated ? 'Deaktivieren' : 'Aktivieren'
|
||||
"
|
||||
[matTooltip]="
|
||||
account.activated
|
||||
? 'Account deaktivieren'
|
||||
: 'Account aktivieren'
|
||||
"
|
||||
[disabled]="account.is_current || account.deleted"
|
||||
(click)="toggleAccountActivation(account)">
|
||||
<mat-icon>{{
|
||||
account.activated ? 'person_off' : 'person_check'
|
||||
}}</mat-icon>
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Löschen"
|
||||
matTooltip="Account löschen"
|
||||
[disabled]="account.is_current || account.deleted"
|
||||
(click)="deleteAccount(account)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
}
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr>
|
||||
<td [attr.colspan]="isReadOnly ? 5 : 6" class="empty">
|
||||
Keine Accounts gefunden.
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination">
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
matTooltip="Vorherige Seite anzeigen"
|
||||
[disabled]="!canPageBack"
|
||||
(click)="loadAccounts(page - 1)">
|
||||
<mat-icon>chevron_left</mat-icon>
|
||||
Zurück
|
||||
</button>
|
||||
<span>Seite {{ page + 1 }}</span>
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
matTooltip="Nächste Seite anzeigen"
|
||||
[disabled]="!canPageForward"
|
||||
(click)="loadAccounts(page + 1)">
|
||||
Weiter
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
<section style="display: flex; gap: 1rem; align-items: center">
|
||||
<app-query-param-input
|
||||
queryParamKey="search"
|
||||
label="Nach Name oder E-Mail suchen"
|
||||
style="width: 35%" />
|
||||
<app-query-param-selector
|
||||
queryParamKey="organization_id"
|
||||
[options]="selectorOptions()"
|
||||
label="Organisation"
|
||||
[allowEmptyValue]="true"
|
||||
style="width: 25%" />
|
||||
</section>
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
<app-data-table [columns]="accountColumns" [data]="accountPage().items" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<app-query-param-paginator [total]="accountPage().total" />
|
||||
</section>
|
||||
|
||||
<ng-template #accountRoleTmp let-row>
|
||||
<span class="role">{{ row.role | role }}</span>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #accountStatusTmp let-row>
|
||||
<span
|
||||
class="status"
|
||||
[class.status--deleted]="row.deleted"
|
||||
[class.status--deactivated]="!row.deleted && !row.activated">
|
||||
{{
|
||||
(row.deleted ? 'deleted' : row.activated ? 'active' : 'inactive') | status
|
||||
}}
|
||||
</span>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #accountActionsTmp let-row>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
(click)="startEdit(row)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Impersonate"
|
||||
[disabled]="!canImpersonate(row)"
|
||||
(click)="impersonate(row)">
|
||||
<mat-icon>switch_account</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
[attr.aria-label]="row.activated ? 'Deaktivieren' : 'Aktivieren'"
|
||||
[disabled]="row.is_current || row.deleted"
|
||||
(click)="toggleAccountActivation(row)">
|
||||
<mat-icon>{{ row.activated ? 'person_off' : 'person_check' }}</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="row.is_current || row.deleted"
|
||||
(click)="deleteAccount(row)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
|
||||
@@ -155,3 +155,8 @@ tr.deactivated:not(.deleted) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
mat-card,
|
||||
mat-paginator {
|
||||
background-color: var(--sg-background);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
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';
|
||||
@@ -10,19 +18,32 @@ 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',
|
||||
@@ -38,95 +59,92 @@ import { RolePipe } from '../../shared/pipes/role.pipe';
|
||||
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 isReadOnly(): boolean {
|
||||
return this.credentialService.isEffectiveManager();
|
||||
}
|
||||
|
||||
protected get availableRoles(): AccountRole[] {
|
||||
accountColumns: GenericColumn<AccountProfile>[] = [];
|
||||
accountRoleTmp = viewChild.required<TemplateRef<any>>('accountRoleTmp');
|
||||
accountStatusTmp = viewChild.required<TemplateRef<any>>('accountStatusTmp');
|
||||
accountActionsTmp = viewChild.required<TemplateRef<any>>('accountActionsTmp');
|
||||
|
||||
availableRoles = computed<UserRole[]>(() => {
|
||||
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<string>(''),
|
||||
organizationId: new FormControl<string>(''),
|
||||
});
|
||||
|
||||
selectorOptions = computed<SelectorOption[]>(() => {
|
||||
return this.organizations().map((org) => ({
|
||||
value: org.id,
|
||||
display_name: org.name,
|
||||
}));
|
||||
});
|
||||
|
||||
accountPage = input.required<AccountPage>();
|
||||
organizations =
|
||||
input.required<InseAccountManagementModelOrganizationProfile[]>();
|
||||
|
||||
ngOnInit(): void {
|
||||
if (!this.isReadOnly) {
|
||||
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',
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open(
|
||||
'Organisationen konnten nicht geladen werden.',
|
||||
'OK',
|
||||
{ duration: 5000 },
|
||||
);
|
||||
{
|
||||
id: 'email',
|
||||
header: 'E-Mail',
|
||||
type: 'accessor',
|
||||
accessorKey: 'email',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected applyFilters(): void {
|
||||
this.loadAccounts(0);
|
||||
}
|
||||
|
||||
protected resetFilters(): void {
|
||||
this.filterForm.reset({ search: '', organizationId: '' });
|
||||
this.loadAccounts(0);
|
||||
{
|
||||
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 {
|
||||
@@ -140,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 =
|
||||
@@ -170,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, {
|
||||
@@ -180,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(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -199,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', {
|
||||
@@ -248,14 +272,17 @@ export class AccountsComponent implements OnInit {
|
||||
account: AccountProfile,
|
||||
activated: boolean,
|
||||
): void {
|
||||
this.accountService.updateAccount(account.id, { activated }).subscribe({
|
||||
this.authService.updateAccount(account.id, { activated }).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open(
|
||||
activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.',
|
||||
'OK',
|
||||
{ duration: 3000 },
|
||||
);
|
||||
this.loadAccounts();
|
||||
this.router.navigate([], {
|
||||
queryParams: { page: 0 },
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open(
|
||||
@@ -267,36 +294,24 @@ export class AccountsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
protected impersonate(account: AccountProfile): void {
|
||||
protected async impersonate(account: AccountProfile): Promise<void> {
|
||||
if (!this.canImpersonate(account)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.credentialService.impersonateAccount(account.id).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
|
||||
duration: 4000,
|
||||
});
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
error: () => {
|
||||
this.snackBar.open(
|
||||
'Impersonation konnte nicht gestartet werden.',
|
||||
'OK',
|
||||
{
|
||||
duration: 5000,
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected get canPageBack(): boolean {
|
||||
return this.page > 0;
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user